@buddysh/buddy 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1633 -0
- package/LICENSE.md +21 -0
- package/README.md +1087 -0
- package/bin/cli.ts +3401 -0
- package/dist/bin/cli.d.ts +1 -0
- package/dist/bin/cli.js +188 -0
- package/dist/chunk-0j7z87kh.js +3 -0
- package/dist/chunk-0r8zt3d7.js +2 -0
- package/dist/chunk-16yqbccr.js +3 -0
- package/dist/chunk-1a53wj0h.js +1 -0
- package/dist/chunk-1c1gznm9.js +3 -0
- package/dist/chunk-1h3ey7k5.js +3 -0
- package/dist/chunk-1stt2whn.js +62 -0
- package/dist/chunk-1wjnd24b.js +24 -0
- package/dist/chunk-1xe07hzm.js +2 -0
- package/dist/chunk-2bp7tqca.js +2 -0
- package/dist/chunk-2dbkpfy9.js +2 -0
- package/dist/chunk-3q6czqs4.js +6 -0
- package/dist/chunk-3zdcekfj.js +5 -0
- package/dist/chunk-49ey79p0.js +5 -0
- package/dist/chunk-4c9m61yd.js +5 -0
- package/dist/chunk-4efbxdjr.js +4 -0
- package/dist/chunk-4f7panqj.js +21 -0
- package/dist/chunk-4hd3rre0.js +2 -0
- package/dist/chunk-4xsq18p3.js +9 -0
- package/dist/chunk-52x8mvh4.js +15 -0
- package/dist/chunk-54sc18p8.js +2 -0
- package/dist/chunk-56q4pwb5.js +3 -0
- package/dist/chunk-5c3qf34r.js +2 -0
- package/dist/chunk-5k40mwd4.js +4 -0
- package/dist/chunk-5kt03hx5.js +2 -0
- package/dist/chunk-63ept76v.js +2 -0
- package/dist/chunk-65b3vq52.js +2 -0
- package/dist/chunk-6d9hmjt8.js +3 -0
- package/dist/chunk-6g1y9yqh.js +3 -0
- package/dist/chunk-6k653r8w.js +2 -0
- package/dist/chunk-6md7qf2g.js +4 -0
- package/dist/chunk-6patq6bw.js +2 -0
- package/dist/chunk-6sgh49z1.js +2 -0
- package/dist/chunk-74pxb991.js +7 -0
- package/dist/chunk-7mgec8kb.js +7 -0
- package/dist/chunk-7tfrww3v.js +2 -0
- package/dist/chunk-7xk28xrv.js +2 -0
- package/dist/chunk-82dv4p13.js +2 -0
- package/dist/chunk-8661pvb8.js +3 -0
- package/dist/chunk-887s0w81.js +2 -0
- package/dist/chunk-8rc6042h.js +4 -0
- package/dist/chunk-9750tenz.js +3 -0
- package/dist/chunk-978wtejw.js +44 -0
- package/dist/chunk-9eqpaxfz.js +2 -0
- package/dist/chunk-9h04nskh.js +8 -0
- package/dist/chunk-9p1xkmjy.js +2 -0
- package/dist/chunk-agdesgzv.js +2 -0
- package/dist/chunk-akffynkc.js +3 -0
- package/dist/chunk-ar01x04a.js +2 -0
- package/dist/chunk-ay43f085.js +2 -0
- package/dist/chunk-bk9bqd5j.js +2 -0
- package/dist/chunk-bm8d40j0.js +69 -0
- package/dist/chunk-bxfc4g2x.js +73 -0
- package/dist/chunk-c3fczawt.js +2 -0
- package/dist/chunk-c9r9nd4t.js +1 -0
- package/dist/chunk-ctsz0ynx.js +3 -0
- package/dist/chunk-czremqk7.js +2 -0
- package/dist/chunk-da3wbh04.js +2 -0
- package/dist/chunk-dat582cg.js +2 -0
- package/dist/chunk-dfesffnr.js +3 -0
- package/dist/chunk-djntbp7a.js +105 -0
- package/dist/chunk-eagjp0dh.js +3 -0
- package/dist/chunk-eht72nnj.js +2 -0
- package/dist/chunk-f4nv5x3z.js +2 -0
- package/dist/chunk-fdfk918n.js +2 -0
- package/dist/chunk-fdj0tewy.js +20 -0
- package/dist/chunk-fm8ckj9b.js +2 -0
- package/dist/chunk-fqj7e6xa.js +2 -0
- package/dist/chunk-frm8zz31.js +2 -0
- package/dist/chunk-fvpr07dn.js +16 -0
- package/dist/chunk-g0nv8psv.js +2 -0
- package/dist/chunk-g0w8n555.js +19 -0
- package/dist/chunk-gkmvxjbe.js +2 -0
- package/dist/chunk-gngwjf70.js +7 -0
- package/dist/chunk-h7hs95wn.js +5 -0
- package/dist/chunk-hfvezfxh.js +3 -0
- package/dist/chunk-hw70wbzg.js +3 -0
- package/dist/chunk-j8asz4hb.js +15 -0
- package/dist/chunk-k62w2v03.js +2 -0
- package/dist/chunk-mcrfxphm.js +5 -0
- package/dist/chunk-mh3x7j6h.js +2 -0
- package/dist/chunk-naq32yx3.js +86 -0
- package/dist/chunk-nsmcjkas.js +2 -0
- package/dist/chunk-p1xm1jvz.js +2 -0
- package/dist/chunk-p3wsm8kz.js +2 -0
- package/dist/chunk-p4zwy518.js +4 -0
- package/dist/chunk-p7zgy37f.js +2 -0
- package/dist/chunk-ph1b3vbp.js +315 -0
- package/dist/chunk-pkjm2r0a.js +2 -0
- package/dist/chunk-pkkwb0n0.js +4 -0
- package/dist/chunk-pnpx1kqn.js +6 -0
- package/dist/chunk-q9n79dd3.js +3 -0
- package/dist/chunk-qpz9k66h.js +2 -0
- package/dist/chunk-qvn1rtgp.js +2 -0
- package/dist/chunk-qyf90zz3.js +2 -0
- package/dist/chunk-r06ce5g6.js +2 -0
- package/dist/chunk-r2sbprdb.js +49 -0
- package/dist/chunk-r3zyw8x0.js +3 -0
- package/dist/chunk-rb1fh9vd.js +1 -0
- package/dist/chunk-rqdep14r.js +2 -0
- package/dist/chunk-s1km8cyq.js +2 -0
- package/dist/chunk-s4ms8zag.js +2 -0
- package/dist/chunk-sp818c27.js +9 -0
- package/dist/chunk-tb5y0350.js +3 -0
- package/dist/chunk-thaxgm5p.js +2 -0
- package/dist/chunk-tn8prpny.js +503 -0
- package/dist/chunk-ts35hc5t.js +3 -0
- package/dist/chunk-tzs22es2.js +3 -0
- package/dist/chunk-vagxqhef.js +13 -0
- package/dist/chunk-vh504tcv.js +6 -0
- package/dist/chunk-vkctfqpm.js +3 -0
- package/dist/chunk-vyapg8ca.js +186 -0
- package/dist/chunk-wdwvt7gb.js +43 -0
- package/dist/chunk-wtjhehz9.js +4 -0
- package/dist/chunk-x0ya2r4r.js +3 -0
- package/dist/chunk-x3kragh9.js +12 -0
- package/dist/chunk-x9ctz1qc.js +1 -0
- package/dist/chunk-xakpdqaq.js +3 -0
- package/dist/chunk-xqx460y2.js +3 -0
- package/dist/chunk-xvptf9jy.js +3 -0
- package/dist/chunk-yk23nc4t.js +2 -0
- package/dist/chunk-yncea6ty.js +2 -0
- package/dist/chunk-yq0gxtzv.js +2 -0
- package/dist/chunk-yqhs08ky.js +2 -0
- package/dist/chunk-zb62jhwm.js +31 -0
- package/dist/chunk-zs3jaj0g.js +1023 -0
- package/dist/chunk-zve5d96e.js +2 -0
- package/dist/src/agent/index.d.ts +44 -0
- package/dist/src/agent/modes.d.ts +33 -0
- package/dist/src/agent/runner.d.ts +44 -0
- package/dist/src/agent/stacked.d.ts +83 -0
- package/dist/src/agent/tasks.d.ts +41 -0
- package/dist/src/agent/toolbelt.d.ts +19 -0
- package/dist/src/agent/tools/fs.d.ts +26 -0
- package/dist/src/agent/tools/shell.d.ts +32 -0
- package/dist/src/agent/types.d.ts +56 -0
- package/dist/src/ai/aliases.d.ts +62 -0
- package/dist/src/ai/client.d.ts +42 -0
- package/dist/src/ai/index.d.ts +35 -0
- package/dist/src/ai/learnings.d.ts +78 -0
- package/dist/src/ai/providers/anthropic.d.ts +12 -0
- package/dist/src/ai/providers/google.d.ts +12 -0
- package/dist/src/ai/providers/openai.d.ts +15 -0
- package/dist/src/ai/redact.d.ts +30 -0
- package/dist/src/ai/types.d.ts +75 -0
- package/dist/src/analysis/analyzers/actionlint.d.ts +11 -0
- package/dist/src/analysis/analyzers/external.d.ts +57 -0
- package/dist/src/analysis/analyzers/github-actions.d.ts +9 -0
- package/dist/src/analysis/analyzers/hadolint.d.ts +9 -0
- package/dist/src/analysis/analyzers/linter.d.ts +53 -0
- package/dist/src/analysis/analyzers/markdownlint.d.ts +11 -0
- package/dist/src/analysis/analyzers/secrets.d.ts +23 -0
- package/dist/src/analysis/analyzers/shellcheck.d.ts +8 -0
- package/dist/src/analysis/analyzers/syntax.d.ts +13 -0
- package/dist/src/analysis/engine.d.ts +38 -0
- package/dist/src/analysis/index.d.ts +13 -0
- package/dist/src/analysis/types.d.ts +14 -0
- package/dist/src/buddy.d.ts +17 -0
- package/dist/src/ci/classify.d.ts +49 -0
- package/dist/src/ci/fix.d.ts +42 -0
- package/dist/src/ci/index.d.ts +8 -0
- package/dist/src/commands/dispatcher.d.ts +49 -0
- package/dist/src/commands/handlers.d.ts +23 -0
- package/dist/src/commands/index.d.ts +22 -0
- package/dist/src/commands/parser.d.ts +71 -0
- package/dist/src/config-validation.d.ts +38 -0
- package/dist/src/config.d.ts +22 -0
- package/dist/src/dashboard/dashboard-generator.d.ts +10 -0
- package/dist/src/doctor.d.ts +44 -0
- package/dist/src/ecosystems/go.d.ts +10 -0
- package/dist/src/ecosystems/index.d.ts +60 -0
- package/dist/src/ecosystems/pep440.d.ts +57 -0
- package/dist/src/ecosystems/python.d.ts +12 -0
- package/dist/src/ecosystems/ruby.d.ts +9 -0
- package/dist/src/ecosystems/rust.d.ts +8 -0
- package/dist/src/ecosystems/scan.d.ts +49 -0
- package/dist/src/ecosystems/shared.d.ts +45 -0
- package/dist/src/ecosystems/types.d.ts +58 -0
- package/dist/src/events/bus.d.ts +41 -0
- package/dist/src/events/index.d.ts +11 -0
- package/dist/src/events/sinks.d.ts +33 -0
- package/dist/src/gates/ai-checks.d.ts +77 -0
- package/dist/src/gates/checks.d.ts +84 -0
- package/dist/src/gates/index.d.ts +17 -0
- package/dist/src/gates/post-merge.d.ts +56 -0
- package/dist/src/git/bitbucket-provider.d.ts +50 -0
- package/dist/src/git/github-provider.d.ts +50 -0
- package/dist/src/git/gitlab-provider.d.ts +51 -0
- package/dist/src/git/provider.d.ts +210 -0
- package/dist/src/headless/run.d.ts +78 -0
- package/dist/src/index.d.ts +243 -0
- package/dist/src/index.js +2 -0
- package/dist/src/issues/enrichment.d.ts +76 -0
- package/dist/src/issues/index.d.ts +16 -0
- package/dist/src/issues/quick-links.d.ts +55 -0
- package/dist/src/pr/auto-merge.d.ts +75 -0
- package/dist/src/pr/pr-generator.d.ts +9 -0
- package/dist/src/pr/pr-manifest.d.ts +82 -0
- package/dist/src/pr/templates.d.ts +44 -0
- package/dist/src/registry/docker-tags.d.ts +56 -0
- package/dist/src/registry/eol.d.ts +87 -0
- package/dist/src/registry/oci-client.d.ts +98 -0
- package/dist/src/registry/registry-client.d.ts +39 -0
- package/dist/src/reports/history.d.ts +51 -0
- package/dist/src/reports/index.d.ts +23 -0
- package/dist/src/reports/metrics.d.ts +89 -0
- package/dist/src/reports/render.d.ts +33 -0
- package/dist/src/review/diff.d.ts +50 -0
- package/dist/src/review/engine.d.ts +49 -0
- package/dist/src/review/findings.d.ts +102 -0
- package/dist/src/review/guidelines.d.ts +46 -0
- package/dist/src/review/index.d.ts +48 -0
- package/dist/src/review/local.d.ts +81 -0
- package/dist/src/review/marker.d.ts +34 -0
- package/dist/src/review/poster.d.ts +39 -0
- package/dist/src/review/run.d.ts +24 -0
- package/dist/src/rules/engine.d.ts +108 -0
- package/dist/src/rules/index.d.ts +9 -0
- package/dist/src/rules/renovate.d.ts +25 -0
- package/dist/src/rules/schedule.d.ts +44 -0
- package/dist/src/scanner/catalog-scan.d.ts +39 -0
- package/dist/src/scanner/package-json-extras.d.ts +101 -0
- package/dist/src/scanner/package-scanner.d.ts +17 -0
- package/dist/src/scanner/resolution-drift.d.ts +81 -0
- package/dist/src/scanner/workspace-catalog.d.ts +53 -0
- package/dist/src/scheduler/scheduler.d.ts +27 -0
- package/dist/src/security/engine.d.ts +12 -0
- package/dist/src/security/loader.d.ts +7 -0
- package/dist/src/security/parser.d.ts +15 -0
- package/dist/src/security/rules/bash-injection.d.ts +18 -0
- package/dist/src/security/rules/dangerous-pull-request-target.d.ts +18 -0
- package/dist/src/security/rules/excessive-permissions.d.ts +14 -0
- package/dist/src/security/rules/index.d.ts +16 -0
- package/dist/src/security/rules/missing-timeout.d.ts +9 -0
- package/dist/src/security/rules/self-hosted-exposure.d.ts +13 -0
- package/dist/src/security/rules/unpinned-action.d.ts +10 -0
- package/dist/src/security/rules/walk.d.ts +13 -0
- package/dist/src/security/types.d.ts +64 -0
- package/dist/src/services/deprecated-dependencies-checker.d.ts +16 -0
- package/dist/src/services/release-notes-fetcher.d.ts +70 -0
- package/dist/src/services/security-advisories.d.ts +59 -0
- package/dist/src/setup.d.ts +162 -0
- package/dist/src/setup.js +2 -0
- package/dist/src/templates/github-actions.d.ts +31 -0
- package/dist/src/templates/gitlab-ci.d.ts +46 -0
- package/dist/src/types.d.ts +449 -0
- package/dist/src/upgrades/index.d.ts +18 -0
- package/dist/src/upgrades/migrate.d.ts +45 -0
- package/dist/src/upgrades/plan.d.ts +112 -0
- package/dist/src/upgrades/report.d.ts +22 -0
- package/dist/src/upgrades/span.d.ts +47 -0
- package/dist/src/upgrades/usage.d.ts +30 -0
- package/dist/src/upgrades/wire.d.ts +61 -0
- package/dist/src/utils/concurrency.d.ts +50 -0
- package/dist/src/utils/dependency-file-parser.d.ts +17 -0
- package/dist/src/utils/dockerfile-parser.d.ts +69 -0
- package/dist/src/utils/endpoints.d.ts +58 -0
- package/dist/src/utils/errors.d.ts +35 -0
- package/dist/src/utils/file-changes.d.ts +14 -0
- package/dist/src/utils/github-actions-parser.d.ts +21 -0
- package/dist/src/utils/globs.d.ts +22 -0
- package/dist/src/utils/helpers.d.ts +73 -0
- package/dist/src/utils/http.d.ts +81 -0
- package/dist/src/utils/lock-file.d.ts +28 -0
- package/dist/src/utils/logger.d.ts +45 -0
- package/dist/src/utils/package-paths.d.ts +6 -0
- package/dist/src/utils/pantry-parser.d.ts +30 -0
- package/dist/src/utils/repository.d.ts +41 -0
- package/dist/src/utils/security-format.d.ts +18 -0
- package/dist/src/utils/zig-parser.d.ts +18 -0
- package/dist/src/version/version-resolver.d.ts +9 -0
- package/package.json +115 -0
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{De as l}from"./chunk-6md7qf2g.js";import{Oe as c,Xe as A}from"./chunk-978wtejw.js";import{Ui as y}from"./chunk-7mgec8kb.js";import{Bj as k}from"./chunk-5k40mwd4.js";import{Rj as i}from"./chunk-akffynkc.js";import u from"process";var d=/\{([a-z_]+)\}/gi,b={title:"title",message:"message",group:"group",count:"count",strategy:"strategy",update_type:"updateType",updateType:"updateType",packages:"packages",updates_table:"updatesTable",release_notes:"releaseNotes",footer:"footer",package_count:"packageCount"};function C(W,$){return W.replace(d,(Y,R)=>{let K=b[R]??b[R.toLowerCase()];if(!K)return Y;let H=$[K];return H===void 0?Y:String(H)})}function f(W,$={},Y){return{...$,group:W.name,count:W.updates.length,packageCount:W.updates.length,updateType:W.updateType,packages:W.updates.map((R)=>R.name).join(", "),...Y?{strategy:Y}:{}}}class p{config;releaseNotesFetcher=new l;verbose=!1;logger;constructor(W,$){this.config=W;this.verbose=W?.verbose||u.env.BUDDY_VERBOSE==="true",this.logger=$??i()}get releaseNotesSettings(){let W=this.config?.releaseNotes;return{enabled:W?.enabled??!0,maxReleases:W?.maxReleases??3,maxBodyLength:W?.maxBodyLength??1000,includeCompareLinks:W?.includeCompareLinks??!0}}repositoryFileUrl(W){let $=k(this.config),{owner:Y,name:R,baseBranch:K}=this.config?.repository??{};return`${$}/${Y}/${R}/blob/${K||"main"}/${W}`}log(W,$){if(this.verbose){let Y=new Date().toISOString();if(this.logger.info(`[${Y}] PR-GEN: ${W}`),$)this.logger.info(JSON.stringify($,null,2))}}async generatePullRequests(W){let $=[];for(let Y of W){let R=this.generateTitle(Y),K=await this.generateBody(Y),H={number:0,title:R,body:K,head:`buddy/update-${Y.name.toLowerCase().replace(/\s+/g,"-")}`,base:"main",state:"open",url:"",createdAt:new Date,updatedAt:new Date,author:"github-actions[bot]",reviewers:[],assignees:[],labels:this.generateLabels(Y),draft:!1};$.push(H)}return $}generateLabels(W){let $=["dependencies"];if(W.updateType==="major")$.push("major");else if(W.updateType==="minor")$.push("minor");else if(W.updateType==="patch")$.push("patch");let Y=W.updates.filter((B)=>B.file==="package.json"||B.file.endsWith("/package.json")||B.file.endsWith("\\package.json")).length,R=W.updates.filter((B)=>B.file.endsWith("composer.json")||B.file.endsWith("composer.lock")).length,K=W.updates.filter((B)=>B.file.endsWith("build.zig.zon")).length,H=W.updates.filter((B)=>(B.file.includes(".yaml")||B.file.includes(".yml"))&&!B.file.includes(".github/workflows/")).length,Z=W.updates.filter((B)=>B.file.includes(".github/workflows/")).length;if(Y>0)$.push("npm");if(R>0)$.push("composer");if(K>0)$.push("zig");if(H>0)$.push("system");if(Z>0)$.push("github-actions");if(W.updates.length===1){let B=W.updates[0];$.push(B.name)}return $}generateTitle(W){let $=this.config?.pullRequest?.titleFormat;if($)return C($,f(W,{title:this.defaultTitle(W)},this.config?.packages?.strategy));return this.defaultTitle(W)}defaultTitle(W){if(W.updates.length===1){let R=W.updates[0];return`chore(deps): update dependency ${R.name} to v${R.newVersion}`}let $=W.updates.filter((R)=>R.updateType==="major").length,Y=W.updates.filter((R)=>R.updateType==="minor").length;if($>0)return`chore(deps): update ${W.updates.length} dependencies (major)`;else if(Y>0)return`chore(deps): update ${W.updates.length} dependencies (minor)`;else return`chore(deps): update ${W.updates.length} dependencies (patch)`}async generateBody(W){if(this.log("\uD83D\uDE80 Starting PR body generation",{groupName:W.name,totalUpdates:W.updates.length,updates:W.updates.map((Q)=>({name:Q.name,file:Q.file,dependencyType:Q.dependencyType,currentVersion:Q.currentVersion,newVersion:Q.newVersion,updateType:Q.updateType}))}),W.updates.length===0)this.log("\u26A0\uFE0F WARNING: No updates in group - this will result in sparse PR body",{groupName:W.name,groupTitle:W.title});let $=W.updates.filter((Q)=>Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")).length,Y=W.updates.filter((Q)=>(Q.file.includes(".yaml")||Q.file.includes(".yml"))&&!Q.file.includes(".github/workflows/")).length,R=W.updates.filter((Q)=>Q.file.includes(".github/workflows/")).length,K=W.updates.filter((Q)=>Q.file.endsWith("composer.json")||Q.file.endsWith("composer.lock")).length,H=W.updates.filter((Q)=>Q.file.endsWith("build.zig.zon")).length;if(this.log("\uD83D\uDCCA Package type counts",{packageJsonCount:$,dependencyFileCount:Y,githubActionsCount:R,composerCount:K,total:W.updates.length}),W.updates.length>0)this.log("\uD83D\uDD0D File path analysis",{files:W.updates.map((Q)=>({name:Q.name,file:Q.file,isExactMatch:Q.file==="package.json",endsWithSlash:Q.file.endsWith("/package.json"),endsWithBackslash:Q.file.endsWith("\\package.json"),matchesAny:Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")}))});let Z=`This PR contains the following updates:
|
|
3
|
+
|
|
4
|
+
`;Z+=c(W.updates);let B=W.updates.length>1;if(B){if(Z+=`## Package Updates Summary
|
|
5
|
+
|
|
6
|
+
`,Z+=`| Type | Count |
|
|
7
|
+
`,Z+=`|------|-------|
|
|
8
|
+
`,$>0)Z+=`| \uD83D\uDCE6 NPM Packages | ${$} |
|
|
9
|
+
`;if(Y>0)Z+=`| \uD83D\uDD27 System Dependencies | ${Y} |
|
|
10
|
+
`;if(R>0)Z+=`| \uD83D\uDE80 GitHub Actions | ${R} |
|
|
11
|
+
`;if(K>0)Z+=`| \uD83D\uDC18 Composer Packages | ${K} |
|
|
12
|
+
`;if(H>0)Z+=`| \u26A1 Zig Packages | ${H} |
|
|
13
|
+
`;Z+=`| **Total** | **${W.updates.length}** |
|
|
14
|
+
|
|
15
|
+
`}let E=W.updates.filter((Q)=>Q.file==="package.json"||Q.file.endsWith("/package.json")||Q.file.endsWith("\\package.json")),x=W.updates.filter((Q)=>Q.file.endsWith("composer.json")||Q.file.endsWith("composer.lock")),q=W.updates.filter((Q)=>Q.file.endsWith("build.zig.zon")),S=W.updates.filter((Q)=>Q.file.includes(".yaml")||Q.file.includes(".yml")).filter((Q)=>!Q.file.includes(".github/workflows/")),P=W.updates.filter((Q)=>Q.file.includes(".github/workflows/"));this.log("\uD83D\uDCDD Filtered updates by type",{packageJsonUpdates:{count:E.length,items:E.map((Q)=>({name:Q.name,file:Q.file}))},composerUpdates:{count:x.length,items:x.map((Q)=>({name:Q.name,file:Q.file}))},dependencyFileUpdates:{count:S.length,items:S.map((Q)=>({name:Q.name,file:Q.file}))},githubActionsUpdates:{count:P.length,items:P.map((Q)=>({name:Q.name,file:Q.file}))}});let T=new Map;for(let Q of P){let X=`${Q.name}@${Q.currentVersion}=>${Q.newVersion}`,D=T.get(X);if(D)D.files.add(Q.file);else T.set(X,{update:Q,files:new Set([Q.file])})}let V=Array.from(T.values()).map(({update:Q,files:X})=>({...Q,file:Array.from(X).join(", ")})),U=new Set,w=[];for(let Q of x){let X=`${Q.name}@${Q.currentVersion}=>${Q.newVersion}`;if(!U.has(X))U.add(X),w.push(Q)}let F=new Map,m=new Map;if(E.length>0){if(this.log("\u2705 Generating npm Dependencies section",{packageCount:E.length,packages:E.map((_)=>_.name)}),B||$<W.updates.length)Z+=`## \uD83D\uDCE6 npm Dependencies
|
|
16
|
+
|
|
17
|
+
`;if(Z+=`
|
|
18
|
+
|
|
19
|
+
`,E.length>1)Z+=`*${E.length} packages will be updated*
|
|
20
|
+
|
|
21
|
+
`;Z+=`| Package | Change | Age | Adoption | Passing | Confidence |
|
|
22
|
+
`,Z+=`|---|---|---|---|---|---|
|
|
23
|
+
`;let Q=Date.now();this.log(`\u23F1\uFE0F Starting to fetch info for ${E.length} npm packages in parallel...`);let X=(this.releaseNotesSettings.enabled?E:[]).map(async(_)=>{let M=Date.now();try{let L=_.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,""),j=await this.releaseNotesFetcher.fetchPackageInfo(L,_.currentVersion,_.newVersion);return this.log(`\u23F1\uFE0F Fetched ${L} in ${Date.now()-M}ms`),{name:_.name,result:j}}catch(L){return this.logger.warn(`Failed to fetch info for ${_.name}:`,L),null}});(await Promise.all(X)).forEach((_)=>{if(_)F.set(_.name,_.result)});let O=Date.now()-Q;this.log(`\u23F1\uFE0F Total npm package info fetch took ${O}ms for ${E.length} packages (avg: ${Math.round(O/E.length)}ms per package)`),this.logger.info(`\u23F1\uFE0F [PR-GEN] npm package info fetch: ${O}ms for ${E.length} packages (PARALLEL)`);for(let _ of E){let L=F.get(_.name)?.packageInfo||{name:_.name},j=_.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,""),z;if(L.repository?.url){let J=this.getRepositorySourceUrl(L.repository.url,j),h=this.getRepositorySourceUrl(L.repository.url,j,"HEAD");z=`[${j}](${J}) ([source](${h}))`}else if(j.startsWith("@types/")){let J=j.replace("@types/",""),h=`https://redirect.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/${J}`,r=`https://redirect.github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/${J}`;z=`[${j}](${h}) ([source](${r}))`}else z=`[${j}](https://www.npmjs.com/package/${encodeURIComponent(j)})`;let v=`https://renovatebot.com/diffs/npm/${encodeURIComponent(j)}/${encodeURIComponent(_.currentVersion)}/${encodeURIComponent(_.newVersion)}`,g=this.escapeMarkdownTableValue(_.currentVersion),s=this.escapeMarkdownTableValue(_.newVersion),n=`[\`${g}\` -> \`${s}\`](${v})`,I=this.releaseNotesFetcher.generatePackageBadges({...L,name:j},_.currentVersion,_.newVersion);Z+=`| ${z} | ${n} | ${I.age} | ${I.adoption} | ${I.passing} | ${I.confidence} |
|
|
24
|
+
`}Z+=`
|
|
25
|
+
`}if(w.length>0){for(let Q of w)try{let X=await this.releaseNotesFetcher.fetchComposerPackageInfo(Q.name);m.set(Q.name,X)}catch(X){this.logger.warn(`Failed to fetch Composer info for ${Q.name}:`,X)}if(B||K<W.updates.length)Z+=`## \uD83D\uDC18 PHP/Composer Dependencies
|
|
26
|
+
|
|
27
|
+
`;if(Z+=`
|
|
28
|
+
|
|
29
|
+
`,w.length>1)Z+=`*${w.length} packages will be updated*
|
|
30
|
+
|
|
31
|
+
`;Z+=`| Package | Change | Age | Adoption | Passing | Confidence | Type | Update |
|
|
32
|
+
`,Z+=`|---|---|---|---|---|---|---|---|
|
|
33
|
+
`;for(let Q of w){let X=m.get(Q.name)||{name:Q.name},D;if(X.homepage&&X.repository?.url){let v=this.getComposerRedirectSourceUrl(X.repository.url,Q.name);D=`[${Q.name}](${X.homepage}) ([source](${v}))`}else if(X.repository?.url){let v=this.getComposerRedirectSourceUrl(X.repository.url,Q.name);D=`[${Q.name}](${v})`}else D=`[${Q.name}](https://packagist.org/packages/${encodeURIComponent(Q.name)})`;let O=this.getConstraintStyleChange(Q.currentVersion,Q.newVersion),_=`https://renovatebot.com/diffs/packagist/${encodeURIComponent(Q.name)}/${Q.currentVersion}/${Q.newVersion}`,M=`[\`${O}\`](${_})`,L=this.releaseNotesFetcher.generateComposerBadges(X,Q.currentVersion,Q.newVersion),j=Q.dependencyType||"require",z=Q.updateType||"minor";Z+=`| ${D} | ${M} | ${L.age} | ${L.adoption} | ${L.passing} | ${L.confidence} | ${j} | ${z} |
|
|
34
|
+
`}Z+=`
|
|
35
|
+
`}if(q.length>0){if(B||H<W.updates.length)Z+=`## \u26A1 Zig Dependencies
|
|
36
|
+
|
|
37
|
+
`;if(Z+=`
|
|
38
|
+
|
|
39
|
+
`,q.length>1)Z+=`*${q.length} packages will be updated*
|
|
40
|
+
|
|
41
|
+
`;Z+=`| Package | Change | Type | File |
|
|
42
|
+
`,Z+=`|---|---|---|---|
|
|
43
|
+
`;for(let Q of q){let X,D=Q.metadata;if(D?.url){let z=D.url.match(/https?:\/\/github\.com\/([^/]+\/[^/]+)/);if(z){let v=`https://github.com/${z[1]}`;X=`[${Q.name}](${v})`}else X=Q.name}else X=Q.name;let O=A(Q.currentVersion,Q.newVersion),_=O==="major"?"\uD83D\uDD34":O==="minor"?"\uD83D\uDFE1":"\uD83D\uDFE2",M=this.formatVersionChange(Q.currentVersion,Q.newVersion),L=Q.file.split("/").pop()||Q.file,j=this.config?.repository?.owner&&this.config?.repository?.name?`[\`${L}\`](${this.repositoryFileUrl(Q.file)})`:`\`${L}\``;Z+=`| ${X} | ${M} | ${_} ${O} | ${j} |
|
|
44
|
+
`}Z+=`
|
|
45
|
+
`}if(S.length>0){if(B||Y<W.updates.length)Z+=`## \uD83D\uDD27 System Dependencies
|
|
46
|
+
|
|
47
|
+
`;Z+=`
|
|
48
|
+
|
|
49
|
+
`;let Q=[...new Set(S.map((X)=>X.file))];if(S.length>1)Z+=`*${S.length} packages will be updated across ${Q.length} file(s): ${Q.map((X)=>`\`${X.split("/").pop()}\``).join(", ")}*
|
|
50
|
+
|
|
51
|
+
`;Z+=`| Package | Change | Type | File |
|
|
52
|
+
`,Z+=`|---|---|---|---|
|
|
53
|
+
`;for(let X of S){let D=X.name==="bun.sh"?"bun.com":X.name,O=X.name==="bun.sh"?"https://bun.sh":`https://pkgx.com/pkg/${encodeURIComponent(X.name)}`,_=`[${D}](${O})`,M=A(X.currentVersion,X.newVersion),L=M==="major"?"\uD83D\uDD34":M==="minor"?"\uD83D\uDFE1":"\uD83D\uDFE2",j=this.formatVersionChange(X.currentVersion,X.newVersion),z=X.file.split("/").pop()||X.file,v=this.config?.repository?.owner&&this.config?.repository?.name?`[\`${z}\`](${this.repositoryFileUrl(X.file)})`:`\`${z}\``;Z+=`| ${_} | ${j} | ${L} ${M} | ${v} |
|
|
54
|
+
`}Z+=`
|
|
55
|
+
`}if(V.length>0){if(B||R<W.updates.length)Z+=`## \uD83D\uDE80 GitHub Actions
|
|
56
|
+
|
|
57
|
+
`;if(Z+=`
|
|
58
|
+
|
|
59
|
+
`,V.length>1)Z+=`*${V.length} actions will be updated*
|
|
60
|
+
|
|
61
|
+
`;Z+=`| Action | Change | Type | Files |
|
|
62
|
+
`,Z+=`|---|---|---|---|
|
|
63
|
+
`;for(let Q of V){let X=`${k(this.config)}/${Q.name}`,D=`[${Q.name}](${X})`,O=A(Q.currentVersion,Q.newVersion),_=O==="major"?"\uD83D\uDD34":O==="minor"?"\uD83D\uDFE1":"\uD83D\uDFE2",M=this.formatVersionChange(Q.currentVersion,Q.newVersion),L=Q.file.includes(", ")?Q.file.split(", ").map((j)=>{let z=j.split("/").pop()||j;return this.config?.repository?.owner&&this.config?.repository?.name?`[\`${z}\`](${this.repositoryFileUrl(j)})`:`\`${z}\``}).join(", "):(()=>{let j=Q.file.split("/").pop()||Q.file;return this.config?.repository?.owner&&this.config?.repository?.name?`[\`${j}\`](${this.repositoryFileUrl(Q.file)})`:`\`${j}\``})();Z+=`| ${D} | ${M} | ${_} ${O} | ${L} |
|
|
64
|
+
`}Z+=`
|
|
65
|
+
`}Z+=`
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
`;let G=this.releaseNotesSettings;if(!G.enabled)return this.finalizeBody(Z,W);Z+=`### Release Notes
|
|
69
|
+
|
|
70
|
+
`;for(let Q of E){let X=F.get(Q.name),D=X?.packageInfo||{name:Q.name},O=X?.releaseNotes||[],_=X?.compareUrl;Z+=`<details>
|
|
71
|
+
`;let M,L=Q.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,"");if(D.repository?.url)M=`${this.getRepositoryName(D.repository.url)} (${L})`;else M=L;if(Z+=`<summary>${M}</summary>
|
|
72
|
+
|
|
73
|
+
`,Z+=`**${Q.currentVersion} -> ${Q.newVersion}**
|
|
74
|
+
|
|
75
|
+
`,O.length>0)for(let j of O.slice(0,G.maxReleases)){if(Z+=`### [\`${j.version}\`](${j.htmlUrl})
|
|
76
|
+
|
|
77
|
+
`,_&&G.includeCompareLinks)Z+=`[Compare Source](${_})
|
|
78
|
+
|
|
79
|
+
`;if(j.body){let z=this.cleanReleaseBody(j.body);Z+=`${z}
|
|
80
|
+
|
|
81
|
+
`}if(j.author)Z+=`*Released by [${j.author}](https://github.com/${j.author}) on ${new Date(j.date).toLocaleDateString()}*
|
|
82
|
+
|
|
83
|
+
`}else{if(_&&G.includeCompareLinks)Z+=`[Compare Source](${_})
|
|
84
|
+
|
|
85
|
+
`;if(D.description)Z+=`${D.description}
|
|
86
|
+
|
|
87
|
+
`;if(D.repository?.url){let j=this.getRepositoryName(D.repository.url);if(j)Z+=`\uD83D\uDCD6 [View Release Notes](https://github.com/${j}/releases)
|
|
88
|
+
|
|
89
|
+
`,Z+=`\uD83D\uDD17 [View Changelog](https://github.com/${j}/blob/main/CHANGELOG.md)
|
|
90
|
+
|
|
91
|
+
`}else Z+=`\uD83D\uDCE6 [View on npm](https://www.npmjs.com/package/${encodeURIComponent(L)})
|
|
92
|
+
|
|
93
|
+
`;if(Q.releaseNotesUrl)Z+=`[Release Notes](${Q.releaseNotesUrl})
|
|
94
|
+
|
|
95
|
+
`;if(Q.changelogUrl)Z+=`[Changelog](${Q.changelogUrl})
|
|
96
|
+
|
|
97
|
+
`}Z+=`</details>
|
|
98
|
+
|
|
99
|
+
`}let N=S.filter((Q)=>!E.some((X)=>X.name.replace(/\s*\(dev\)$/,"").replace(/\s*\(peer\)$/,"").replace(/\s*\(optional\)$/,"")===Q.name));for(let Q of N){let X=Q.name==="bun.sh"?"bun.com":Q.name;Z+=`<details>
|
|
100
|
+
`,Z+=`<summary>${X}</summary>
|
|
101
|
+
|
|
102
|
+
`;let D=this.formatVersionChange(Q.currentVersion,Q.newVersion).replace(/`/g,"");if(Z+=`**${D}**
|
|
103
|
+
|
|
104
|
+
`,Q.file){let O=Q.file.split("/").pop()||Q.file,_=this.config?.repository?.owner&&this.config?.repository?.name?`\uD83D\uDCC1 **File**: [\`${O}\`](https://github.com/${this.config.repository.owner}/${this.config.repository.name}/blob/main/${Q.file})
|
|
105
|
+
|
|
106
|
+
`:`\uD83D\uDCC1 **File**: \`${O}\`
|
|
107
|
+
|
|
108
|
+
`;Z+=_}if(Q.name==="bun.sh")Z+=`\uD83D\uDD17 **Release Notes**: [bun.sh](https://bun.sh)
|
|
109
|
+
|
|
110
|
+
`;else if(Q.name.includes(".org")||Q.name.includes(".net")||Q.name.includes(".com")){let O=Q.name.split("/")[0]||Q.name;Z+=`\uD83D\uDD17 **Package Info**: [pkgx.com](https://pkgx.com/pkg/${encodeURIComponent(Q.name)})
|
|
111
|
+
|
|
112
|
+
`,Z+=`\uD83C\uDF10 **Official Site**: [${O}](https://${O})
|
|
113
|
+
|
|
114
|
+
`}else Z+=`\uD83D\uDD17 **Package Info**: [pkgx.com](https://pkgx.com/pkg/${encodeURIComponent(Q.name)})
|
|
115
|
+
|
|
116
|
+
`;Z+=`</details>
|
|
117
|
+
|
|
118
|
+
`}for(let Q of w){Z+=`<details>
|
|
119
|
+
`,Z+=`<summary>${Q.name}</summary>
|
|
120
|
+
|
|
121
|
+
`;let X=this.formatVersionChange(Q.currentVersion,Q.newVersion).replace(/`/g,"");Z+=`**${X}**
|
|
122
|
+
|
|
123
|
+
`,Z+=`Visit [${Q.name}](https://packagist.org/packages/${encodeURIComponent(Q.name)}) on Packagist for more information.
|
|
124
|
+
|
|
125
|
+
`,Z+=`</details>
|
|
126
|
+
|
|
127
|
+
`}for(let Q of V){Z+=`<details>
|
|
128
|
+
`,Z+=`<summary>${Q.name}</summary>
|
|
129
|
+
|
|
130
|
+
`;let X=this.formatVersionChange(Q.currentVersion,Q.newVersion).replace(/`/g,"");Z+=`**${X}**
|
|
131
|
+
|
|
132
|
+
`,Z+=`Visit [${Q.name}](https://github.com/${Q.name}/releases) for release notes.
|
|
133
|
+
|
|
134
|
+
`,Z+=`</details>
|
|
135
|
+
|
|
136
|
+
`}if(Z+=`---
|
|
137
|
+
|
|
138
|
+
`,F.size>0||w.length>0||N.length>0||V.length>0){Z+=`### \uD83D\uDCCA Package Statistics
|
|
139
|
+
|
|
140
|
+
`;for(let Q of E){let D=F.get(Q.name)?.packageInfo;if(D?.weeklyDownloads)Z+=`- **${Q.name}**: ${D.weeklyDownloads.toLocaleString()} weekly downloads
|
|
141
|
+
`;else Z+=`- **${Q.name}**: npm package with weekly downloads tracked on npmjs.com
|
|
142
|
+
`}for(let Q of w)Z+=`- **${Q.name}**: PHP package available on Packagist
|
|
143
|
+
`;for(let Q of N){let X=Q.name==="bun.sh"?"bun.com":Q.name;if(Q.name==="bun.sh")Z+=`- **${X}**: Popular JavaScript runtime and package manager
|
|
144
|
+
`;else Z+=`- **${X}**: Available via pkgx package manager
|
|
145
|
+
`}for(let Q of V)Z+=`- **${Q.name}**: GitHub Action for workflow automation
|
|
146
|
+
`;Z+=`
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
`}return this.finalizeBody(Z,W)}finalizeBody(W,$){let Y=this.config?.pullRequest?.bodyTemplate,R=" - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box";if(Y){if(W=C(Y,{...f($,{},this.config?.packages?.strategy),updatesTable:W,footer:" - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box"}),!W.includes("<!-- rebase-check -->"))W+=`
|
|
150
|
+
|
|
151
|
+
- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box
|
|
152
|
+
`}else{W+=`### Configuration
|
|
153
|
+
|
|
154
|
+
`,W+=`\uD83D\uDCC5 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).
|
|
155
|
+
|
|
156
|
+
`,W+=`\uD83D\uDEA6 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.
|
|
157
|
+
|
|
158
|
+
`,W+=`\u267B **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.
|
|
159
|
+
|
|
160
|
+
`;let Z=$.updates.length===1?"this update again":"these updates again";W+=`\uD83D\uDD15 **Ignore**: Close this PR and you won't be reminded about ${Z}.
|
|
161
|
+
|
|
162
|
+
`,W+=`---
|
|
163
|
+
|
|
164
|
+
`,W+=` - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box
|
|
165
|
+
|
|
166
|
+
`,W+=`---
|
|
167
|
+
|
|
168
|
+
`,W+="This PR was generated by [Buddy](https://github.com/stacksjs/buddy) \uD83E\uDD16"}let K=y($),H=60000-K.length;if(W.length>H){let Z=W.substring(0,H),B=Z.lastIndexOf("</details>");if(B>0)W=`${Z.substring(0,B+10)}
|
|
169
|
+
|
|
170
|
+
---
|
|
171
|
+
|
|
172
|
+
**Note**: This PR body was truncated due to GitHub's character limit. View the full details in the individual commits.
|
|
173
|
+
|
|
174
|
+
`;else W=`${Z}
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
**Note**: This PR body was truncated due to GitHub's character limit.
|
|
179
|
+
|
|
180
|
+
`;W+="This PR was generated by [Buddy](https://github.com/stacksjs/buddy) \uD83E\uDD16"}if(W+=K,this.log("\u2705 PR body generation complete",{bodyLength:W.length,hasNpmSection:W.includes("## \uD83D\uDCE6 npm Dependencies"),hasComposerSection:W.includes("## \uD83D\uDC18 PHP/Composer Dependencies"),hasSystemSection:W.includes("## \uD83D\uDD27 System Dependencies"),hasGitHubActionsSection:W.includes("## \uD83D\uDE80 GitHub Actions"),hasPackageTable:W.includes("| Package | Change | Age | Adoption | Passing | Confidence |"),hasReleaseNotes:W.includes("### Release Notes"),isSparse:W.length<1000,sections:{hasNpmPackagesInSummary:W.includes("\uD83D\uDCE6 NPM Packages"),hasComposerInSummary:W.includes("\uD83D\uDC18 Composer Packages"),hasSystemInSummary:W.includes("\uD83D\uDD27 System Dependencies"),hasGitHubActionsInSummary:W.includes("\uD83D\uDE80 GitHub Actions")}}),W.length<1000)this.log("\uD83D\uDEA8 WARNING: Generated PR body appears sparse (under 1000 chars)!");return W}getRepositoryName(W){try{let $=W.replace(/^git\+/,"").replace(/\.git$/,"").replace(/^git:\/\//,"https://").replace(/^ssh:\/\/git@/,"https://").replace(/^git@github\.com:/,"https://github.com/"),R=new URL($).pathname.split("/").filter(Boolean);if(R.length>=2)return`${R[0]}/${R[1]}`;return W}catch{return W}}getRepositorySourceUrl(W,$,Y="master"){try{let R=W.replace(/^git\+/,"").replace(/\.git$/,"").replace(/^git:\/\//,"https://").replace(/^ssh:\/\/git@/,"https://").replace(/^git@github\.com:/,"https://github.com/"),K=new URL(R);if($.startsWith("@types/")&&K.pathname.includes("DefinitelyTyped")){let H=$.replace("@types/","");return`https://redirect.github.com/DefinitelyTyped/DefinitelyTyped/tree/${Y}/types/${H}`}if(K.hostname==="github.com")return`${R}/tree/${Y}`;return R}catch{return W}}getComposerSourceUrl(W,$){try{let Y=W.replace(/^git\+/,"").replace(/\.git$/,"").replace(/^git:\/\//,"https://").replace(/^ssh:\/\/git@/,"https://").replace(/^git@github\.com:/,"https://github.com/"),R=new URL(Y);if($.startsWith("@types/")&&R.pathname.includes("DefinitelyTyped"))return`https://redirect.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/${$.replace("@types/","")}`;if(R.hostname==="github.com")return`${Y}/tree/master`;return Y}catch{return W}}getConstraintStyleChange(W,$){let Y=W.replace(/^v/,""),R=$.replace(/^v/,""),K=`^${Y}`,H=`^${R}`;return`${K} -> ${H}`}escapeMarkdownTableValue(W){return W.replaceAll("|","\\|").replaceAll(/\r?\n/g," ")}getComposerRedirectSourceUrl(W,$){try{let Y=W.replace(/^git\+/,"").replace(/\.git$/,"").replace(/^git:\/\//,"https://").replace(/^ssh:\/\/git@/,"https://").replace(/^git@github\.com:/,"https://github.com/"),R=new URL(Y);if($.startsWith("@types/")&&R.pathname.includes("DefinitelyTyped"))return`https://redirect.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/${$.replace("@types/","")}`;if(R.hostname==="github.com"){let K=R.pathname.split("/").filter((H)=>H);if(K.length>=2){let H=K[0],Z=K[1];return`https://redirect.github.com/${H}/${Z}`}}return Y}catch{return W}}cleanReleaseBody(W){let $=W.replace(/\r\n/g,`
|
|
181
|
+
`).replace(/\n{3,}/g,`
|
|
182
|
+
|
|
183
|
+
`).trim();$=this.sanitizeMentions($),$=this.sanitizeGitHubReferences($);let Y=this.config?.releaseNotes?.maxBodyLength??1000;if($.length>Y)$=`${$.substring(0,Y)}...
|
|
184
|
+
|
|
185
|
+
*[View full release notes]*`;return $}sanitizeMentions(W){let $=[],Y=[],R=W.replace(/```[\s\S]*?```/g,(K)=>{return $.push(K),`__FENCE_PLACEHOLDER_${$.length-1}__`});return R=R.replace(/`[^`\n]+`/g,(K)=>{return Y.push(K),`__INLINE_CODE_PLACEHOLDER_${Y.length-1}__`}),R=R.replace(/(?<![\w./])@([A-Z0-9-]+)(?![A-Z0-9-])/gi,(K,H)=>{return`[${H}](https://github.com/${H})`}),R=R.replace(/__INLINE_CODE_PLACEHOLDER_(\d+)__/g,(K,H)=>Y[Number(H)]),R=R.replace(/__FENCE_PLACEHOLDER_(\d+)__/g,(K,H)=>$[Number(H)]),R}sanitizeGitHubReferences(W){if(this.config?.releaseNotes?.sanitizeReferences===!1)return W;let $=[],Y=[],R=W.replace(/```[\s\S]*?```/g,(K)=>{return $.push(K),`__FENCE_PLACEHOLDER_${$.length-1}__`});return R=R.replace(/`[^`\n]+`/g,(K)=>{return Y.push(K),`__INLINE_CODE_PLACEHOLDER_${Y.length-1}__`}),R=R.replace(/https?:\/\/github\.com\/([^/]+)\/([^/]+)\/(?:pull|issues)\/(\d+)/g,(K,H,Z,B)=>`\`${H}/${Z}#${B}\``),R=R.replace(/(?<![`\w])#(\d+)(?!\d)/g,"`#$1`"),R=R.replace(/__INLINE_CODE_PLACEHOLDER_(\d+)__/g,(K,H)=>Y[Number(H)]),R=R.replace(/__FENCE_PLACEHOLDER_(\d+)__/g,(K,H)=>$[Number(H)]),R}generateCustomTemplate(W,$,Y={}){let R=$,H={...{"{title}":this.generateTitle(W),"{package_count}":W.updates.length.toString(),"{update_type}":W.updateType,"{packages}":W.updates.map((Z)=>Z.name).join(", "),"{date}":new Date().toISOString().split("T")[0]},...Y};for(let[Z,B]of Object.entries(H))R=R.replace(new RegExp(Z,"g"),B);return R}formatVersionChange(W,$){let Y=W.match(/^(\D+)/),R=Y?Y[1]:"";if(R){let K=W.replace(/^\D+/,""),H=$.replace(/^\D+/,"");return`\`${R}${K}\` \u2192 \`${R}${H}\``}return`\`${W}\` \u2192 \`${$}\``}getVersionChangeDescription(W,$,Y){return{major:"\uD83D\uDD34 Breaking changes possible",minor:"\uD83D\uDFE1 New features added",patch:"\uD83D\uDFE2 Bug fixes & patches"}[Y]}}
|
|
186
|
+
export{C as hd,f as id,p as jd};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{tk as T,uk as oe}from"./chunk-8661pvb8.js";import{vk as M,wk as _,xk as B}from"./chunk-ctsz0ynx.js";import{Fk as ie}from"./chunk-6g1y9yqh.js";var W=[{domain:"php.net",aliases:["php"]},{domain:"ruby-lang.org",aliases:["ruby"]},{domain:"go.dev",aliases:["go"]},{domain:"nodejs.org",aliases:["node"]},{domain:"python.org",aliases:["python","py"]},{domain:"openjdk.org",aliases:["java","jdk"]},{domain:"kotlinlang.org",aliases:["kotlin"]},{domain:"scala-lang.org",aliases:["scala"]},{domain:"deno.land",aliases:["deno"]},{domain:"openssl.org",aliases:["openssl"]},{domain:"cmake.org",aliases:["cmake"]},{domain:"gradle.org",aliases:["gradle"]},{domain:"maven.apache.org",aliases:["maven","mvn"]},{domain:"curl.se",aliases:["curl"]},{domain:"git-scm.org",aliases:["git"]},{domain:"vim.org",aliases:["vim","vi"]},{domain:"gnupg.org",aliases:["gpg"]},{domain:"crates.io/ripgrep",aliases:["ripgrep","rg"]},{domain:"npmjs.com",aliases:["npm"]},{domain:"classic.yarnpkg.com",aliases:["yarn"]},{domain:"bun.com",aliases:["bun","bun.sh"]},{domain:"docker.com/cli",aliases:["docker"]},{domain:"terraform.io",aliases:["terraform"]},{domain:"kubernetes.io/kubectl",aliases:["kubectl"]},{domain:"helm.sh",aliases:["helm"]},{domain:"sqlite.org",aliases:["sqlite"]},{domain:"postgresql.org",aliases:["postgres","postgresql"]},{domain:"redis.io",aliases:["redis"]},{domain:"mysql.com",aliases:["mysql"]},{domain:"s3tools.org",aliases:["s3cmd"]},{domain:"aws.amazon.com/cdk",aliases:["cdk","aws/cdk"]},{domain:"info-zip.org/zip",aliases:["zip"]},{domain:"info-zip.org/unzip",aliases:["unzip"]}];function ee(e){let s=W.find((o)=>o.domain===e);return s?s.aliases:[]}function ne(e){return W.find((s)=>s.domain===e)?.replace===!0}function we(){let e={};for(let s of W)for(let o of s.aliases)e[o]=s.domain;return e}import g from"fs";import S from"path";import U from"process";oe();var le=async(...e)=>null;function X(e,s){let o=e.replace(/^v/,"").split("."),n=s.replace(/^v/,"").split(".");for(let t=0;t<Math.max(o.length,n.length);t++){let i=Number.parseInt(o[t]||"0",10),a=Number.parseInt(n[t]||"0",10);if(!Number.isNaN(i)&&!Number.isNaN(a)){if(i!==a)return a-i}else{let c=(n[t]||"").localeCompare(o[t]||"");if(c!==0)return c}}return 0}function te(e){if(e.includes("/")){let[s,...o]=e.split("/"),n=o.join("/"),t=s.replace(/\./g,"");if(s.includes("github.com")){let a=n.split("/");return a[a.length-1].replace(/[.-]/g,"").toLowerCase()}let i=n.replace(/[/.-]/g,"");return`${t}${i}`.toLowerCase()}return e.replace(/\./g,"").toLowerCase()}function ce(e,s){switch(e){case"versions":if(Array.isArray(s)&&s.length>0)return` /**
|
|
3
|
+
* Available versions from newest to oldest.
|
|
4
|
+
* @see https://ts-pantry.netlify.app/usage for installation instructions
|
|
5
|
+
*/`;break;case"programs":if(Array.isArray(s)&&s.length>0)return` /**
|
|
6
|
+
* Executable programs provided by this package.
|
|
7
|
+
* These can be run after installation.
|
|
8
|
+
*/`;break;case"dependencies":if(Array.isArray(s)&&s.length>0)return` /**
|
|
9
|
+
* Runtime dependencies for this package.
|
|
10
|
+
* These are required when running the package.${s.some((o)=>typeof o==="string"&&o.includes(":"))?"\n * OS-specific dependencies are prefixed with `os:` (e.g., `linux:freetype.org`).":""}
|
|
11
|
+
*/`;break;case"buildDependencies":if(Array.isArray(s)&&s.length>0)return` /**
|
|
12
|
+
* Build dependencies for this package.
|
|
13
|
+
* These are only required when building the package from source.${s.some((o)=>typeof o==="string"&&o.includes(":"))?"\n * OS-specific dependencies are prefixed with `os:` (e.g., `linux:gnu.org/gcc`).":""}
|
|
14
|
+
*/`;break;case"companions":if(Array.isArray(s)&&s.length>0)return` /**
|
|
15
|
+
* Related packages that work well with this package.
|
|
16
|
+
* Consider installing these for enhanced functionality.
|
|
17
|
+
*/`;break;case"aliases":if(Array.isArray(s)&&s.length>0)return` /**
|
|
18
|
+
* Alternative names for this package.
|
|
19
|
+
* You can use any of these names to access the package.
|
|
20
|
+
*/`;break;case"installCommand":return` /**
|
|
21
|
+
* Command to install this package using pantry.
|
|
22
|
+
* @example pantry install package-name
|
|
23
|
+
*/`;case"description":return` /**
|
|
24
|
+
* Brief description of what this package does.
|
|
25
|
+
*/`;case"domain":return` /**
|
|
26
|
+
* The canonical domain name for this package.
|
|
27
|
+
*/`;case"name":return` /**
|
|
28
|
+
* The display name of this package.
|
|
29
|
+
*/`;default:return null}return null}function ae(e){let s=[];s.push("{");for(let[o,n]of Object.entries(e)){if(o==="fetchedAt")continue;let t=ce(o,n);if(t)s.push(t);if(n===void 0){s.push(` ${o}: undefined,`);continue}if(Array.isArray(n))if(n.length===0)s.push(` ${o}: [] as const,`);else if(typeof n[0]==="string"){let i=n;if(o==="aliases"){let a=e.name;i=n.filter((c)=>{if(c.includes("--")||c.includes("$SHELL")||c.includes("+")||c.includes("(")||c.includes(")"))return!1;if(c===a)return!1;return!0})}if(i.length===0)s.push(` ${o}: [] as const,`);else{s.push(` ${o}: [`);for(let a of i)s.push(` '${String(a).replace(/'/g,"\\'")}',`);s.push(" ] as const,")}}else{let i=JSON.stringify(n).replace(/"/g,"'");s.push(` ${o}: ${i} as const,`)}else if(typeof n==="string")s.push(` ${o}: '${String(n).replace(/'/g,"\\'")}' as const,`);else if(typeof n==="number"||typeof n==="boolean")s.push(` ${o}: ${n} as const,`);else if(n===null)s.push(` ${o}: null,`);else if(typeof n==="object")s.push(` ${o}: ${ae(n)},`);else{let i=JSON.stringify(n).replace(/"/g,"'");s.push(` ${o}: ${i},`)}}return s.push("}"),s.join(`
|
|
30
|
+
`)}function pe(e,s,o){let n=[];if(n.push("/**"),e.description)n.push(` * **${o}** - ${e.description.trim()}`);else n.push(` * **${o}** - pkgx package`);if(n.push(" *"),n.push(` * @domain \`${e.domain||s}\``),e.programs&&e.programs.length>0){let t=e.programs.slice(0,5).join("`, `"),i=e.programs.length>5?`, ... (+${e.programs.length-5} more)`:"";n.push(` * @programs \`${t}\`${i}`)}if(e.versions&&e.versions.length>0)n.push(` * @version \`${e.versions[0]}\` (${e.versions.length} versions available)`),n.push(" * @versions From newest version to oldest.");if(e.installCommand)n.push(" *"),n.push(` * @install \`${e.installCommand}\``);if(e.aliases&&e.aliases.length>0){let t=e.aliases.filter((i)=>{return!i.includes("--")&&!i.includes("$SHELL")&&!i.includes("+")&&!i.includes("(")&&!i.includes(")")});if(t.length>0){let i=e.name,a=t.filter((p)=>p!==i),c=t.find((p)=>p===i);if(c)n.push(` * @name \`${c}\``);if(a.length>0)n.push(` * @aliases ${a.map((p)=>`\`${p}\``).join(", ")}`)}}if(e.homepageUrl)n.push(` * @homepage ${e.homepageUrl}`);if(e.dependencies&&e.dependencies.length>0){let t=e.dependencies.slice(0,3).join("`, `"),i=e.dependencies.length>3?`, ... (+${e.dependencies.length-3} more)`:"",a=e.dependencies.some((c)=>c.includes(":"))?" (includes OS-specific dependencies with `os:package` format)":"";n.push(` * @dependencies \`${t}\`${i}${a}`)}if(e.buildDependencies&&e.buildDependencies.length>0){let t=e.buildDependencies.slice(0,3).join("`, `"),i=e.buildDependencies.length>3?`, ... (+${e.buildDependencies.length-3} more)`:"",a=e.buildDependencies.some((c)=>c.includes(":"))?" (includes OS-specific dependencies with `os:package` format)":"";n.push(` * @buildDependencies \`${t}\`${i}${a} - required only when building from source`)}if(e.companions&&e.companions.length>0){let t=e.companions.slice(0,3).join("`, `"),i=e.companions.length>3?`, ... (+${e.companions.length-3} more)`:"";n.push(` * @companions \`${t}\`${i}`)}if(n.push(" *"),n.push(" * @example"),n.push(" * ```typescript"),n.push(" * import { pantry } from 'ts-pantry'"),n.push(" *"),e.aliases&&e.aliases.length>0){let t=e.aliases.find((i)=>{return!i.includes("--")&&!i.includes("$SHELL")&&!i.includes("+")&&!i.includes("(")&&!i.includes(")")});if(t){let i=t.replace(/[^a-z0-9]/gi,""),a=s.replace(/[.-]/g,"").replace(/\//g,"").toLowerCase();if(t===e.name)n.push(" * // Access the package"),n.push(` * const pkg = pantry.${i}`),n.push(" * // Or access via domain"),n.push(` * const samePkg = pantry.${a}`),n.push(" * console.log(pkg === samePkg) // true");else n.push(" * // Access via alias (recommended)"),n.push(` * const pkg = pantry.${i}`),n.push(" * // Or access via domain"),n.push(` * const samePkg = pantry.${a}`),n.push(" * console.log(pkg === samePkg) // true")}else{let i=s.replace(/[.-]/g,"").replace(/\//g,"").toLowerCase();n.push(` * const pkg = pantry.${i}`)}}else{let t=s.replace(/[.-]/g,"").replace(/\//g,"").toLowerCase();n.push(` * const pkg = pantry.${t}`)}if(n.push(` * console.log(pkg.name) // "${e.name||o}"`),e.description){let t=e.description.length>50?`${e.description.substring(0,47)}...`:e.description;n.push(` * console.log(pkg.description) // "${t}"`)}if(e.programs&&e.programs.length>0)n.push(` * console.log(pkg.programs) // [${e.programs.slice(0,2).map((t)=>`"${t}"`).join(", ")}${e.programs.length>2?", ...":""}]`);if(e.versions&&e.versions.length>0)n.push(` * console.log(pkg.versions[0]) // "${e.versions[0]}" (latest)`);return n.push(" * ```"),n.push(" *"),n.push(` * @see https://ts-pantry.netlify.app/packages/${s.replace(/\./g,"-")}.md`),n.push(" * @see https://ts-pantry.netlify.app/usage"),n.push(" */"),n.join(`
|
|
31
|
+
`)}function ue(e,s){function o(p){if(!p||p.length<2)return!1;if(p.includes("--")||p.includes("$SHELL")||p.includes("+")||p.includes("(")||p.includes(")"))return!1;if(["cli","app","tool","server","client","api","lib","core"].includes(p.toLowerCase()))return!1;if(/^[\d.]+$/.test(p)&&/^\d/.test(p))return!1;return!0}let n,t;if(s==="classic.yarnpkg.com")n="classicYarnPackage",t="yarn";else if(s==="yarnpkg.com")n="yarnPackage",t="yarn";else if(e.aliases&&e.aliases.length>0){let p=e.aliases.find((l)=>o(l));if(p){let l=p.replace(/[^a-z0-9]/gi,"");n=`${l.charAt(0).toLowerCase()}${l.slice(1)}Package`,t=p}else n=`${te(s)}Package`,t=e.name||s}else n=`${te(s)}Package`,t=e.name||s;let i=n.replace(/[^\w$]/g,""),a=pe(e,s,t),c=ae(e);return`${a}
|
|
32
|
+
export const ${i} = ${c}
|
|
33
|
+
|
|
34
|
+
export type ${i.charAt(0).toUpperCase()+i.slice(1)} = typeof ${i}
|
|
35
|
+
`}function Z(e){let s=e.replace(/\{\{[^}]*\}\}/g,"").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");if(!s||s.length===0)return"package";let o=s.replace(/[^\w.-]/g,"-");if(o.length>200)o=`${o.substring(0,150)}...${o.substring(o.length-45)}`;return o}function G(e,s,o){if(!g.existsSync(e))g.mkdirSync(e,{recursive:!0});let n;if(s.includes("/")){let a=s.split("/");if(a.some((w)=>!w||w===".."||w==="."||w.includes("\x00")||w.includes("\\")))throw Error(`Invalid domain name (contains path-traversal): ${s}`);let c=a[0],p=a.slice(1),l=S.join(e,c,...p.slice(0,-1)),b=S.resolve(e);if(!S.resolve(l).startsWith(`${b}${S.sep}`)&&S.resolve(l)!==b)throw Error(`Path traversal detected for ${s}`);if(!g.existsSync(l))g.mkdirSync(l,{recursive:!0});let P=Z(p[p.length-1]);n=S.join(l,`${P}.ts`)}else{let a=s.replace(/\./g,"");n=S.join(e,`${a}.ts`)}let t={...o};delete t.fetchedAt;let i=ue(t,s);return g.writeFileSync(n,i),n}function De(e,s){if(!g.existsSync(e))return[];let o=new Set;for(let a of s)if(a.includes("/")){let c=a.split("/"),p=c[0],l=c.slice(1),b=Z(l[l.length-1]);o.add(S.resolve(e,p,...l.slice(0,-1),`${b}.ts`))}else{let c=a.replace(/\./g,"");o.add(S.resolve(e,`${c}.ts`))}let n=new Set(["index.ts","aliases.ts","types.ts"]),t=[];function i(a){if(!g.existsSync(a))return;for(let c of g.readdirSync(a,{withFileTypes:!0})){let p=S.join(a,c.name);if(c.isDirectory()){if(i(p),g.existsSync(p)&&g.readdirSync(p).length===0)g.rmdirSync(p)}else if(c.name.endsWith(".ts")&&!n.has(c.name)){if(!o.has(S.resolve(p)))g.unlinkSync(p),t.push(p)}}}return i(e),t}function ge(e,s={}){try{let o=s.cacheDir||M;if(s.cache===!1)return console.log(`Cache disabled for ${e}, skipping cache check`),null;let n=(T[e]||e).replace(/\//g,"-"),t=S.join(o,`${n}.json`);if(console.log(`Checking for cache file: ${t}`),!g.existsSync(t))return null;let i;try{i=JSON.parse(g.readFileSync(t,"utf-8"))}catch{try{g.unlinkSync(t)}catch{}return null}if(!i.fetchedAt)return console.log(`Cache for ${e} missing fetchedAt timestamp, invalidating`),null;if(["Crafters of fine Open Source products","Go home.","Package information for","pkgx package","Loading...","Please wait..."].some((p)=>i.description&&i.description.includes(p)))return console.log(`Cache for ${e} has generic description "${i.description}", invalidating`),null;if(!i.versions||i.versions.length===0)return console.log(`Cache for ${e} has no versions, invalidating`),null;let a=(s.cacheExpirationMinutes||_)*60*1000,c=Date.now();if(c-i.fetchedAt>a)return console.log(`Cache for ${e} has expired (age: ${Math.round((c-i.fetchedAt)/60000)} minutes)`),null;return console.log(`Using cached data for ${e} (age: ${Math.round((c-i.fetchedAt)/60000)} minutes)`),{packageInfo:i,filePath:t}}catch(o){return console.error(`Error reading cache for ${e}:`,o),null}}function de(e,s,o={}){let n={...s,fetchedAt:Date.now()},t=o.cacheDir||M;if(!g.existsSync(t))g.mkdirSync(t,{recursive:!0});let i=e.replace(/\//g,"-"),a=S.join(t,`${i}.json`);g.writeFileSync(a,JSON.stringify(n,null,2));let c=o.outputDir||"packages";if(!g.existsSync(c))g.mkdirSync(c,{recursive:!0});let p=G(c,e,s);return{cachePath:a,outputPath:p}}function re(){return Promise.resolve()}async function Ie(e={}){let s=e.apiUrl||"https://api.github.com/repos/pkgxdev/pantry/contents/projects";try{console.log(`Fetching projects from GitHub API: ${s}`);let o=await fetch(s,{headers:{Accept:"application/vnd.github.v3+json"}});if(!o.ok)throw Error(`Failed to fetch from GitHub API: ${o.statusText}`);let n=(await o.json()).filter((t)=>t.type==="dir").map((t)=>({name:t.name,url:t.html_url}));return console.log(`Retrieved ${n.length} projects from GitHub API`),n.sort((t,i)=>t.name.localeCompare(i.name)),n}catch(o){throw console.error("Error fetching projects from GitHub API:",o),o}}async function z(e,s={}){let o=e,n=e;if(e.includes("/")){let[t,i]=e.split("/");console.log(`Identified nested package: domain=${t}, name=${i}`)}if(T[e])console.log(`'${e}' is an alias for '${T[e]}', redirecting...`),n=T[e],e=T[e];try{let t=s.timeout||B,i=await le(e,{timeout:t,useClientSideScraper:!0});if(!i||typeof i!=="object")return se(e,o,n);let a={name:i.displayName||i.name||e.split("/").pop()||e,domain:i.domain||e,description:i.description||i.brief||"",packageYmlUrl:`https://github.com/pkgxdev/pantry/tree/main/projects/${e}/package.yml`,homepageUrl:i.homepage||"",githubUrl:i.github||"",installCommand:`pantry install ${e}`,pantryInstallCommand:`pantry install ${e}`,programs:i.provides||[],companions:Array.isArray(i.companions)?i.companions:[],dependencies:Array.isArray(i.dependencies)?i.dependencies:[],buildDependencies:i.buildDependencies||[],versions:i.versions||[],aliases:[]};if(!a.versions||a.versions.length===0){let c=a.domain||e;if(!["apache.org","breakfastquay.com","catb.org","bloomreach.com","cairographics.org","certifi.io","charm.sh","aws.amazon.com","google.com","microsoft.com","mozilla.org","freedesktop.org","gnome.org","kde.org","sourceforge.net","sf.net"].some((p)=>c.startsWith(p)))try{let p=a.domain||e,l=await me(p);a.versions=l}catch(p){console.warn(`Failed to fetch versions for ${e} from GitHub API:`,p),a.versions=[]}}if(a.versions&&a.versions.length>0)try{a.versions.sort((c,p)=>{try{return-1*Bun.semver.order(c,p)}catch{return X(c,p)}})}catch(c){console.warn(`Warning: Failed to sort versions for ${e} using semver:`,c)}return a.name=a.name||o,a.domain=a.domain||n,a.programs=a.programs||[],a.companions=a.companions||[],a.dependencies=a.dependencies||[],a.versions=a.versions||[],{packageInfo:a,originalName:o,fullDomainName:n}}catch(t){return console.error(`Error in fetchPantryPackage for ${e}:`,t),se(e,o,n)}}async function me(e){try{let{shouldProceedWithGitHubRequest:s,saveRateLimitInfo:o}=await import("./chunk-dat582cg.js");if(!s())return console.warn("Skipping GitHub API request for versions due to rate limiting"),[];let n=await fetch(`https://api.github.com/repos/pkgxdev/pantry/contents/projects/${e}`,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"ts-pantry"},signal:AbortSignal.timeout(15000)});if(o(n.headers),n.status===403){let t=n.headers.get("X-RateLimit-Remaining"),i=n.headers.get("X-RateLimit-Reset"),a=i?new Date(Number(i)*1000).toLocaleString():"unknown";return console.warn(`GitHub API rate limit exceeded. Remaining: ${t||0}, Reset: ${a}`),[]}if(!n.ok)throw Error(`GitHub API responded with ${n.status}: ${n.statusText}`);return(await n.json()).filter((t)=>t.name.match(/^v\d+/)).map((t)=>t.name)}catch(s){return console.error("Error fetching versions from GitHub:",s),[]}}var fe=300000,O=null;function he(){let e=async(s)=>{if(console.log(`
|
|
36
|
+
Received ${s} signal. Cleaning up resources...`),O)clearInterval(O);await re(),console.log("Resources cleaned up. Exiting."),setTimeout(()=>{console.log("Forcing process exit..."),U.exit(0)},5000)};U.on("SIGINT",()=>e("SIGINT")),U.on("SIGTERM",()=>e("SIGTERM")),U.on("uncaughtException",(s)=>{console.error("Uncaught exception:",s),e("uncaughtException")})}if(typeof Bun<"u"&&Bun.main===import.meta.path)he(),U.on("uncaughtException",(e)=>{let s=String(e);if(console.error("Uncaught exception caught:",e.message),e.message.includes("No target found for targetId")||e.message.includes("Assertion error")||e.message.includes("Target page, context or browser has been closed")||e.message.includes("Failed to connect")||e.message.includes("Connection closed")||e.message.includes("Protocol error")||s.includes("WebSocket connection closed")||e.message.includes("Browser has been closed")){console.error("Browser/network connection error detected, continuing execution...");return}console.error("Non-browser error, exiting..."),U.exit(1)}),U.on("unhandledRejection",(e,s)=>{let o=String(e);if(console.error("Unhandled rejection caught:",o),o.includes("No target found for targetId")||o.includes("Assertion error")||o.includes("Target page, context or browser has been closed")||o.includes("Failed to connect")||o.includes("Connection closed")||o.includes("Protocol error")||o.includes("WebSocket connection closed")||o.includes("Browser has been closed")){console.error("Browser/network connection error in promise, continuing execution...");return}console.error("Non-browser promise rejection, exiting..."),U.exit(1)});function Ee(){if(O)clearInterval(O);O=setInterval(()=>{console.log("Running periodic browser resource cleanup..."),re().then(()=>console.log("Periodic cleanup completed")).catch((e)=>console.error("Error during periodic cleanup:",e))},fe)}async function Ce(e={}){let s=e.timeout||B,o=e.outputDir||"packages",n=e.cacheDir||M,t=e.cache!==!1,i=e.cacheExpirationMinutes||_,a=Math.min(e.concurrency||6,8),c=e.pantryDir||"src/pantry";if(!e.outputJson)console.log(`Starting bulk fetch with concurrency: ${a}, timeout: ${s}ms`);let p=Date.now(),l=[];try{if(!e.outputJson)console.log("Scanning local pantry for packages...");try{if(l=await ye(c),!e.outputJson)console.log(`Found ${l.length} packages in local pantry`)}catch(r){if(!e.outputJson)console.warn("Failed to scan local pantry, falling back to consts:",r);try{let{ALL_KNOWN_PACKAGES:h}=await import("./chunk-bk9bqd5j.js");if(l=[...h].filter((d)=>d&&d!=="undefined"&&d!=="aliases"&&d!=="index"),!e.outputJson)console.log(`Using comprehensive package list: ${l.length} packages`)}catch(h){if(!e.outputJson)console.warn("Failed to load consts, falling back to GitHub API:",h);try{let d=await fetch("https://api.github.com/repos/pkgxdev/pantry/contents/projects",{headers:{"User-Agent":"ts-pantry-fetcher",Accept:"application/vnd.github.v3+json"}});if(d.ok){let A=(await d.json()).filter((m)=>m.type==="dir").map((m)=>m.name).sort();if(!e.outputJson)console.log(`Retrieved ${A.length} projects from GitHub API`);l=A}else throw Error(`GitHub API returned ${d.status}`)}catch(d){if(!e.outputJson)console.warn("Failed to fetch from GitHub API, falling back to local discovery:",d);if(g.existsSync(o))l=g.readdirSync(o).filter((A)=>A.endsWith(".ts")).map((A)=>S.basename(A,".ts")),console.log(`Found ${l.length} existing packages`)}}}if(l.length===0)return console.error("No packages found to process"),[];let b=["android.com","apache.org","akuity.io","alsa-project.org","anchore.com","aomedia.googlesource.com","apollographql.com","facebook.com","google.com","microsoft.com","mozilla.org","sourceforge.net","x.org","xiph.org","yui.github.io","crates.io","gitlab.com","github.com"],P=new Set,w=l.filter((r)=>r.startsWith("github.com/"));for(let r of w){let h=r.split("/");if(h.length>2){let d=h.slice(0,2).join("/");P.add(d)}}if(l=l.filter((r)=>{if(r.endsWith("/.pkgroot"))return console.log(`Filtering out .pkgroot marker: ${r}`),!1;if(r.endsWith("/README.rst"))return console.log(`Filtering out README.rst documentation: ${r}`),!1;if(r==="agwa.name")return console.log("Filtering out standalone agwa.name - only agwa.name/git-crypt is valid"),!1;if(b.includes(r))return console.log(`Filtering out parent domain ${r} - only has nested packages`),!1;if(P.has(r))return console.log(`Filtering out GitHub parent path ${r} - only has nested packages`),!1;if(r==="undefined"||r==="aliases"||r==="index")return!1;return!0}),console.log(`Found ${l.length} packages to process`),e.limit&&e.limit>0)l=l.slice(0,e.limit),console.log(`Limited to ${l.length} packages`);let k=[],f=[],x=0,u=Math.min(a,6),y=[];for(let r=0;r<l.length;r+=u)y.push(l.slice(r,r+u));if(!e.outputJson)console.log(`Processing ${l.length} packages in ${y.length} batches...`);for(let r=0;r<y.length;r++){let h=y[r];if(!e.outputJson)console.log(`Processing batch ${r+1}/${y.length} (${h.length} packages)`);let d=h.map(async($)=>{try{let j=S.join(n,`${$.replace(/\//g,"-")}.json`);if(t&&g.existsSync(j)){let L=g.statSync(j),q=(Date.now()-L.mtime.getTime())/60000;if(q<i){if(!e.outputJson)console.log(`Using cached data for ${$} (age: ${Math.round(q)} minutes)`);try{let J=JSON.parse(g.readFileSync(j,"utf-8"));delete J.fetchedAt;let H=G(o,$,J);if(!e.outputJson)console.log(`Using cached data for ${$} (saved to ${H})`);return{success:!0,packageName:$}}catch{console.warn(`Cache file corrupted for ${$}, will refetch`)}}}let E=await be($,{...e,pantryDir:c,timeout:s,cache:t,cacheDir:n,cacheExpirationMinutes:i});if(E){let{outputPath:L}=de($,E.packageInfo,{cacheDir:n,outputDir:o,cache:t});if(!e.outputJson)console.log(`Successfully processed ${$} (saved to ${L})`);return{success:!0,packageName:$}}else return console.warn(`Failed to fetch ${$}`),{success:!1,packageName:$}}catch(j){return console.error(`Error processing ${$}:`,j),{success:!1,packageName:$}}}),A=await Promise.allSettled(d);for(let $ of A)if(x++,$.status==="fulfilled")if($.value.success)k.push($.value.packageName);else f.push($.value.packageName);else console.error("Batch promise rejected:",$.reason),f.push("unknown");let m=Math.round((Date.now()-p)/1000),N=Math.round(x/m*10)/10,D=Math.round((l.length-x)/N);if(!e.outputJson)console.log(`Batch ${r+1}/${y.length} complete. Progress: ${x}/${l.length} (${Math.round(x/l.length*100)}%) | Success: ${k.length} | Failed: ${f.length} | Rate: ${N}/s | ETA: ${D}s`);if(r<y.length-1)await new Promise(($)=>setTimeout($,1000))}let v=Math.round((Date.now()-p)/1000);if(!e.outputJson){if(console.log(`
|
|
37
|
+
Completed in ${v}s. Successfully processed: ${k.length}, Failed: ${f.length}`),f.length>0)console.log(`Failed packages: ${f.slice(0,10).join(", ")}${f.length>10?` ... and ${f.length-10} more`:""}`)}return k}catch(b){return console.error("Error in fetchAndSaveAllPackages:",b),[]}}function se(e,s,o){let n=e.split("/"),t=n[0];return{packageInfo:{name:(n.length>1?n.slice(1).join("/"):null)||e,domain:t,description:`Package information for ${e}`,packageYmlUrl:"",homepageUrl:"",githubUrl:"",installCommand:`pantry install ${e}`,pantryInstallCommand:`pantry install ${e}`,programs:[],companions:[],dependencies:[],versions:[]},originalName:s,fullDomainName:o}}async function $e(e,s,o,n=!1,t=1,i=3,a=!1,c={}){try{let p=c.cache!==!1,l=c.cacheDir||M;if(!p)console.log(`Cache disabled for ${e}, will fetch directly`);else{let f=ge(e,{cacheDir:l,cacheExpirationMinutes:c.cacheExpirationMinutes,cache:c.cache});if(f){let{packageInfo:x}=f,u=x.domain||e,y=x.aliases||[],v=G(s,e,x);return console.log(`Using cached data for ${e} (saved to ${v})`),{success:!0,fullDomainName:u,aliases:y,filePath:v}}}let b=o+(t-1)*1e4;console.log(`Using timeout for ${e} (attempt ${t}): ${b}ms`);let P=b,w,k=new Promise((f,x)=>{w=setTimeout(()=>{console.error(`Operation timeout for ${e} after ${P}ms`),x(Error(`Operation timeout after ${P}ms`))},P)});if(e.includes("/")){let f=e.split("/"),x=f[0],u=f.slice(1).join("/");console.log(`Processing nested package: domain=${x}, subPath=${u}`);try{let y=z(`${x}/${u}`,{timeout:b,browser:c.browser}),v=await Promise.race([y,k]);clearTimeout(w);let{packageInfo:r,originalName:h,fullDomainName:d}=v;if(r.versions&&r.versions.length>0)try{r.versions.sort((j,E)=>{try{return-1*Bun.semver.order(j,E)}catch{return X(j,E)}})}catch(j){console.warn(`Warning: Failed to sort versions for ${e} using semver:`,j)}let A=d.replace(/\//g,"-"),m=[];if(r.aliases&&r.aliases.length>0)m.push(...r.aliases);for(let[j,E]of Object.entries(T))if(E===d&&!m.includes(j))m.push(j);if(h!==d&&!m.includes(h))m.push(h);let N=["cli","app","tool","server","client","api","lib","core"];if(!m.includes(u)&&!N.includes(u.toLowerCase()))m.push(u);let D={...r,fullPath:e,aliases:m.length>0?m:[]};if(p){let j=S.join(l,`${A}.json`),E={...D,fetchedAt:Date.now()};if(!g.existsSync(l))g.mkdirSync(l,{recursive:!0});g.writeFileSync(j,JSON.stringify(E,null,2)),console.log(`Saved package data to cache: ${j}`)}let $=G(s,d,D);return console.log(`Successfully saved nested package ${e} to ${$} with aliases: ${m.join(", ")||"none"}`),{success:!0,fullDomainName:d,aliases:m,filePath:$}}catch(y){if(clearTimeout(w),y.toString().includes("404")||y.toString().includes("Not Found"))return console.error(`Package ${e} returned 404 Not Found.`),console.error(`Skipping ${e} to avoid overwriting existing files.`),{success:!1,fullDomainName:e};throw y}}else try{let f=z(e,{timeout:b,browser:c.browser}),x=await Promise.race([f,k]);clearTimeout(w);let{packageInfo:u,originalName:y,fullDomainName:v}=x,r=u.description&&u.description.trim()!=="",h=u.versions&&u.versions.length>0,d=u.programs&&u.programs.length>0,A=u.packageYmlUrl&&u.packageYmlUrl.length>0,m=u.dependencies&&u.dependencies.length>0,N=u.companions&&u.companions.length>0,D=r&&(u.description.toLowerCase().trim()==="go home."||u.description.toLowerCase().trim()==="page not found"||u.description.toLowerCase().trim()==="not found"||u.description.toLowerCase().trim()==="404"||u.description.toLowerCase().trim()==="error"),$=r&&!D,j=h||d||A||m||N,E=u.domain&&u.domain.includes(".");if(!($||j||E))return console.error(`Package ${e} appears to have no meaningful data. Skipping to avoid creating empty files.`),{success:!1,fullDomainName:e};let L=u.name&&u.name!==v&&u.name!==v.split("/")[0]&&u.name.length>1&&!u.name.includes("/")?Z(u.name):null,q=v.replace(/\//g,"-"),J=L?S.join(s,`${L}.ts`):S.join(s,`${q}.ts`);if(g.existsSync(J)){let I=g.readFileSync(J,"utf-8"),F=I.includes("dependencies: [")&&!I.includes("dependencies: [] as const"),V=u.dependencies.length===0,K=!I.includes("description: 'Package information for")&&!I.includes("description: '' as const"),Q=u.description.includes("Package information for")||u.description.trim()==="";if(F&&V||K&&Q)return console.warn(`\u26A0\uFE0F Existing file ${J} has better data than new fetch. Skipping to prevent data loss.`),console.warn(` Existing deps: ${F}, New deps: ${!V}`),console.warn(` Existing desc: ${K}, New desc: ${!Q}`),{success:!1,fullDomainName:e}}if(u.versions&&u.versions.length>0)try{u.versions.sort((I,F)=>{try{return-1*Bun.semver.order(I,F)}catch{return X(I,F)}})}catch(I){console.warn(`Warning: Failed to sort versions for ${e} using semver:`,I)}let H=v.replace(/\//g,"-"),C=[];if(u.aliases&&u.aliases.length>0)C.push(...u.aliases);for(let[I,F]of Object.entries(T))if(F===v&&!C.includes(I))C.push(I);if(y!==v&&!C.includes(y))C.push(y);let R={...u,fullPath:e,aliases:C.length>0?C:[]};if(p){let I=S.join(l,`${H}.json`),F={...R,fetchedAt:Date.now()};if(!g.existsSync(l))g.mkdirSync(l,{recursive:!0});g.writeFileSync(I,JSON.stringify(F,null,2)),console.log(`Saved package data to cache: ${I}`)}let Y=G(s,v,R);return console.log(`Successfully saved ${e} to ${Y} with aliases: ${C.join(", ")||"none"}`),{success:!0,fullDomainName:v,aliases:C,filePath:Y}}catch(f){if(clearTimeout(w),f.toString().includes("404")||f.toString().includes("Not Found"))return console.error(`Package ${e} returned 404 Not Found. Skipping to avoid overwriting existing files.`),{success:!1,fullDomainName:e};throw f}}catch(p){let l=String(p),b=l.includes("Operation timed out after")||l.includes("Operation timeout after")||l.includes("timeout")||l.includes("Timeout")||l.includes("Navigation timeout"),P=l.includes("No target found")||l.includes("targetId")||l.includes("Target page, context or browser has been closed")||l.includes("Protocol error")||l.includes("Connection closed")||l.includes("Assertion error")||l.includes("Browser has been closed")||l.includes("Target closed")||l.includes("Session closed")||l.includes("WebSocket connection closed");if(b)console.error(`Timeout error for ${e}:`,l.substring(0,200)),await new Promise((k)=>setTimeout(k,1000*t));else if(P){if(console.error(`Browser connection error for ${e}:`,l.substring(0,200)),c.browser)try{await c.browser.close().catch(()=>{})}catch{}await new Promise((k)=>setTimeout(k,3000*t))}if(t>=i){if(console.error(`Failed to fetch package ${e} after ${t} attempts:`,p),a){let k=S.join(U.cwd(),`${e.replace(/\//g,"-")}-error.txt`);g.writeFileSync(k,`Error fetching ${e}:
|
|
38
|
+
${p.toString()}
|
|
39
|
+
|
|
40
|
+
Stack:
|
|
41
|
+
${p.stack||"No stack trace available"}`),console.error(`Saved error details to ${k}`)}return console.error(`Skipping ${e} after ${t} failed attempts to avoid overwriting existing files.`),{success:!1,fullDomainName:e}}console.error(`Attempt ${t} failed for ${e}, retrying...`,p);let w=500*t;if(P)w=2000*t;else if(b)w=1000*t;return await new Promise((k)=>setTimeout(k,w)),$e(e,s,o,n,t+1,i,a,c)}}async function ye(e="src/pantry"){if(!g.existsSync(e))throw Error(`Pantry directory not found: ${e}. Please run 'bun ./bin/cli.ts update-pantry' first.`);let s=[];function o(n,t=""){let i=g.readdirSync(n,{withFileTypes:!0}),a=S.join(n,"package.yml");if(t&&g.existsSync(a))s.push(t);for(let c of i)if(c.isDirectory()&&!c.name.startsWith(".")){let p=t?`${t}/${c.name}`:c.name,l=S.join(n,c.name);o(l,p)}}return o(e),console.log(`Found ${s.length} packages in pantry`),s.sort()}async function ke(e,s="src/pantry"){let o=S.join(s,e,"package.yml");if(!g.existsSync(o))return console.warn(`Package.yml not found for ${e}`),null;try{let n=g.readFileSync(o,"utf-8"),t=[],i=[],a=n.split(`
|
|
42
|
+
`),c=!1,p=!1,l=!1,b="";for(let r of a){if(r.match(/^dependencies:\s*$/)){c=!0,p=!1,l=!1;continue}if(r.match(/^\s{2}dependencies:\s*$/)){p=!0,c=!1,l=!1;continue}if(c||p){if(r.match(/^\s*$/)||c&&r.match(/^\S/)||p&&!r.match(/^\s{4,}/)){c=!1,p=!1,l=!1;continue}let h=r.match(/^\s{2}(linux|darwin|windows):\s*$/);if(h){l=!0,b=h[1];continue}if(l){let d=r.match(/^\s{4,}([^\s:]+):\s*['"]?([^'"]+)['"]?/);if(d){let A=d[1],m=d[2].trim(),N=`${b}:`;if(m&&m!=="*"){let D=/^[~^>=<@]/.test(m),$=/^[\d.]+$/.test(m)&&/^\d/.test(m),j=`${N}${A}${D?"":$?"@":"^"}${m}`;if(p)i.push(j);else t.push(j)}else{let D=`${N}${A}`;if(p)i.push(D);else t.push(D)}}else if(!r.match(/^\s{4,}/)&&!r.match(/^\s*$/))l=!1,b=""}else{let d=r.match(/^\s{2,3}([^\s:]+):\s*['"]?([^'"]+)['"]?/);if(d){let A=d[1],m=d[2].trim();if(["linux","darwin","windows"].includes(A))continue;if(m&&m!=="*"){let N=/^[~^>=<@]/.test(m),D=/^[\d.]+$/.test(m)&&/^\d/.test(m),$=`${A}${N?"":D?"@":"^"}${m}`;if(p)i.push($);else t.push($)}else{let N=A;if(p)i.push(N);else t.push(N)}}}}}let P=[],w=!1;for(let r of a){if(r.match(/^runtime:\s*$/)){w=!0;continue}if(w){if(r.match(/^\s*$/)||r.match(/^\S/)){w=!1;continue}if(r.match(/^\s+env:\s*$/))continue;if(r.match(/^\s+[A-Z_]+:\s*\$\{\{/))continue;let h=r.match(/^\s+([^\s:]+):\s*['"]?([^'"]+)['"]?/);if(h){let d=h[1],A=h[2].trim();if(/^[A-Z_]+$/.test(d))continue;if(A&&A!=="*"){let m=/^[~^>=<@]/.test(A),N=/^[\d.]+$/.test(A)&&/^\d/.test(A),D=m?"":N?"@":"^";P.push(`${d}${D}${A}`)}else P.push(d)}}}let k="",f="",x=n.match(/distributable:[\t\v\f\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*\n\s*url:\s*(.+)/);if(x){let r=x[1].trim();if(r.includes("github.com")){let h=r.match(/git\+https:\/\/github\.com\/([^/]+\/[^.]+)/);if(h){if(f=`https://github.com/${h[1]}`,h[1]==="python-attrs/attrs")k="https://www.attrs.org/"}}}let u=[],y=!1,v=!1;for(let r of a){if(r.match(/^provides:\s*$/)){y=!0,v=!1;continue}if(y){if(r.match(/^\S/)&&!r.match(/^\s*$/)){y=!1;continue}if(r.match(/^\s+(darwin|linux|windows):\s*$/)){v=!0;continue}let h=r.match(/^\s+-\s+(?:bin|sbin)\/(.+)/);if(h){let d=h[1].trim();if(!u.includes(d))u.push(d)}}}return{name:e.split("/").pop()||e,domain:e,dependencies:t,buildDependencies:i,companions:P,programs:u,homepageUrl:k,githubUrl:f}}catch(n){return console.warn(`Error reading package.yml for ${e}:`,n),null}}async function be(e,s={}){let o=s.pantryDir||"src/pantry";try{let n=await ke(e,o);try{let t=await z(e,s),i=n?.domain||t.packageInfo.domain,a=ee(i),c=t.packageInfo.aliases||[];if(a.length>0)if(ne(i))c=a;else c=[...new Set([...c,...a])];let p=[],l=[],b="",P="",w=t.packageInfo.versions||[],k=t.packageInfo.programs||[],f=n?.programs||[];if(w.length===0||k.length===0&&f.length===0){let x=s.outputDir||"src/packages",u=e.split("/"),y=u.length>1?S.join(x,...u.slice(0,-1),`${u[u.length-1]}.ts`):S.join(x,`${e.replace(/\./g,"")}.ts`);if(g.existsSync(y))try{let v=g.readFileSync(y,"utf-8");if(w.length===0){let r=v.match(/versions:\s*\[([\s\S]*?)\]\s*as\s*const/);if(r&&r[1].trim())p=r[1].match(/'([^']+)'/g)?.map((h)=>h.replace(/'/g,""))||[]}if(k.length===0&&f.length===0){let r=v.match(/programs:\s*\[([\s\S]*?)\]\s*as\s*const/);if(r&&r[1].trim())l=r[1].match(/'([^']+)'/g)?.map((h)=>h.replace(/'/g,""))||[]}if(!t.packageInfo.description){let r=v.match(/description:\s*'([^']*)'\s*as\s*const/);if(r&&r[1])b=r[1]}if(!t.packageInfo.homepageUrl&&!n?.homepageUrl){let r=v.match(/homepageUrl:\s*'([^']*)'\s*as\s*const/);if(r&&r[1])P=r[1]}}catch{}}return{packageInfo:{...t.packageInfo,dependencies:n?.dependencies&&n.dependencies.length>0?n.dependencies:t.packageInfo.dependencies,buildDependencies:n?.buildDependencies&&n.buildDependencies.length>0?n.buildDependencies:t.packageInfo.buildDependencies,companions:n?.companions&&n.companions.length>0?n.companions:t.packageInfo.companions,programs:k.length>0?k:f.length>0?f:l.length>0?l:[],versions:w.length>0?w:p,domain:n?.domain||t.packageInfo.domain,description:t.packageInfo.description||b||"",name:t.packageInfo.name||n?.name||e.split("/").pop()||e,homepageUrl:n?.homepageUrl||t.packageInfo.homepageUrl||P,githubUrl:n?.githubUrl||t.packageInfo.githubUrl,aliases:c},originalName:t.originalName,fullDomainName:t.fullDomainName}}catch(t){if(!n)return console.warn(`No pantry or web data available for ${e}:`,t),null;console.warn(`Failed to fetch web metadata for ${e}, using pantry data only:`,t);let i=[],a=[],c="",p="",l=s.outputDir||"src/packages",b=e.split("/"),P=b.length>1?S.join(l,...b.slice(0,-1),`${b[b.length-1]}.ts`):S.join(l,`${e.replace(/\./g,"")}.ts`);if(g.existsSync(P))try{let k=g.readFileSync(P,"utf-8"),f=k.match(/versions:\s*\[([\s\S]*?)\]\s*as\s*const/);if(f&&f[1].trim())i=f[1].match(/'([^']+)'/g)?.map((v)=>v.replace(/'/g,""))||[];let x=k.match(/programs:\s*\[([\s\S]*?)\]\s*as\s*const/);if(x&&x[1].trim())a=x[1].match(/'([^']+)'/g)?.map((v)=>v.replace(/'/g,""))||[];let u=k.match(/description:\s*'([^']*)'\s*as\s*const/);if(u&&u[1])c=u[1];let y=k.match(/homepageUrl:\s*'([^']*)'\s*as\s*const/);if(y&&y[1])p=y[1]}catch{}let w=n.programs&&n.programs.length>0?n.programs:a;return{packageInfo:{name:n.name||e.split("/").pop()||e,domain:n.domain||e,description:c||"",installCommand:`pantry install ${e}`,pantryInstallCommand:`pantry install ${e}`,programs:w,companions:n.companions||[],dependencies:n.dependencies||[],versions:i,buildDependencies:n.buildDependencies||[],packageYmlUrl:`https://github.com/pkgxdev/pantry/tree/main/projects/${e}/package.yml`,homepageUrl:p||n.homepageUrl||"",githubUrl:n.githubUrl||""},originalName:e,fullDomainName:e}}}catch(n){return console.error(`Error processing pantry package ${e}:`,n),null}}
|
|
43
|
+
export{we as ek,G as fk,De as gk,ge as hk,de as ik,re as jk,Ie as kk,z as lk,he as mk,Ee as nk,Ce as ok,$e as pk,ye as qk,ke as rk,be as sk};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import"./chunk-6g1y9yqh.js";var z={error:"error",warning:"warning",info:"notice"};function E(j){let q=[];for(let h of j.findings){let x=[`file=${h.file}`,`title=${h.ruleId}`];if(h.line!==void 0)x.push(`line=${h.line}`);let y=B(`${h.message}${h.fix?` \u2014 ${h.fix}`:""}`);q.push(`::${z[h.severity]} ${x.join(",")}::${y}`)}return q.join(`
|
|
3
|
+
`)}function B(j){return j.replaceAll("%","%25").replaceAll("\r","%0D").replaceAll(`
|
|
4
|
+
`,"%0A")}export{E as formatGitHub};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Wc as Z}from"./chunk-djntbp7a.js";import{Pj as _}from"./chunk-akffynkc.js";import Y from"process";class L{jobs=new Map;timers=new Map;logger;isRunning=!1;constructor(q=!1){this.logger=q?_.verbose():_.quiet()}addJob(q){this.jobs.set(q.id,q),this.scheduleJob(q),this.logger.info(`Scheduled job '${q.name}' with cron: ${q.schedule.cron}`)}removeJob(q){let C=this.timers.get(q);if(C)clearTimeout(C),this.timers.delete(q);this.jobs.delete(q),this.logger.info(`Removed scheduled job: ${q}`)}start(){if(this.isRunning){this.logger.warn("Scheduler is already running");return}this.isRunning=!0,this.logger.info("\uD83D\uDD52 Buddy Scheduler started");for(let q of this.jobs.values())if(this.scheduleJob(q),q.schedule.runOnStartup)this.logger.info(`Running startup job: ${q.name}`),setImmediate(()=>this.runJob(q));Y.on("SIGINT",()=>this.stop()),Y.on("SIGTERM",()=>this.stop())}stop(){if(!this.isRunning)return;this.isRunning=!1,this.logger.info("\uD83D\uDED1 Stopping Buddy Scheduler...");for(let q of this.timers.values())clearTimeout(q);this.timers.clear(),this.logger.success("\u2705 Buddy Scheduler stopped"),Y.exit(0)}getJobStatus(q){return this.jobs.get(q)}getAllJobs(){return Array.from(this.jobs.values())}scheduleJob(q){let C=this.timers.get(q.id);if(C)clearTimeout(C);let D=this.getNextRunTime(q.schedule.cron,q.schedule.timezone);if(q.nextRun=D||void 0,D){let G=D.getTime()-Date.now(),F=setTimeout(()=>{this.runJob(q),this.scheduleJob(q)},G);this.timers.set(q.id,F),this.logger.debug(`Job '${q.name}' scheduled for ${D.toISOString()}`)}}async runJob(q){if(q.status==="running"){this.logger.warn(`Job '${q.name}' is already running, skipping`);return}q.status="running",q.lastRun=new Date,this.logger.info(`\uD83D\uDE80 Running scheduled job: ${q.name}`);let C=Date.now(),D=q.schedule.maxRuntime||1800000;try{let G=new Promise((Q,U)=>{setTimeout(()=>U(Error("Job timeout")),D)}),F=this.executeJob(q);await Promise.race([F,G]);let J=Date.now()-C;q.status="idle",this.logger.success(`\u2705 Job '${q.name}' completed in ${J}ms`)}catch(G){q.status="error",this.logger.error(`\u274C Job '${q.name}' failed:`,G)}}async executeJob(q){let C=new Z(q.config),D=await C.scanForUpdates();if(D.updates.length===0){this.logger.info("No dependency updates found");return}if(this.logger.info(`Found ${D.updates.length} dependency updates`),q.config.repository&&q.config.pullRequest)await C.createPullRequests(D),this.logger.success(`Created pull requests for ${D.groups.length} update groups`);else this.logger.info("Repository not configured, skipping PR creation")}getNextRunTime(q,C){try{return this.parseCronExpression(q,C)}catch(D){return this.logger.error(`Invalid cron expression '${q}':`,D),null}}parseCronExpression(q,C){let D=q.trim().split(/\s+/);if(D.length!==5)throw Error("Cron expression must have 5 parts: minute hour day month dayOfWeek");let[G,F,J,Q,U]=D,K=new Date,V=C?this.timezoneOffsetMinutes(K,C):0;if(C)this.logger.debug(`Using timezone: ${C} (offset ${V} minutes)`);let X=new Date(K.getTime()+V*60*1000);X.setSeconds(0,0);let $=this.parseCronField(F,0,23),B=this.parseCronField(G,0,59);if($.length>0&&B.length>0){if(X.setHours($[0],B[0],0,0),X.getTime()-V*60*1000<=K.getTime())X.setDate(X.getDate()+1);return new Date(X.getTime()-V*60*1000)}return new Date(K.getTime()+3600000)}timezoneOffsetMinutes(q,C){try{let D=new Date(q.toLocaleString("en-US",{timeZone:C})),G=new Date(q.toLocaleString("en-US"));return Math.round((D.getTime()-G.getTime())/60000)}catch{return this.logger.warn(`\u26A0\uFE0F Unknown timezone "${C}", scheduling in host time instead`),0}}parseCronField(q,C,D){if(q==="*")return Array.from({length:D-C+1},(F,J)=>C+J);if(q.includes(","))return q.split(",").map(Number).filter((F)=>Number.isFinite(F)&&F>=C&&F<=D);if(q.includes("-")){let F=q.split("-").map(Number),J=F[0],Q=F[1];if(F.length!==2||!Number.isFinite(J)||!Number.isFinite(Q)||Q<J)return[];return Array.from({length:Q-J+1},(U,K)=>J+K).filter((U)=>U>=C&&U<=D)}if(q.includes("/")){let[F,J]=q.split("/"),Q=Number(J);if(!Number.isFinite(Q)||Q<=0)return[];if(F==="*")return Array.from({length:D-C+1},(K,V)=>C+V).filter((K,V)=>V%Q===0);let U=Number(F);return Number.isFinite(U)?[U].filter((K)=>K>=C&&K<=D):[]}let G=Number(q);return Number.isFinite(G)&&G>=C&&G<=D?[G]:[]}static createJobFromConfig(q,C="default"){let D={cron:q.schedule?.cron||"0 2 * * 1",timezone:q.schedule?.timezone,runOnStartup:!1,maxRuntime:1800000};return{id:C,name:`Buddy Dependency Updates (${C})`,schedule:D,status:"idle",config:q}}static PRESETS={DAILY:"0 2 * * *",WEEKLY:"0 2 * * 1",WEEKDAYS:"0 2 * * 1-5",TWICE_WEEKLY:"0 2 * * 1,4",MONTHLY:"0 2 1 * *",HOURLY:"0 * * * *",CUSTOM:(q,C,D="*")=>`${q} ${C} * * ${D}`}}
|
|
3
|
+
export{L as Pa};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{tk as g,uk as j}from"./chunk-8661pvb8.js";import{Fk as A}from"./chunk-6g1y9yqh.js";import u from"fs";import k from"path";import v from"process";j();var p=k.join(v.cwd(),"github-rate-limit.json"),h=k.join(v.cwd(),"github-cache.json"),S=10,d=3600000;function $(t){try{let e=t.get("X-RateLimit-Remaining"),i=t.get("X-RateLimit-Reset"),n=t.get("X-RateLimit-Limit");if(e&&i&&n){let a=new Date(Number(i)*1000),r={remaining:Number(e),limit:Number(n),resetTime:a.toISOString(),resetTimestamp:Number(i)*1000,lastUpdated:new Date().toISOString()};u.writeFileSync(p,JSON.stringify(r,null,2)),console.warn(`GitHub API rate limit info saved to ${p}`),console.warn(`Rate limit: ${e}/${n} remaining, resets at ${a.toLocaleString()}`)}}catch(e){console.error("Failed to save GitHub rate limit info:",e)}}function b(){try{if(!u.existsSync(p))return!0;let t=JSON.parse(u.readFileSync(p,"utf8"));if(!t||typeof t.resetTimestamp!=="number"||typeof t.remaining!=="number")return!0;let e=Date.now();if(e>=t.resetTimestamp)return!0;if(t.remaining<=S){let i=new Date(t.resetTimestamp);console.warn(`GitHub API rate limit almost exhausted (${t.remaining}/${t.limit} remaining). Preserving remaining calls until reset at ${i.toLocaleString()}`);let n=t.resetTimestamp-e;if(n<300000)console.error(`Waiting ${Math.round(n/1000)} seconds for rate limit to reset...`);return!1}return!0}catch(t){return console.error("Error checking GitHub rate limit:",t),!0}}function G(){try{if(!u.existsSync(h))return null;let t=JSON.parse(u.readFileSync(h,"utf8")),e=Date.now();if(t.timestamp&&e-t.timestamp<d){let i=new Date(t.timestamp+d);if(console.error(`Using GitHub API cache from ${new Date(t.timestamp).toLocaleString()}, expires at ${i.toLocaleString()}`),Array.isArray(t.packages))return console.error(`Using ${t.packages.length} packages from GitHub API cache`),t.packages;else if(Array.isArray(t.data))return console.error(`Using ${t.data.length} packages from GitHub API cache (old format)`),t.data;else return console.error("GitHub API cache has invalid format, fetching fresh data"),null}return console.error(`GitHub API cache expired (older than ${d/1000/60} minutes), fetching fresh data`),null}catch(t){return console.error("Error reading GitHub cache:",t),null}}function y(t){try{let e={timestamp:Date.now(),packages:t};u.writeFileSync(h,JSON.stringify(e,null,2)),console.error(`GitHub API package list cached to ${h} (${t.length} packages)`)}catch(e){console.error("Error saving GitHub cache:",e)}}async function F(t=0,e){if(e){if(e.startsWith("/")||e.includes("/bin/"))return console.error(`Error: '${e}' appears to be a path, not a valid package name.`),[];return console.log(`Single package mode: only fetching '${e}'`),[e]}console.log("Fetching package list from GitHub API...");let i=G();if(i)return console.log("Using cached package list, no GitHub API calls needed"),t>0?i.slice(0,t):i;try{if(!b()){console.warn("GitHub API rate limit preventing request - using cached data or hardcoded list");let o=["node","bun.sh","python.org","go.dev","rust-lang.org","deno.land","ruby-lang.org","php.net","dart.dev","postgresql.org","mozilla.org","mysql.com","nginx.org","redis.io","mongodb.com"];return y(o),t>0?o.slice(0,t):o}console.error("No valid cache found, making GitHub API requests");let n=await fetch("https://api.github.com/repos/pkgxdev/pantry/contents/projects",{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"ts-pantry"}});if($(n.headers),!n.ok)throw Error(`GitHub API responded with ${n.status}: ${n.statusText}`);let a=(await n.json()).filter((o)=>o.type==="dir").map((o)=>o.name);console.error(`Found ${a.length} base projects on GitHub`);let r=[...a],c=["agwa.name","acorn.io","apache.org","aquasecurity.github.io","aws.amazon.com"],s=["alsa-project.org/alsa-lib","apple.com/remote_cmds","android.com/cmdline-tools","anchore.com/syft","argoproj.github.io/cd","argoproj.github.io/workflows","amrdeveloper.github.io/GQL","authzed.com/spicedb","arduino.github.io/arduino-cli","aomedia.googlesource.com/aom","akuity.io/kargo","asciinema.org/agg","ansible.com/ansible-lint","astral.sh/ruff","astral.sh/uv","apollographql.com/rover","brxken128.github.io/dexios","cedarpolicy.com/cli","blake2.net/libb2"];for(let o of c){if(!b()){console.error(`Skipping nested path check for ${o} due to rate limit concerns`);continue}try{console.error(`Checking for nested projects in ${o}...`);let l=await fetch(`https://api.github.com/repos/pkgxdev/pantry/contents/projects/${o}`,{headers:{Accept:"application/vnd.github.v3+json","User-Agent":"ts-pantry"}});if($(l.headers),!l.ok){console.error(`Failed to fetch nested projects for ${o}: ${l.status}`);continue}let f=(await l.json()).filter((m)=>m.type==="dir").map((m)=>`${o}/${m.name}`);console.error(`Found ${f.length} nested projects for ${o}: ${f.join(", ")}`),r.push(...f)}catch(l){console.error(`Error fetching nested projects for ${o}:`,l)}}for(let o of s)if(!r.includes(o))console.error(`Adding known nested project: ${o}`),r.push(o);y(r),console.error(`Cached ${r.length} packages for future use (valid for ${d/60000} minutes)`);let W=t>0?r.slice(0,t):r;return console.error(`Total of ${r.length} projects found (including nested paths)`),W}catch(n){return console.error("Error fetching package list from GitHub:",n),[]}}async function N(){try{let{fetchPkgxProjects:t}=await import("./chunk-da3wbh04.js"),e=await t();if(console.error(`Found ${e.length} projects`),e.length>0){if(console.error("First 10 projects:"),e.slice(0,10).forEach((i)=>{console.error(`- ${i.name}`)}),e.length>10)console.error(`... and ${e.length-10} more`)}return e}catch(t){return console.error("Failed to fetch projects:",t),[]}}function w(t,e=2){if(t===null)return"null";if(t===void 0)return"undefined";if(Array.isArray(t)){if(t.length===0)return"[]";if(t.every((n)=>typeof n==="string")){if(t.length===1)return`[${JSON.stringify(t[0])}]`;let n=t.map((a)=>JSON.stringify(a)).join(`,
|
|
3
|
+
${" ".repeat(e)}`);return`[
|
|
4
|
+
${" ".repeat(e)}${n}
|
|
5
|
+
${" ".repeat(e-2)}]`}let i=t.map((n)=>w(n,e+2)).join(`,
|
|
6
|
+
${" ".repeat(e+2)}`);return`[
|
|
7
|
+
${" ".repeat(e+2)}${i}
|
|
8
|
+
${" ".repeat(e)}]`}if(typeof t==="object")return`{
|
|
9
|
+
${Object.entries(t).map(([i,n])=>{let a=typeof n==="string"?JSON.stringify(n):w(n,e+2);return`${" ".repeat(e)}${i}: ${a}`}).join(`,
|
|
10
|
+
`)}
|
|
11
|
+
}`;return String(t)}function O(t){if(t.includes("/")){let e=t.split("/"),i=e[0],n=e.slice(1),a=i.replace(/[.-]/g,""),r=n.map((s)=>s.replace(/[.-]/g,"")),c="";if(r.length>0){let s=r[0];if(a.includes(s.toLowerCase()))c="";else if(r.length===1)c=s;else c=s}return`${a}${c}`.toLowerCase()}return t.replace(/[.-]/g,"").toLowerCase()}function D(t){if(t.includes("/")){let e=t.split("/"),i=e[0],n=e.slice(1).join("/"),a=i.replace(/\./g,""),r=n.replace(/\//g,"-");return`${a}-${r}`.toLowerCase()}return t.replace(/\./g,"").toLowerCase()}function E(t){if(t.includes("-")){let i=t.indexOf("-"),n=t.substring(0,i),a=t.substring(i+1),r=n;if(r.endsWith("org")&&!r.endsWith(".org"))r=r.replace(/org$/,".org");if(r.endsWith("io")&&!r.endsWith(".io"))r=r.replace(/io$/,".io");if(r.endsWith("com")&&!r.endsWith(".com"))r=r.replace(/com$/,".com");if(r.endsWith("sh")&&!r.endsWith(".sh"))r=r.replace(/sh$/,".sh");if(r.endsWith("dev")&&!r.endsWith(".dev"))r=r.replace(/dev$/,".dev");if(r.endsWith("net")&&!r.endsWith(".net"))r=r.replace(/net$/,".net");if(r.endsWith("name")&&!r.endsWith(".name"))r=r.replace(/name$/,".name");return`${r}/${a}`}let e=t;if(e.endsWith("org")&&!e.endsWith(".org"))e=e.replace(/org$/,".org");if(e.endsWith("io")&&!e.endsWith(".io"))e=e.replace(/io$/,".io");if(e.endsWith("com")&&!e.endsWith(".com"))e=e.replace(/com$/,".com");if(e.endsWith("sh")&&!e.endsWith(".sh"))e=e.replace(/sh$/,".sh");if(e.endsWith("dev")&&!e.endsWith(".dev"))e=e.replace(/dev$/,".dev");if(e.endsWith("net")&&!e.endsWith(".net"))e=e.replace(/net$/,".net");if(e.endsWith("land")&&!e.endsWith(".land"))e=e.replace(/land$/,".land");return e}function H(t){let[e]=t.split("@");if(g[e])return g[e];if(e.includes("."))return e;return`${e}.org`}function T(){return{...g}}function Z(t){let[e]=t.split("@");return e in g}function q(t){return H(t)}
|
|
12
|
+
export{$ as Sj,b as Tj,G as Uj,y as Vj,F as Wj,N as Xj,w as Yj,O as Zj,D as _j,E as $j,H as ak,T as bk,Z as ck,q as dk};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
// @bun
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Lj as M}from"./chunk-1h3ey7k5.js";import{Oj as K,Rj as Q}from"./chunk-akffynkc.js";class V{token;apiUrl;logger;slug;constructor(j,z,A,C,F){this.token=j;this.apiUrl=(C??"https://api.bitbucket.org/2.0").replace(/\/+$/,""),this.logger=F??Q(),this.slug=`${encodeURIComponent(z)}/${encodeURIComponent(A)}`}capabilities(){return{pinIssues:!1,checkRuns:!0,inlineReviewComments:!0,reviewSuggestions:!1,nativeAutoMerge:!1,commentReactions:!1,ciLogs:!1,teamReviewers:!1,draftPullRequests:!1,permissionLookup:!0,branchHousekeeping:!0,reopenPullRequests:!1,labels:!1}}async request(j,z,A,C={}){let F={Authorization:`Bearer ${this.token}`,Accept:C.raw?"text/plain":"application/json","User-Agent":"buddy"},H;if(C.form)F["Content-Type"]="application/x-www-form-urlencoded",H=new URLSearchParams(C.form).toString();else if(A)F["Content-Type"]="application/json",H=JSON.stringify(A);let G=await M(`${this.apiUrl}${z}`,{method:j,headers:F,...H?{body:H}:{}});if(!G.ok){let J=await G.text().catch(()=>"");throw Error(`Bitbucket ${j} ${z} failed: ${G.status} ${J.slice(0,200)}`)}let I=await G.text();if(C.raw)return I;return I.trim()?JSON.parse(I):void 0}async optional(j,z){try{return await this.request(j,z)}catch(A){if(String(A).includes("404"))return null;throw A}}async collect(j,z=10){let A=[],C=`${this.apiUrl}${j}`;for(let F=0;F<z&&C;F++){let H=C,G=await this.optional("GET",H.startsWith(this.apiUrl)?H.slice(this.apiUrl.length):H);if(!G)break;A.push(...G.values??[]),C=G.next}return A}async branchExists(j){return await this.optional("GET",`/repositories/${this.slug}/refs/branches/${encodeURIComponent(j)}`)!==null}async createBranch(j,z){await this.request("POST",`/repositories/${this.slug}/refs/branches`,{name:j,target:{hash:z}})}async deleteBranch(j){await this.request("DELETE",`/repositories/${this.slug}/refs/branches/${encodeURIComponent(j)}`)}async commitChanges(j,z,A,C="main"){if(A.length===0)return;let F={message:z,branch:j};for(let I of A)if(I.type==="delete")F.files=F.files?`${F.files},${I.path}`:I.path;else F[I.path]=I.content;let H=new URLSearchParams;for(let[I,J]of Object.entries(F)){if(I==="files")continue;H.append(I,J)}for(let I of A)if(I.type==="delete")H.append("files",I.path);let G=await this.headOf(C);if(G)H.append("parents",G);await this.request("POST",`/repositories/${this.slug}/src`,void 0,{form:Object.fromEntries(H.entries())})}async headOf(j){return(await this.optional("GET",`/repositories/${this.slug}/refs/branches/${encodeURIComponent(j)}`))?.target?.hash??null}async getFileContent(j,z){try{return await this.request("GET",`/repositories/${this.slug}/src/${encodeURIComponent(z)}/${j}`,void 0,{raw:!0})}catch(A){if(String(A).includes("404"))return null;throw A}}async createPullRequest(j){if(j.draft)this.logger.debug("Bitbucket has no draft pull requests; opening as ready");let z=await this.request("POST",`/repositories/${this.slug}/pullrequests`,{title:j.title,description:j.body,source:{branch:{name:j.head}},destination:{branch:{name:j.base}},close_source_branch:!0,...j.reviewers?.length?{reviewers:j.reviewers.map((A)=>({nickname:A}))}:{}});return this.toPullRequest(z)}async getPullRequests(j="open"){let A=(j==="open"?["OPEN"]:j==="closed"?["MERGED","DECLINED","SUPERSEDED"]:["OPEN","MERGED","DECLINED","SUPERSEDED"]).map((F)=>`state=${F}`).join("&");return(await this.collect(`/repositories/${this.slug}/pullrequests?${A}&pagelen=50`)).map((F)=>this.toPullRequest(F))}async updatePullRequest(j,z){let A=await this.request("PUT",`/repositories/${this.slug}/pullrequests/${j}`,{...z.title!==void 0?{title:z.title}:{},...z.body!==void 0?{description:z.body}:{},...z.base!==void 0?{destination:{branch:{name:z.base}}}:{}});return this.toPullRequest(A)}async closePullRequest(j){await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/decline`)}async reopenPullRequest(j){throw Error(`Bitbucket cannot reopen declined pull request #${j}; open a new one from the same branch.`)}async mergePullRequest(j,z="squash"){let A={merge:"merge_commit",squash:"squash",rebase:"fast_forward"};await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/merge`,{merge_strategy:A[z]??"squash",close_source_branch:!0})}async getPullRequestDiff(j){return await this.request("GET",`/repositories/${this.slug}/pullrequests/${j}/diff`,void 0,{raw:!0})}async getPullRequestHeadSha(j){return(await this.request("GET",`/repositories/${this.slug}/pullrequests/${j}`)).source?.commit?.hash??""}async createComment(j,z){await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/comments`,{content:{raw:z}})}async createIssue(j){let z=await this.request("POST",`/repositories/${this.slug}/issues`,{title:j.title,content:{raw:j.body},kind:"task"});return this.toIssue(z)}async getIssues(j="open"){let A=(await this.collect(`/repositories/${this.slug}/issues?pagelen=50`)).map((C)=>this.toIssue(C));return j==="all"?A:A.filter((C)=>C.state===j)}async updateIssue(j,z){let A=await this.request("PUT",`/repositories/${this.slug}/issues/${j}`,{...z.title!==void 0?{title:z.title}:{},...z.body!==void 0?{content:{raw:z.body}}:{}});return this.toIssue(A)}async closeIssue(j){await this.request("PUT",`/repositories/${this.slug}/issues/${j}`,{state:"closed"})}async unpinIssue(j){return!1}async getPullRequestChecksState(j){let z=await this.getPullRequestHeadSha(j);if(!z)return"none";let A=await this.collect(`/repositories/${this.slug}/commit/${z}/statuses?pagelen=50`);if(A.length===0)return"none";if(A.some((C)=>C.state==="FAILED"||C.state==="STOPPED"))return"failure";if(A.some((C)=>C.state==="INPROGRESS"))return"pending";if(A.every((C)=>C.state==="SUCCESSFUL"))return"success";return"pending"}async createReview(j,z){if(await this.createComment(j,z.body),!z.comments?.length)return{posted:!0,inlineComments:0};let A=0;for(let C of z.comments)try{await this.request("POST",`/repositories/${this.slug}/pullrequests/${j}/comments`,{content:{raw:C.body},inline:{path:C.path,...C.side==="RIGHT"?{to:C.line}:{from:C.line}}}),A++}catch(F){this.logger.debug(`Could not place a comment on ${C.path}:${C.line}: ${K(F)}`)}return{posted:!0,inlineComments:A}}async createCheckRun(j,z,A){try{await this.request("POST",`/repositories/${this.slug}/commit/${z}/statuses/build`,{key:j.replace(/[^\w-]/g,"-").slice(0,40),state:A.conclusion==="failure"?"FAILED":"SUCCESSFUL",name:A.title.slice(0,100),description:A.summary.slice(0,300),url:"https://buddy.sh"})}catch(C){this.logger.warn(`\u26A0\uFE0F Could not report build status ${j}: ${K(C)}`)}}async hasWriteAccess(j){let A=(await this.optional("GET",`/repositories/${this.slug}/permissions-config/users`))?.values?.find((C)=>C.user?.nickname===j);return A?.permission==="write"||A?.permission==="admin"}async getBuddyBranches(){return(await this.collect(`/repositories/${this.slug}/refs/branches?q=${encodeURIComponent('name ~ "buddy/"')}&pagelen=50`)).filter((z)=>z.name?.startsWith("buddy/")).map((z)=>({name:z.name,sha:z.target?.hash??"",lastCommitDate:z.target?.date?new Date(z.target.date):new Date(0)}))}async getOrphanedBuddyBranches(){let[j,z]=await Promise.all([this.getBuddyBranches(),this.getPullRequests("open")]),A=new Set(z.map((C)=>C.head));return j.filter((C)=>!A.has(C.name))}async cleanupStaleBranches(j=7,z=!1){let A=new Date(Date.now()-j*24*60*60*1000),C=(await this.getOrphanedBuddyBranches()).filter((G)=>G.lastCommitDate<A);if(z)return{deleted:C.map((G)=>G.name),failed:[]};let F=[],H=[];for(let G of C)try{await this.deleteBranch(G.name),F.push(G.name)}catch{H.push(G.name)}return{deleted:F,failed:H}}toPullRequest(j){let z=j.state==="MERGED"?"merged":j.state==="OPEN"?"open":"closed";return{number:j.id,title:j.title,body:j.description??"",head:j.source?.branch?.name??"",base:j.destination?.branch?.name??"",state:z,url:j.links?.html?.href??"",createdAt:new Date(j.created_on),updatedAt:new Date(j.updated_on),...z==="merged"?{mergedAt:new Date(j.updated_on)}:{},author:j.author?.nickname??j.author?.display_name??"",reviewers:(j.reviewers??[]).map((A)=>A.nickname??A.display_name??"").filter(Boolean),assignees:[],labels:[],draft:!1}}toIssue(j){let z=["new","open","on hold"].includes(j.state);return{number:j.id,title:j.title,body:j.content?.raw??"",state:z?"open":"closed",url:j.links?.html?.href??"",createdAt:new Date(j.created_on),updatedAt:new Date(j.updated_on),...z?{}:{closedAt:new Date(j.updated_on)},author:j.reporter?.nickname??j.reporter?.display_name??"",assignees:[],labels:[]}}}
|
|
3
|
+
export{V as Gj};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{existsSync as O,readdirSync as R,statSync as A}from"fs";import{join as U,relative as L}from"path";function T(z,K){try{let V=Bun.YAML.parse(K);if(!V||typeof V!=="object")return null;return{file:z,raw:K,data:V}}catch{return null}}function B(z,K){if(!K)return;let V=z.indexOf(K);if(V<0)return;let M=1;for(let Y=0;Y<V;Y++)if(z.charCodeAt(Y)===10)M++;return M}async function W(z){let K=U(z,".github","workflows");if(!O(K))return[];let V=R(K),M=[];for(let Y of V){if(!Y.endsWith(".yml")&&!Y.endsWith(".yaml"))continue;let Q=U(K,Y);if(!A(Q).isFile())continue;let Z=await Bun.file(Q).text(),N=T(L(z,Q),Z);if(N)M.push(N)}return M}function*X(z){let K=z.data.jobs;if(!K||typeof K!=="object")return;for(let[V,M]of Object.entries(K)){if(!M||typeof M!=="object")continue;let Y=M.steps;if(!Array.isArray(Y))continue;for(let Q=0;Q<Y.length;Q++){let Z=Y[Q];if(!Z||typeof Z!=="object")continue;yield{jobId:V,job:M,stepIndex:Q,step:Z}}}}function*$(z){let K=z.data.jobs;if(!K||typeof K!=="object")return;for(let[V,M]of Object.entries(K)){if(!M||typeof M!=="object")continue;yield{jobId:V,job:M}}}var F={id:"bash-injection",defaultSeverity:"error",description:"Avoid `${{ }}` interpolation of untrusted input inside `run:` blocks.",check(z){let K=[];for(let{jobId:V,step:M,stepIndex:Y}of X(z)){let Q=typeof M.run==="string"?M.run:null;if(!Q)continue;let Z=[...Q.matchAll(/\$\{\{\s*([^}]+?)\s*\}\}/g)];for(let N of Z){let C=N[1].trim();if(I(C))continue;K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Job \`${V}\`, step ${Y+1}: \`${C}\` is interpolated into a shell.`,detail:"GitHub evaluates `${{ ... }}` before the shell runs, so attacker-controlled values become part of the command line. Move the value into `env:` and reference it as a shell variable.",file:z.file,line:B(z.raw,N[0]),fix:'Put the value in `env:` and reference it with `"$NAME"` instead.'})}}return K}},_=["secrets.","vars.","runner.","env.","inputs.","matrix.","strategy.","job.","steps.","needs."],S=new Set(["github.repository","github.repository_owner","github.workflow","github.run_id","github.run_number","github.run_attempt","github.event_name","github.sha","github.ref_name","github.token","github.actor","github.actor_id","github.api_url","github.server_url","github.graphql_url","github.workspace","github.action","github.action_path","github.action_ref","github.action_repository","github.action_status","github.job","github.job_workflow_sha"]);function I(z){if(S.has(z))return!0;return _.some((K)=>z.startsWith(K))}var J={id:"dangerous-pull-request-target",defaultSeverity:"error",description:"Avoid checking out PR-author code from a `pull_request_target` workflow.",check(z){if(!x(z.data.on,"pull_request_target"))return[];let K=[];for(let{jobId:V,step:M}of X(z)){if(!(typeof M.uses==="string"?M.uses:"").startsWith("actions/checkout@"))continue;let Q=typeof M.with?.ref==="string"?M.with.ref:null;if(!Q)continue;if(Q.includes("pull_request")||Q.includes("head.sha")||Q.includes("head.ref")||Q.includes("github.head_ref"))K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Job \`${V}\` checks out PR-author code under \`pull_request_target\`.`,detail:"This grants attacker-controlled code access to repository secrets and write tokens. Move the build to `pull_request` or run untrusted code in a sandboxed second workflow without secrets.",file:z.file,line:B(z.raw,Q),fix:"Either switch the trigger to `pull_request`, or split into two workflows: one privileged (no checkout of head) and one unprivileged (checkout of head, no secrets)."})}return K}};function x(z,K){if(typeof z==="string")return z===K;if(Array.isArray(z))return z.includes(K);if(z&&typeof z==="object")return K in z;return!1}var q={id:"excessive-permissions",defaultSeverity:"warning",description:"Workflows and jobs should declare a least-privilege `permissions:` block.",check(z){let K=[],V=z.data.permissions;if(V===void 0)K.push({ruleId:this.id,severity:this.defaultSeverity,message:"Workflow does not declare top-level `permissions:`.",detail:"Without an explicit `permissions:` block, jobs inherit the repository default \u2014 historically `write-all`. Add a least-privilege block at the workflow root.",file:z.file,line:1,fix:"Add `permissions:\\n contents: read` at the top of the workflow, then narrow per-job as needed."});else if(V==="write-all")K.push({ruleId:this.id,severity:"error",message:"Workflow grants `permissions: write-all`.",file:z.file,line:B(z.raw,"write-all"),fix:"Replace with explicit per-scope grants (e.g. `contents: read`, `pull-requests: write`)."});else if(V!=="read-all"&&typeof V==="object")K.push(...P(this.id,z.file,z.raw,V,"workflow"));for(let{jobId:M,job:Y}of $(z)){let Q=Y.permissions;if(Q===void 0)continue;if(Q==="write-all")K.push({ruleId:this.id,severity:"error",message:`Job \`${M}\` grants \`permissions: write-all\`.`,file:z.file,line:B(z.raw,"write-all"),fix:"Replace with explicit per-scope grants."});else if(Q!=="read-all"&&typeof Q==="object")K.push(...P(this.id,z.file,z.raw,Q,`job \`${M}\``))}return K}};function P(z,K,V,M,Y){let Q=[];if(typeof M!=="object"||M===null)return Q;for(let[Z,N]of Object.entries(M))if(N==="write"&&(Z==="actions"||Z==="id-token"))Q.push({ruleId:z,severity:"warning",message:`${Y} grants \`${Z}: write\` \u2014 verify this is required.`,detail:Z==="id-token"?"`id-token: write` is needed for OIDC federation but should never be combined with running untrusted code.":"`actions: write` allows the workflow to dispatch other workflows, increasing blast radius if compromised.",file:K,line:B(V,`${Z}: write`)});return Q}var D={id:"missing-timeout",defaultSeverity:"warning",description:"Jobs should declare an explicit `timeout-minutes` to bound runaway execution.",check(z){let K=[];for(let{jobId:V,job:M}of $(z)){let Y=M["timeout-minutes"];if(typeof Y==="number"&&Y>0)continue;K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Job \`${V}\` has no \`timeout-minutes\`.`,file:z.file,line:B(z.raw,`${V}:`),fix:"Add `timeout-minutes: <n>` (15\u201360 is a reasonable default for most CI jobs)."})}return K}};var G={id:"self-hosted-exposure",defaultSeverity:"warning",description:"Self-hosted runners should be scoped with additional labels, not used bare.",check(z){let K=[];for(let{jobId:V,job:M}of $(z)){let Y=M["runs-on"];if(!Y)continue;if(typeof Y==="string"){if(Y==="self-hosted")K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Job \`${V}\` uses bare \`runs-on: self-hosted\`.`,file:z.file,line:B(z.raw,"runs-on: self-hosted"),fix:"Add at least one scoping label, e.g. `runs-on: [self-hosted, my-project]`, and disable persistence on the runner."});continue}if(Array.isArray(Y)){let Q=Y.filter((Z)=>typeof Z==="string");if(Q.includes("self-hosted")&&Q.length===1)K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Job \`${V}\` uses \`runs-on: [self-hosted]\` with no additional labels.`,file:z.file,line:B(z.raw,"self-hosted"),fix:"Add at least one scoping label (project name, environment) so the pool is explicit."})}}return K}};var v=/^[0-9a-f]{40}$/i,E={id:"unpinned-action",defaultSeverity:"warning",description:"Third-party actions should be pinned to a full commit SHA, not a tag or branch.",check(z){let K=[];for(let{step:V}of X(z)){let M=typeof V.uses==="string"?V.uses:null;if(!M)continue;if(M.startsWith("./")||M.startsWith("docker://"))continue;let Y=M.lastIndexOf("@");if(Y<0){K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Action \`${M}\` is missing a version reference.`,file:z.file,line:B(z.raw,M),fix:`Pin to a commit SHA: \`${M}@<full-sha> # vX.Y.Z\``});continue}let Q=M.slice(0,M.indexOf("/")),Z=M.slice(Y+1);if(Q==="actions"||Q==="github")continue;if(v.test(Z))continue;K.push({ruleId:this.id,severity:this.defaultSeverity,message:`Action \`${M}\` is pinned to a mutable ref (\`${Z}\`).`,file:z.file,line:B(z.raw,M),fix:`Replace with a SHA-pinned reference: \`${M.slice(0,Y)}@<full-sha> # ${Z}\``})}return K}};var H=[E,q,J,F,D,G];async function Tz(z,K={}){let V=await W(z);return y(V,K)}function y(z,K={}){let V=(K.rules??H).filter((Q)=>{return!K.ignore?.includes(Q.id)}),M=[];for(let Q of z)for(let Z of V){let N=Z.check(Q);for(let C of N)M.push(C)}let Y=M.some((Q)=>Q.severity==="error");return{workflows:z,findings:M,failed:Y}}
|
|
3
|
+
export{Tz as Ed,y as Fd};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Lj as X}from"./chunk-1h3ey7k5.js";import{Rj as Z}from"./chunk-akffynkc.js";var V={node:"nodejs","library/node":"nodejs",python:"python","library/python":"python",debian:"debian","library/debian":"debian",ubuntu:"ubuntu","library/ubuntu":"ubuntu",alpine:"alpine","library/alpine":"alpine",php:"php","library/php":"php",ruby:"ruby","library/ruby":"ruby",golang:"go","library/golang":"go",postgres:"postgresql","library/postgres":"postgresql",mysql:"mysql","library/mysql":"mysql",redis:"redis","library/redis":"redis",nginx:"nginx","library/nginx":"nginx"};function q(j){let x=j.replace(/^(?:docker\.io|registry-1\.docker\.io)\//,"");return V[x]??V[x.split("/").pop()??""]??null}function G(j,x){let z=/^v?(\d+(?:\.\d+)*)/.exec(j.trim());if(!z)return null;let H=z[1].split(".");for(let k=H.length;k>=1;k--){let K=H.slice(0,k).join("."),B=x.find((J)=>J.cycle===K);if(B)return B}return null}async function F(j,x,z={}){let H=z.logger??Z(),k=q(j);if(!k)return null;let K=z.baseUrl??"https://endoflife.date",B=await X(`${K}/api/${k}.json`,{headers:{"User-Agent":"buddy",Accept:"application/json"}}).catch(()=>null);if(!B?.ok)return H.debug(`Could not read the support window for ${k}`),null;let J=await B.json().catch(()=>null);if(!Array.isArray(J))return null;let v=G(x,J);if(!v)return null;if(v.eol===!1)return{product:k,cycle:v.cycle,eol:!1};if(v.eol===!0)return{product:k,cycle:v.cycle,eol:!0};let M=new Date(v.eol);if(Number.isNaN(M.getTime()))return{product:k,cycle:v.cycle,eol:!1};let $=z.now??new Date,Q=Math.round((M.getTime()-$.getTime())/86400000);return{product:k,cycle:v.cycle,eol:Q<0,date:v.eol,daysRemaining:Q}}var I=90;function N(j){if(!j)return"";if(j.eol)return j.date?`\`${j.product} ${j.cycle}\` reached end of life on ${j.date} and no longer receives security fixes.`:`\`${j.product} ${j.cycle}\` has reached end of life and no longer receives security fixes.`;if(j.daysRemaining!==void 0&&j.daysRemaining<=I)return`\`${j.product} ${j.cycle}\` reaches end of life in ${j.daysRemaining} day(s), on ${j.date}.`;return""}
|
|
3
|
+
export{V as Ja,q as Ka,G as La,F as Ma,I as Na,N as Oa};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{D as s,E as t,F as u,G as v,H as w,c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i,l as j,m as k,n as l,o as m,p as n,q as o,u as p,v as q,w as r}from"./chunk-r2sbprdb.js";import"./chunk-6g1y9yqh.js";export{r as toFile,v as default,w as betaRefusalFallbackMiddleware,l as UnprocessableEntityError,f as RetryableError,m as RateLimitError,i as PermissionDeniedError,q as PagePromise,j as NotFoundError,n as InternalServerError,s as HUMAN_PROMPT,k as ConflictError,o as BetaFallbackState,u as BaseAnthropic,g as BadRequestError,h as AuthenticationError,a as AnthropicError,v as Anthropic,c as APIUserAbortError,p as APIPromise,b as APIError,e as APIConnectionTimeoutError,d as APIConnectionError,t as AI_PROMPT};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{$e as m,Pe as a,Qe as b,Re as c,Se as d,Te as e,Ue as f,Ve as g,We as h,Xe as i,Ye as j,Ze as k,_e as l}from"./chunk-978wtejw.js";import"./chunk-pkkwb0n0.js";import"./chunk-ph1b3vbp.js";import"./chunk-0j7z87kh.js";import"./chunk-7mgec8kb.js";import"./chunk-5k40mwd4.js";import"./chunk-1h3ey7k5.js";import"./chunk-akffynkc.js";import"./chunk-x3kragh9.js";import"./chunk-wdwvt7gb.js";import"./chunk-8661pvb8.js";import"./chunk-ctsz0ynx.js";import"./chunk-vkctfqpm.js";import"./chunk-6g1y9yqh.js";export{h as sortUpdatesByPriority,j as satisfiesRange,a as parsePackageFile,g as groupUpdates,i as getUpdateType,f as generateBranchName,d as formatPRTitle,e as formatPRBody,c as formatCommitMessage,l as extractPackageNamesFromPRBody,b as detectPackageManager,k as checkForRebaseRequests,m as checkForAutoClose};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{oi as K,pi as B}from"./chunk-bxfc4g2x.js";var J=`Verify your work before reporting it done: run the project's
|
|
3
|
+
tests or build if one exists. If verification fails, report what failed rather
|
|
4
|
+
than claiming success \u2014 a change that looks right and breaks the build costs
|
|
5
|
+
more than no change at all.`,L={name:"docstrings",description:"Add missing doc comments to changed public APIs",mode:B,defaultOutput:"commit",buildTask:({files:j})=>["Add missing documentation comments to the public APIs changed on this branch.","","Follow the documentation style already used in the surrounding code \u2014 match its","density and conventions rather than importing a different house style.","Document what a caller needs: parameters, return value, thrown errors, and any","constraint the signature does not already show. Do not restate what the code says.","","Do not document code that was not changed, and do not modify behaviour.",j?.length?`
|
|
6
|
+
Changed files:
|
|
7
|
+
${j.map((q)=>`- ${q}`).join(`
|
|
8
|
+
`)}`:""].filter(Boolean).join(`
|
|
9
|
+
`)},Q={name:"unit-tests",description:"Write tests covering the changed behaviour",mode:B,defaultOutput:"stacked-pr",buildTask:({files:j})=>["Write tests covering the behaviour changed on this branch.","","Follow the existing test suite's structure and naming. Cover the success path,","the failure path, and any edge case the change introduces.","","Run the tests you write. A generated test that does not pass is worse than none,","so if you cannot make one pass, report why instead of committing it.","",J,j?.length?`
|
|
10
|
+
Changed files:
|
|
11
|
+
${j.map((q)=>`- ${q}`).join(`
|
|
12
|
+
`)}`:""].filter(Boolean).join(`
|
|
13
|
+
`)},W={name:"autofix",description:"Apply the committable suggestions from the review",mode:B,defaultOutput:"commit",buildTask:({summary:j})=>["Apply the fixes identified by the review on this pull request.","","Apply only what the findings describe. Do not take the opportunity to refactor,","rename, or tidy surrounding code \u2014 an autofix commit that also does unrelated","work is one a reviewer has to disentangle.","",J,j?`
|
|
14
|
+
Findings:
|
|
15
|
+
${j}`:""].filter(Boolean).join(`
|
|
16
|
+
`)},X={name:"simplify",description:"Simplify the changed code without altering behaviour",mode:B,defaultOutput:"suggestion",buildTask:({files:j})=>["Simplify the code changed on this branch without altering its behaviour.","","Look for duplicated logic, unnecessary indirection, and conditions that can be","expressed more directly. Leave the code recognisable to whoever wrote it.","","Behaviour must not change. If a simplification would alter an edge case, leave it","and say so.","",J,j?.length?`
|
|
17
|
+
Changed files:
|
|
18
|
+
${j.map((q)=>`- ${q}`).join(`
|
|
19
|
+
`)}`:""].filter(Boolean).join(`
|
|
20
|
+
`)},Z={name:"plan",description:"Produce an implementation plan",mode:K,defaultOutput:"suggestion",buildTask:({summary:j})=>["Produce an implementation plan for the request below.","","Name the files that would change and why, the order of the work, the risks, and","how the result would be verified. Write it so another agent could execute it","without re-deriving your reasoning.","","Do not change anything \u2014 this is a plan, not an implementation.",j?`
|
|
21
|
+
Request:
|
|
22
|
+
${j}`:""].filter(Boolean).join(`
|
|
23
|
+
`)},A={docstrings:L,"unit-tests":Q,autofix:W,simplify:X,plan:Z};function g(j){let q=A[j];if(!q)throw Error(`Unknown finishing touch: ${j}. Available: ${Object.keys(A).join(", ")}`);return q}function k(j=Object.keys(A)){let q=j.map((z)=>A[z]).filter(Boolean).map((z)=>` - [ ] <!-- buddy:touch=${z.name} -->${z.description}`);if(q.length===0)return"";return`<details><summary>Finishing touches</summary>
|
|
24
|
+
|
|
25
|
+
Tick one to have it run:
|
|
26
|
+
|
|
27
|
+
${q.join(`
|
|
28
|
+
`)}
|
|
29
|
+
|
|
30
|
+
</details>`}function v(j){if(!j)return[];let q=[],z=/^\s*-\s*\[[xX]\]\s*<!--\s*buddy:touch=([\w-]+)\s*-->/gm;for(let D of j.matchAll(z))if(A[D[1]]&&!q.includes(D[1]))q.push(D[1]);return q}
|
|
31
|
+
export{L as ja,Q as ka,W as la,X as ma,Z as na,A as oa,g as pa,k as qa,v as ra};
|