@gitkraken/provider-apis 0.29.2 → 0.29.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Qr=Object.create;var Ie=Object.defineProperty;var jr=Object.getOwnPropertyDescriptor;var Fr=Object.getOwnPropertyNames;var zr=Object.getPrototypeOf,Mr=Object.prototype.hasOwnProperty;var Q=(s,t)=>{for(var e in t)Ie(s,e,{get:t[e],enumerable:!0})},tr=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Fr(t))!Mr.call(s,n)&&n!==e&&Ie(s,n,{get:()=>t[n],enumerable:!(r=jr(t,n))||r.enumerable});return s};var Wr=(s,t,e)=>(e=s!=null?Qr(zr(s)):{},tr(t||!s||!s.__esModule?Ie(e,"default",{value:s,enumerable:!0}):e,s)),Hr=s=>tr(Ie({},"__esModule",{value:!0}),s);var Cn={};Q(Cn,{AzureDevOps:()=>se,AzureDevopsUtils:()=>ze,Bitbucket:()=>ne,BitbucketServer:()=>oe,BitbucketServerUtils:()=>We,BitbucketUtils:()=>Me,EntityIdentifierProviderType:()=>T,EntityIdentifierUtils:()=>nt,EntityType:()=>k,EntityVersion:()=>O,GitBuildStatusStage:()=>rr,GitBuildStatusState:()=>me,GitDiffLineType:()=>pt,GitHub:()=>ae,GitHubIssueCloseReason:()=>Br,GitHubUtils:()=>it,GitIssueState:()=>ve,GitLab:()=>le,GitLabUtils:()=>at,GitMergeStrategy:()=>re,GitProviderUtils:()=>ot,GitPullRequestMergeableState:()=>M,GitPullRequestReviewState:()=>j,GitPullRequestState:()=>ee,GraphQLErrors:()=>b,Jira:()=>pe,JiraServer:()=>de,JiraUtils:()=>ut,PullRequestAsyncStatus:()=>_r,Trello:()=>ce,TrelloUtils:()=>lt,Utils:()=>Sn,default:()=>qn,isFetch:()=>ye});module.exports=Hr(Cn);var rr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(rr||{}),me=(p=>(p.ActionRequired="ACTION_REQUIRED",p.Cancelled="CANCELLED",p.Error="ERROR",p.Failed="FAILED",p.Pending="PENDING",p.Running="RUNNING",p.Skipped="SKIPPED",p.Success="SUCCESS",p.Warning="WARNING",p.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",p))(me||{}),re=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(re||{}),ee=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(ee||{}),j=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(j||{}),M=(u=>(u.Behind="BEHIND",u.Blocked="BLOCKED",u.Conflicts="CONFLICTS",u.FailingChecks="FAILING_CHECKS",u.Mergeable="MERGEABLE",u.Unknown="UNKNOWN",u.UnknownAndBlocked="UNKNOWN_AND_BLOCKED",u.Unstable="UNSTABLE",u))(M||{}),pt=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(pt||{});var sr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},F=s=>!s||s.length===0?null:s.reduce((t,e)=>sr[e.state]>sr[t]?e.state:t,"APPROVED"),Re=(s,t)=>s.name||s.username||s.email||t,te=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var U=100;var nr=Wr(require("node-fetch")),or=globalThis.fetch||nr.default;var Jr=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let n=await s.text();e=n.trim().length>0?JSON.parse(n):null}else if(t.startsWith("text/")||t==="")e=await s.text();else if(t.startsWith("application/vnd.github.raw+json"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${t}`);let r={body:e,headers:Object.fromEntries(s.headers.entries()),status:s.status,statusText:s.statusText};if(!s.ok){let n=new Error(s.statusText);throw Object.assign(n,{response:r}),n}return r},dt=s=>async({url:t,...e})=>{let r=await s(t,e);return Jr(r)};var ye=(s,t=!1)=>s.name==="fetch"||t;var W=class{constructor(t){let e=(t==null?void 0:t.request)||or;this.config={...t,request:ye(e,t==null?void 0:t.forceIsFetch)?dt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&ye(t.request,(t==null?void 0:t.forceIsFetch)??this.config.forceIsFetch)?dt(t.request):this.config.request}}},x=class extends W{};var y=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},ir=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,X=(s,t,e)=>!s||t.some(r=>s[r])?e:"",ar=async s=>{var n,o,i;let t=[],e=!0,r;for(;e;){let a=await s(r);t=t.concat(a.data),e=!!((n=a==null?void 0:a.pageInfo)!=null&&n.hasNextPage),r=((o=a==null?void 0:a.pageInfo)==null?void 0:o.endCursor)||((i=a==null?void 0:a.pageInfo)==null?void 0:i.nextPage)}return t};var Vr="https://app.vssps.visualstudio.com/_apis",Kr="https://vssps.dev.azure.com/",Xr="https://dev.azure.com",q=(s,t={})=>y(t.token||s.token,t.isPAT||s.isPAT),ur=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),ct=(s,t)=>{let e=t.baseUrl||s.baseUrl||Vr;return e=e.replace(/\/$/,""),e},C=(s,t)=>{let e=t.baseUrl||s.baseUrl||Xr;return e=e.replace(/\/$/,""),e},gt=(s,t)=>{let e=t.baseUrl||s.baseUrl||Kr;return e=e.replace(/\/$/,""),e};var Yr={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Zr={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},mt=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Pe=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,es=s=>{switch(s){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},be=(s,t)=>{var n;let e=[],r=[];return t.reviewers.forEach(o=>{let i={reviewer:mt(o),state:Zr[o.vote??0]||"REVIEW_REQUESTED"};o.isRequired&&e.push(i),r.push(i)}),{id:t.pullRequestId.toString(),title:t.title,number:t.codeReviewId,state:Yr[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:mt(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Pe(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Pe(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:ur(t),assignees:t.reviewers.map(mt),reviews:r,reviewDecision:F(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:null}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:es(t.mergeStatus),labels:((n=t.labels)==null?void 0:n.map(o=>({color:null,description:null,id:o.id,name:o.name})))??[],permissions:null}},lr=(s,t)=>({id:t.id,name:t.name,namespace:s,project:t.project.name,projectId:t.project.id,webUrl:t.webUrl,httpsUrl:t.remoteUrl,sshUrl:t.sshUrl,defaultBranch:t.defaultBranch?{name:Pe(t.defaultBranch)}:null,permissions:null}),ts=(s,t,e,r)=>{var l,p,d,c,g,m;let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=(l=r[a])==null?void 0:l[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:((d=(p=n["System.CreatedBy"]._links)==null?void 0:p.avatar)==null?void 0:d.href)??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:((g=(c=o._links)==null?void 0:c.avatar)==null?void 0:g.href)??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:(u==null?void 0:u.title)||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,resourceId:null,key:null,id:null},upvoteCount:0,labels:((m=e.fields["System.Tags"])==null?void 0:m.split(";").map(I=>({color:null,description:null,id:null,name:I.trim()})))??[]}},se=class extends x{async getCurrentUser(t={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${ct(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:r,headers:q(this.config,e)});return{data:{id:n.body.id,name:n.body.displayName,username:n.body.displayName,email:n.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(t,e={}){let n=(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/ConnectionData`,headers:q(this.config,e)})).body.authorizedUser;if(n.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:n.id,name:n.providerDisplayName,username:n.providerDisplayName,email:n.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/commits/${t.oid}`,headers:q(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(t,e={}){let r=`${ct(this.config,e)}/accounts?memberId=${t.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:q(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(t,e={}){let r=`${C(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:q(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(t,e={}){let r=new URL(`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/projects`);r.searchParams.set("$top",U.toString()),t.cursor&&r.searchParams.set("$skip",t.cursor);let n=await this.config.request({url:r.toString(),headers:q(this.config,e)}),o=n.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:n.body.value.map(i=>({id:i.id,name:i.name,namespace:t.namespace}))}}async getAzureProjectScopeDescriptor(t,e={}){let{namespace:r,projectId:n}=t;return{data:{scope:(await this.config.request({url:`${gt(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:q(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(t,e={}){let{namespace:r,projectScopeDescriptor:n,cursor:o}=t,i=new URL(`${gt(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/users`);n&&i.searchParams.set("scopeDescriptor",n),o&&i.searchParams.set("continuationToken",o);let a=await this.config.request({url:i.toString(),headers:q(this.config,e)}),u=a.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:a.body.value.map(l=>{var p,d,c,g;return{avatarUrl:((d=(p=l._links)==null?void 0:p.avatar)==null?void 0:d.href)??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:((g=(c=l._links)==null?void 0:c.storageKey)==null?void 0:g.href)??null,username:l.displayName??null}})}}async getAccountFromAzureGraphAccount(t,e={}){let{azureGraphAccount:r}=t;if(!r.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let n=await this.config.request({url:r.storageKeyURL,headers:q(this.config,e)});return{data:{avatarUrl:r.avatarUrl,email:r.email,id:n.body.value,name:r.name,username:r.username,url:null}}}async getAccountsFromAzureGraphAccounts(t,e={}){let r=[];for(let n of t.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:n},e);r.push(o.data)}return{data:r}}async getRepo(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`,headers:q(this.config,e)});return{data:lr(t.namespace,r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories`,headers:q(this.config,e)})).body.value.map(n=>lr(t.namespace,n))}}async getRefs(t,e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=new URL(`${C(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",t),n.searchParams.set("$top",U.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:q(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:Pe(a.name),commit:{oid:a.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(t,e={}){return this.getRefs("heads",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getPullRequestsForRepoBase(t,e={},r=100){let{page:n,repo:o,assigneeLogins:i,authorLogin:a}=t||{},u=n||1;if(!o.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return i&&i.length&&(l+=`&searchCriteria.reviewerId=${i[0]}`),a&&(l+=`&searchCriteria.creatorId=${a}`),await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${r}&%24skip=${(u-1)*r}`,headers:q(this.config,e)})}async getPullRequestsForRepo(t,e={}){let n=t.page||1,o=await this.getPullRequestsForRepoBase(t,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:n+1},data:o.body.value.map(i=>be(t.repo.namespace,i))}}async getPullRequestsForRepos(t,e={}){if(!t.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...t},e)).body.value.forEach(a=>{n.push(be(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(t,e={},r=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=t;if(l!=null&&l.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let p=i||1,d=new URL(`${C(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",r.toString()),d.searchParams.set("$skip",((p-1)*r).toString()),l!=null&&l.id&&(l==null?void 0:l.project)===o&&d.searchParams.set("searchCriteria.repositoryId",l.id),a&&a.length&&d.searchParams.set("searchCriteria.reviewerId",a[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers:q(this.config,e)})}async getPullRequestsForProject(t,e={}){let n=t.page||1,o=await this.getPullRequestsForProjectBase(t,e,100);return{pageInfo:{hasNextPage:(o==null?void 0:o.body.value.length)===100,nextPage:n+1},data:(o==null?void 0:o.body.value.map(i=>be(t.namespace,i)))||[]}}async getPullRequestsForProjects(t,e={}){let{projects:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{if(!t.repo||t.repo.project&&t.repo.project===o.project){let i=await this.getPullRequestsForProjectBase({...o,...t},e);i==null||i.body.value.forEach(a=>{n.push(be(o.namespace,a))})}}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getAzurePullRequestLastMergeStatus(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:r,project:n,name:o},pullRequestId:i}=t,a=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...q(this.config,e)}});if(!a.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:a.body.mergeStatus}}async updatePullRequest(t,e,r){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}?api-version=6.0`,body:e,headers:{...q(this.config,r),"Content-Type":"application/json"}})}async closePullRequest(t,e={}){let{pullRequest:r}=t,n={status:"abandoned"};if(!(await this.updatePullRequest(r,JSON.stringify(n),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){var u;let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="noFastForward";break}case"REBASE":{o="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{o="rebaseMerge";break}case"SQUASH":{o="squash";break}}let i={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:(u=r.headRef)==null?void 0:u.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(i),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(t,e={}){let{pullRequest:r,label:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o={name:n.name};if(!(await this.config.request({method:"POST",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels?api-version=6.0`,body:JSON.stringify(o),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(t,e={}){let{pullRequest:r,label:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...q(this.config,e)}})}async setPullRequestLabels(t,e={}){let{pullRequest:r,labels:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=r.labels;if(!o)throw new Error('Azure DevOps requires "labels" for this function.');for(let i of n)o.find(a=>a.id===i.id)||await this.addPullRequestLabel({pullRequest:r,label:i},e);for(let i of o)n.find(a=>i.id===a.id)||await this.removePullRequestLabel({pullRequest:r,label:i},e)}async setPullRequestAsDraft(t,e={}){let{pullRequest:r,isDraft:n}=t,o={isDraft:n};if(!(await this.updatePullRequest(r,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n,isRequired:o}=t,i={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(i),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n}=t;await this.config.request({method:"DELETE",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,headers:{...q(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;for(let o of n)r.assignees.find(i=>i.id===o.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:o,isRequired:!0},e);for(let o of r.assignees)n.find(i=>o.id===i.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:o},e)}async getIssuesForAzureProject(t,e={}){let{page:r,assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,statusByWorkItemIdByStatusId:u}=t||{},l=r||1,p=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&d.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),n&&n[0]&&d.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),i&&d.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(f=>d.push(`[System.Tags] Contains '${f}'`));let c=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...q(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(f=>f.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let I=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...q(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:I.body.value.map(f=>ts(t.namespace,t.project,f,u||{}))}}async getPermissionsForRepos(t,e={}){let{namespace:r,repos:n}=t,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},i=p=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${p.projectId}/${p.id}`;return Object.keys(o).map(g=>({securityNamespaceId:d,token:c,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(i)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,e)}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,I=o[d.permissions];for(let f of I)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][f]=!1);return p},{})}}async decorateReposWithPermissions(t,e={}){let{namespace:r,repos:n}=t,o=await this.getPermissionsForRepos({namespace:r,repos:n},e);return{data:n.map(i=>({...i,permissions:o.data[`${i.projectId}/${i.id}`]}))}}async updateIssue(t,e,r={}){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${encodeURIComponent(t.project.namespace)}/${encodeURIComponent(t.project.name)}/_apis/wit/workitems/${t.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...q(this.config,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(t,e={}){var a;let{issue:r,status:n}=t,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!((a=(await this.updateIssue(r,o,e)).body.fields)!=null&&a["System.State"]))throw new Error("Could not set issue status")}async setIssueAssignee(t,e={}){var a;let{issue:r,assignee:n}=t,o=[{op:"add",path:"/fields/System.AssignedTo",value:(n==null?void 0:n.name)??""}];if(!((a=(await this.updateIssue(r,o,e)).body.fields)!=null&&a["System.State"]))throw new Error("Could not set issue assignee")}async setIssueLabels(t,e={}){var u;let{issue:r,labels:n}=t,i=[{op:"replace",path:"/fields/System.Tags",value:n.map(l=>l.name).join(";")}];if(!((u=(await this.updateIssue(r,i,e)).body.fields)!=null&&u["System.Tags"]))throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...q(this.config,e)}})).body.value}}async getLabelsForProject(t,e={}){let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...q(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}};var L=(s,t={})=>y(t.token||s.token,t.isPAT||s.isPAT);var $="https://api.bitbucket.org/2.0",rs={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},we=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),pr=s=>{let t=s.links.clone,e=t==null?void 0:t.find(n=>n.name==="ssh"),r=t==null?void 0:t.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},dr=s=>{var t,e;return{id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:((t=s.links.clone.find(r=>r.name==="https"))==null?void 0:t.href)??null,sshUrl:((e=s.links.clone.find(r=>r.name==="ssh"))==null?void 0:e.href)??null,defaultBranch:{name:s.mainbranch.name},permissions:null}},ht=s=>{var r;let t=s.id,e=((r=s.participants)==null?void 0:r.map(n=>{let o="REVIEW_REQUESTED";return n.approved?o="APPROVED":n.state==="changes_requested"?o="CHANGES_REQUESTED":n.participated_on!==null&&(o="COMMENTED"),{reviewer:we(n.user),state:o}}))??[];return{id:t.toString(),title:s.title,number:t,state:rs[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:we(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo:pr(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:F(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:pr(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},ss=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},ne=class extends W{async refreshToken(t){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${$}/user`,headers:L(this.config,e)});return{data:we(r.body)}}async getUserForCommit(t,e={}){var i;let n=(await this.config.request({url:`${$}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:L(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:((i=n.user)==null?void 0:i.links.avatar.href)||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${$}/repositories/${t.namespace}/${t.name}`,headers:L(this.config,e)});return{data:dr(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=new URL(`${$}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",U.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(dr)}}async getBranches(t,e={}){var i;let r=new URL(`${$}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen",U.toString());let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getTags(t,e={}){let r=new URL(`${$}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",U.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForUser(t,e={}){var i;let r=new URL(`${$}/user/permissions/workspaces`);r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>({id:a.workspace.uuid,slug:a.workspace.slug,name:a.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){var i;let r=new URL(`${$}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);if(r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen","50"),t.repos&&t.repos.length>0){let a=`state = "open" AND (${t.repos.map(u=>`source.repository.full_name = "${u.namespace}/${u.name}"`).join(" OR ")})`;r.searchParams.set("q",a)}let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(ht)}}async getPullRequestsForRepoBase(t,e={}){var i;let r=new URL(`${$}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests?state=OPEN`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen","50"),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:L(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{r.push(ht(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{r.push(ht(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){var i;let r=new URL(`${$}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>we(a.user))}}async getReposPermissionsForCurrentUser(t,e={}){var i;let r=new URL(`${$}/user/permissions/repositories`);r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((a,u)=>({...a,[u.repository.uuid]:ss(u.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${$}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:L(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${$}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${$}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var ft=s=>({name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??null,id:s.id.toString(),username:s.name,url:s.links.self[0].href}),he=s=>{var u,l,p,d,c,g;let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(m=>({reviewer:ft(m.user),state:e[m.status]})),n=((u=s.toRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:u.href)??null,o=((l=s.toRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:l.href)??null;o||(o=((p=s.toRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:p.href)??null);let i=((d=s.fromRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:d.href)??null,a=((c=s.fromRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:c.href)??null;return a||(a=((g=s.fromRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:g.href)??null),{id:s.id.toString(),number:s.id,title:s.title,url:s.links.self[0].href,state:t[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:ft(s.author.user),assignees:null,reviews:r,reviewDecision:F(r),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},cr=s=>{var t,e,r;return{id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:((t=s.links.self[0])==null?void 0:t.href)??null,httpsUrl:((e=s.links.clone.find(n=>n.name==="https"||n.name==="http"))==null?void 0:e.href)??null,sshUrl:((r=s.links.clone.find(n=>n.name==="ssh"))==null?void 0:r.href)??null,defaultBranch:null,permissions:null}},oe=class extends x{getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return y(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>i?i===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:ft(l)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data:cr(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=t.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(cr)}}async getPullRequestsForRepoBase(t,e={}){var n;let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests?state=OPEN`);return r.searchParams.set("start",((n=t.page)==null?void 0:n.toString())||"0"),r.searchParams.set("limit","50"),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(he(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(he(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getPullRequestsForCurrentUser(t,e={}){var i;let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state","OPEN"),r.searchParams.set("start",((i=t.page)==null?void 0:i.toString())||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(he)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var yr=require("js-base64");var ve=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ve||{});var b=class extends Error{constructor(e,r){let n=r==null?void 0:r.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var ns={AS_CODE_OWNER:[3,0,0],CHECK_RUN:[3,0,0],LATEST_REVIEWS:[3,0,0],VIEWER_CAN_MERGE_AS_ADMIN:[3,5,0],ISSUE_FULL_DATABASE_ID:[3,12,0],PR_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_COMMENT_FULL_DATABASE_ID:[3,13,0]},gr=15,mr=100,G=s=>!!s,H=(s,t)=>{let e=ns[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},qe="https://api.github.com",os=`${qe}/graphql`,Se=`
1
+ "use strict";var Fr=Object.create;var Ie=Object.defineProperty;var Mr=Object.getOwnPropertyDescriptor;var zr=Object.getOwnPropertyNames;var Wr=Object.getPrototypeOf,Hr=Object.prototype.hasOwnProperty;var Q=(s,t)=>{for(var e in t)Ie(s,e,{get:t[e],enumerable:!0})},rr=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of zr(t))!Hr.call(s,n)&&n!==e&&Ie(s,n,{get:()=>t[n],enumerable:!(r=Mr(t,n))||r.enumerable});return s};var Jr=(s,t,e)=>(e=s!=null?Fr(Wr(s)):{},rr(t||!s||!s.__esModule?Ie(e,"default",{value:s,enumerable:!0}):e,s)),Vr=s=>rr(Ie({},"__esModule",{value:!0}),s);var An={};Q(An,{AzureDevOps:()=>se,AzureDevopsUtils:()=>ze,Bitbucket:()=>ne,BitbucketServer:()=>oe,BitbucketServerUtils:()=>ve,BitbucketUtils:()=>We,EntityIdentifierProviderType:()=>T,EntityIdentifierUtils:()=>nt,EntityType:()=>k,EntityVersion:()=>O,GitBuildStatusStage:()=>sr,GitBuildStatusState:()=>me,GitDiffLineType:()=>pt,GitHub:()=>ae,GitHubIssueCloseReason:()=>jr,GitHubUtils:()=>it,GitIssueState:()=>Ee,GitLab:()=>le,GitLabUtils:()=>at,GitMergeStrategy:()=>re,GitProviderUtils:()=>ot,GitPullRequestMergeableState:()=>z,GitPullRequestReviewState:()=>j,GitPullRequestState:()=>ee,GraphQLErrors:()=>b,Jira:()=>pe,JiraServer:()=>de,JiraUtils:()=>ut,PullRequestAsyncStatus:()=>Qr,Trello:()=>ce,TrelloUtils:()=>lt,Utils:()=>Dn,default:()=>Cn,isFetch:()=>ye});module.exports=Vr(An);var sr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(sr||{}),me=(p=>(p.ActionRequired="ACTION_REQUIRED",p.Cancelled="CANCELLED",p.Error="ERROR",p.Failed="FAILED",p.Pending="PENDING",p.Running="RUNNING",p.Skipped="SKIPPED",p.Success="SUCCESS",p.Warning="WARNING",p.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",p))(me||{}),re=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(re||{}),ee=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(ee||{}),j=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(j||{}),z=(u=>(u.Behind="BEHIND",u.Blocked="BLOCKED",u.Conflicts="CONFLICTS",u.FailingChecks="FAILING_CHECKS",u.Mergeable="MERGEABLE",u.Unknown="UNKNOWN",u.UnknownAndBlocked="UNKNOWN_AND_BLOCKED",u.Unstable="UNSTABLE",u))(z||{}),pt=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(pt||{});var nr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},F=s=>!s||s.length===0?null:s.reduce((t,e)=>nr[e.state]>nr[t]?e.state:t,"APPROVED"),Re=(s,t)=>s.name||s.username||s.email||t,te=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var U=100;var or=Jr(require("node-fetch")),ir=globalThis.fetch||or.default;var Kr=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let n=await s.text();e=n.trim().length>0?JSON.parse(n):null}else if(t.startsWith("text/")||t==="")e=await s.text();else if(t.startsWith("application/vnd.github.raw+json"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${t}`);let r={body:e,headers:Object.fromEntries(s.headers.entries()),status:s.status,statusText:s.statusText};if(!s.ok){let n=new Error(s.statusText);throw Object.assign(n,{response:r}),n}return r},dt=s=>async({url:t,...e})=>{let r=await s(t,e);return Kr(r)};var ye=(s,t=!1)=>s.name==="fetch"||t;var W=class{constructor(t){let e=(t==null?void 0:t.request)||ir;this.config={...t,request:ye(e,t==null?void 0:t.forceIsFetch)?dt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&ye(t.request,(t==null?void 0:t.forceIsFetch)??this.config.forceIsFetch)?dt(t.request):this.config.request}}},x=class extends W{};var y=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},ar=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,X=(s,t,e)=>!s||t.some(r=>s[r])?e:"",ur=async s=>{var n,o,i;let t=[],e=!0,r;for(;e;){let a=await s(r);t=t.concat(a.data),e=!!((n=a==null?void 0:a.pageInfo)!=null&&n.hasNextPage),r=((o=a==null?void 0:a.pageInfo)==null?void 0:o.endCursor)||((i=a==null?void 0:a.pageInfo)==null?void 0:i.nextPage)}return t};var Xr="https://app.vssps.visualstudio.com/_apis",Yr="https://vssps.dev.azure.com/",Zr="https://dev.azure.com",q=(s,t={})=>y(t.token||s.token,t.isPAT||s.isPAT),lr=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),ct=(s,t)=>{let e=t.baseUrl||s.baseUrl||Xr;return e=e.replace(/\/$/,""),e},C=(s,t)=>{let e=t.baseUrl||s.baseUrl||Zr;return e=e.replace(/\/$/,""),e},gt=(s,t)=>{let e=t.baseUrl||s.baseUrl||Yr;return e=e.replace(/\/$/,""),e};var es={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},ts={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},mt=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Pe=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,rs=s=>{switch(s){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},be=(s,t)=>{var n;let e=[],r=[];return t.reviewers.forEach(o=>{let i={reviewer:mt(o),state:ts[o.vote??0]||"REVIEW_REQUESTED"};o.isRequired&&e.push(i),r.push(i)}),{id:t.pullRequestId.toString(),title:t.title,number:t.codeReviewId,state:es[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:mt(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Pe(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Pe(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:lr(t),assignees:t.reviewers.map(mt),reviews:r,reviewDecision:F(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:null}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:rs(t.mergeStatus),labels:((n=t.labels)==null?void 0:n.map(o=>({color:null,description:null,id:o.id,name:o.name})))??[],permissions:null}},pr=(s,t)=>({id:t.id,name:t.name,namespace:s,project:t.project.name,projectId:t.project.id,webUrl:t.webUrl,httpsUrl:t.remoteUrl,sshUrl:t.sshUrl,defaultBranch:t.defaultBranch?{name:Pe(t.defaultBranch)}:null,permissions:null}),ss=(s,t,e,r)=>{var l,p,d,c,g,m;let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=(l=r[a])==null?void 0:l[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:((d=(p=n["System.CreatedBy"]._links)==null?void 0:p.avatar)==null?void 0:d.href)??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:((g=(c=o._links)==null?void 0:c.avatar)==null?void 0:g.href)??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:(u==null?void 0:u.title)||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,resourceId:null,key:null,id:null},upvoteCount:0,labels:((m=e.fields["System.Tags"])==null?void 0:m.split(";").map(I=>({color:null,description:null,id:null,name:I.trim()})))??[]}},se=class extends x{async getCurrentUser(t={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${ct(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:r,headers:q(this.config,e)});return{data:{id:n.body.id,name:n.body.displayName,username:n.body.displayName,email:n.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(t,e={}){let n=(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/ConnectionData`,headers:q(this.config,e)})).body.authorizedUser;if(n.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:n.id,name:n.providerDisplayName,username:n.providerDisplayName,email:n.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/commits/${t.oid}`,headers:q(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(t,e={}){let r=`${ct(this.config,e)}/accounts?memberId=${t.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:q(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(t,e={}){let r=`${C(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:q(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(t,e={}){let r=new URL(`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/projects`);r.searchParams.set("$top",U.toString()),t.cursor&&r.searchParams.set("$skip",t.cursor);let n=await this.config.request({url:r.toString(),headers:q(this.config,e)}),o=n.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:n.body.value.map(i=>({id:i.id,name:i.name,namespace:t.namespace}))}}async getAzureProjectScopeDescriptor(t,e={}){let{namespace:r,projectId:n}=t;return{data:{scope:(await this.config.request({url:`${gt(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:q(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(t,e={}){let{namespace:r,projectScopeDescriptor:n,cursor:o}=t,i=new URL(`${gt(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/users`);n&&i.searchParams.set("scopeDescriptor",n),o&&i.searchParams.set("continuationToken",o);let a=await this.config.request({url:i.toString(),headers:q(this.config,e)}),u=a.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:a.body.value.map(l=>{var p,d,c,g;return{avatarUrl:((d=(p=l._links)==null?void 0:p.avatar)==null?void 0:d.href)??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:((g=(c=l._links)==null?void 0:c.storageKey)==null?void 0:g.href)??null,username:l.displayName??null}})}}async getAccountFromAzureGraphAccount(t,e={}){let{azureGraphAccount:r}=t;if(!r.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let n=await this.config.request({url:r.storageKeyURL,headers:q(this.config,e)});return{data:{avatarUrl:r.avatarUrl,email:r.email,id:n.body.value,name:r.name,username:r.username,url:null}}}async getAccountsFromAzureGraphAccounts(t,e={}){let r=[];for(let n of t.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:n},e);r.push(o.data)}return{data:r}}async getRepo(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`,headers:q(this.config,e)});return{data:pr(t.namespace,r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories`,headers:q(this.config,e)})).body.value.map(n=>pr(t.namespace,n))}}async getRefs(t,e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=new URL(`${C(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",t),n.searchParams.set("$top",U.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:q(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:Pe(a.name),commit:{oid:a.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(t,e={}){return this.getRefs("heads",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getPullRequestsForRepoBase(t,e={},r=100){let{page:n,repo:o,assigneeLogins:i,authorLogin:a}=t||{},u=n||1;if(!o.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return i&&i.length&&(l+=`&searchCriteria.reviewerId=${i[0]}`),a&&(l+=`&searchCriteria.creatorId=${a}`),await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${r}&%24skip=${(u-1)*r}`,headers:q(this.config,e)})}async getPullRequestsForRepo(t,e={}){let n=t.page||1,o=await this.getPullRequestsForRepoBase(t,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:n+1},data:o.body.value.map(i=>be(t.repo.namespace,i))}}async getPullRequestsForRepos(t,e={}){if(!t.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...t},e)).body.value.forEach(a=>{n.push(be(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(t,e={},r=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=t;if(l!=null&&l.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let p=i||1,d=new URL(`${C(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",r.toString()),d.searchParams.set("$skip",((p-1)*r).toString()),l!=null&&l.id&&(l==null?void 0:l.project)===o&&d.searchParams.set("searchCriteria.repositoryId",l.id),a&&a.length&&d.searchParams.set("searchCriteria.reviewerId",a[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers:q(this.config,e)})}async getPullRequestsForProject(t,e={}){let n=t.page||1,o=await this.getPullRequestsForProjectBase(t,e,100);return{pageInfo:{hasNextPage:(o==null?void 0:o.body.value.length)===100,nextPage:n+1},data:(o==null?void 0:o.body.value.map(i=>be(t.namespace,i)))||[]}}async getPullRequestsForProjects(t,e={}){let{projects:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{if(!t.repo||t.repo.project&&t.repo.project===o.project){let i=await this.getPullRequestsForProjectBase({...o,...t},e);i==null||i.body.value.forEach(a=>{n.push(be(o.namespace,a))})}}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getAzurePullRequestLastMergeStatus(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:r,project:n,name:o},pullRequestId:i}=t,a=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...q(this.config,e)}});if(!a.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:a.body.mergeStatus}}async updatePullRequest(t,e,r){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}?api-version=6.0`,body:e,headers:{...q(this.config,r),"Content-Type":"application/json"}})}async closePullRequest(t,e={}){let{pullRequest:r}=t,n={status:"abandoned"};if(!(await this.updatePullRequest(r,JSON.stringify(n),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){var u;let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="noFastForward";break}case"REBASE":{o="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{o="rebaseMerge";break}case"SQUASH":{o="squash";break}}let i={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:(u=r.headRef)==null?void 0:u.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(i),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(t,e={}){let{pullRequest:r,label:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o={name:n.name};if(!(await this.config.request({method:"POST",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels?api-version=6.0`,body:JSON.stringify(o),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(t,e={}){let{pullRequest:r,label:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...q(this.config,e)}})}async setPullRequestLabels(t,e={}){let{pullRequest:r,labels:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=r.labels;if(!o)throw new Error('Azure DevOps requires "labels" for this function.');for(let i of n)o.find(a=>a.id===i.id)||await this.addPullRequestLabel({pullRequest:r,label:i},e);for(let i of o)n.find(a=>i.id===a.id)||await this.removePullRequestLabel({pullRequest:r,label:i},e)}async setPullRequestAsDraft(t,e={}){let{pullRequest:r,isDraft:n}=t,o={isDraft:n};if(!(await this.updatePullRequest(r,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n,isRequired:o}=t,i={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(i),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n}=t;await this.config.request({method:"DELETE",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,headers:{...q(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;for(let o of n)r.assignees.find(i=>i.id===o.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:o,isRequired:!0},e);for(let o of r.assignees)n.find(i=>o.id===i.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:o},e)}async getIssuesForAzureProject(t,e={}){let{page:r,assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,statusByWorkItemIdByStatusId:u}=t||{},l=r||1,p=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&d.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),n&&n[0]&&d.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),i&&d.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(f=>d.push(`[System.Tags] Contains '${f}'`));let c=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...q(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(f=>f.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let I=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...q(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:I.body.value.map(f=>ss(t.namespace,t.project,f,u||{}))}}async getPermissionsForRepos(t,e={}){let{namespace:r,repos:n}=t,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},i=p=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${p.projectId}/${p.id}`;return Object.keys(o).map(g=>({securityNamespaceId:d,token:c,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(i)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,e)}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,I=o[d.permissions];for(let f of I)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][f]=!1);return p},{})}}async decorateReposWithPermissions(t,e={}){let{namespace:r,repos:n}=t,o=await this.getPermissionsForRepos({namespace:r,repos:n},e);return{data:n.map(i=>({...i,permissions:o.data[`${i.projectId}/${i.id}`]}))}}async updateIssue(t,e,r={}){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${encodeURIComponent(t.project.namespace)}/${encodeURIComponent(t.project.name)}/_apis/wit/workitems/${t.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...q(this.config,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(t,e={}){var a;let{issue:r,status:n}=t,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!((a=(await this.updateIssue(r,o,e)).body.fields)!=null&&a["System.State"]))throw new Error("Could not set issue status")}async setIssueAssignee(t,e={}){var a;let{issue:r,assignee:n}=t,o=[{op:"add",path:"/fields/System.AssignedTo",value:(n==null?void 0:n.name)??""}];if(!((a=(await this.updateIssue(r,o,e)).body.fields)!=null&&a["System.State"]))throw new Error("Could not set issue assignee")}async setIssueLabels(t,e={}){var u;let{issue:r,labels:n}=t,i=[{op:"replace",path:"/fields/System.Tags",value:n.map(l=>l.name).join(";")}];if(!((u=(await this.updateIssue(r,i,e)).body.fields)!=null&&u["System.Tags"]))throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...q(this.config,e)}})).body.value}}async getLabelsForProject(t,e={}){let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...q(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}};var L=(s,t={})=>y(t.token||s.token,t.isPAT||s.isPAT);var $="https://api.bitbucket.org/2.0",ns={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},we=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),dr=s=>{let t=s.links.clone,e=t==null?void 0:t.find(n=>n.name==="ssh"),r=t==null?void 0:t.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},cr=s=>{var t,e;return{id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:((t=s.links.clone.find(r=>r.name==="https"))==null?void 0:t.href)??null,sshUrl:((e=s.links.clone.find(r=>r.name==="ssh"))==null?void 0:e.href)??null,defaultBranch:{name:s.mainbranch.name},permissions:null}},ht=s=>{var r;let t=s.id,e=((r=s.participants)==null?void 0:r.map(n=>{let o="REVIEW_REQUESTED";return n.approved?o="APPROVED":n.state==="changes_requested"?o="CHANGES_REQUESTED":n.participated_on!==null&&(o="COMMENTED"),{reviewer:we(n.user),state:o}}))??[];return{id:t.toString(),title:s.title,number:t,state:ns[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:we(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo:dr(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:F(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:dr(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},os=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},ne=class extends W{async refreshToken(t){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${$}/user`,headers:L(this.config,e)});return{data:we(r.body)}}async getUserForCommit(t,e={}){var i;let n=(await this.config.request({url:`${$}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:L(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:((i=n.user)==null?void 0:i.links.avatar.href)||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${$}/repositories/${t.namespace}/${t.name}`,headers:L(this.config,e)});return{data:cr(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=new URL(`${$}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",U.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(cr)}}async getBranches(t,e={}){var i;let r=new URL(`${$}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen",U.toString());let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getTags(t,e={}){let r=new URL(`${$}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",U.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForUser(t,e={}){var i;let r=new URL(`${$}/user/permissions/workspaces`);r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>({id:a.workspace.uuid,slug:a.workspace.slug,name:a.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){var i;let r=new URL(`${$}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);if(r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen","50"),t.repos&&t.repos.length>0){let a=`state = "open" AND (${t.repos.map(u=>`source.repository.full_name = "${u.namespace}/${u.name}"`).join(" OR ")})`;r.searchParams.set("q",a)}let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(ht)}}async getPullRequestsForRepoBase(t,e={}){var i;let r=new URL(`${$}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests?state=OPEN`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen","50"),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:L(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{r.push(ht(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{r.push(ht(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){var i;let r=new URL(`${$}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>we(a.user))}}async getReposPermissionsForCurrentUser(t,e={}){var i;let r=new URL(`${$}/user/permissions/repositories`);r.searchParams.set("page",((i=t.page)==null?void 0:i.toString())||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:L(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((a,u)=>({...a,[u.repository.uuid]:os(u.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${$}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:L(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${$}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${$}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var ve={};Q(ve,{normalizePermissions:()=>ft,restApiPullRequestToCommonPullRequest:()=>is});var is=s=>he(s),ft=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var It=s=>({name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??null,id:s.id.toString(),username:s.name,url:s.links.self[0].href}),he=s=>{var u,l,p,d,c,g;let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(m=>({reviewer:It(m.user),state:e[m.status]})),n=((u=s.toRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:u.href)??null,o=((l=s.toRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:l.href)??null;o||(o=((p=s.toRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:p.href)??null);let i=((d=s.fromRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:d.href)??null,a=((c=s.fromRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:c.href)??null;return a||(a=((g=s.fromRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:g.href)??null),{id:s.id.toString(),number:s.id,title:s.title,url:s.links.self[0].href,state:t[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:It(s.author.user),assignees:null,reviews:r,reviewDecision:F(r),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},gr=s=>{var t,e,r;return{id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:((t=s.links.self[0])==null?void 0:t.href)??null,httpsUrl:((e=s.links.clone.find(n=>n.name==="https"||n.name==="http"))==null?void 0:e.href)??null,sshUrl:((r=s.links.clone.find(n=>n.name==="ssh"))==null?void 0:r.href)??null,defaultBranch:null,permissions:null}},oe=class extends x{getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return y(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>i?i===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:It(l)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data:gr(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=t.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(gr)}}async getRepoPermissionsForUsername(t,e={}){var n;let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let o=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:ft(o.body.values)}}catch(o){if(((n=o.response)==null?void 0:n.status)===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw o}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){var n;let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests?state=OPEN`);return r.searchParams.set("start",((n=t.page)==null?void 0:n.toString())||"0"),r.searchParams.set("limit","50"),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(he(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(he(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getPullRequestsForCurrentUser(t,e={}){var i;let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state","OPEN"),r.searchParams.set("start",((i=t.page)==null?void 0:i.toString())||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(he)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var br=require("js-base64");var Ee=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Ee||{});var b=class extends Error{constructor(e,r){let n=r==null?void 0:r.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var as={AS_CODE_OWNER:[3,0,0],CHECK_RUN:[3,0,0],LATEST_REVIEWS:[3,0,0],VIEWER_CAN_MERGE_AS_ADMIN:[3,5,0],ISSUE_FULL_DATABASE_ID:[3,12,0],PR_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_COMMENT_FULL_DATABASE_ID:[3,13,0]},mr=15,hr=100,G=s=>!!s,H=(s,t)=>{let e=as[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Se="https://api.github.com",us=`${Se}/graphql`,Ce=`
2
2
  description
3
3
  dueOn
4
4
  id
@@ -6,7 +6,7 @@ number
6
6
  state
7
7
  title
8
8
  url
9
- `,is=`
9
+ `,ls=`
10
10
  ... on CheckRun {
11
11
  completedAt
12
12
  conclusion
@@ -15,12 +15,12 @@ url
15
15
  permalink
16
16
  startedAt
17
17
  }
18
- `,Ee=/\/api\/v\d+$/,Ce=`
18
+ `,qe=/\/api\/v\d+$/,De=`
19
19
  color
20
20
  description
21
21
  id
22
22
  name
23
- `,hr=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},as=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),hr(e),Ee.test(e)&&(e=e.replace(Ee,"")),`${e}/api/graphql`):os},ie=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),hr(e),Ee.test(e)&&(e=e.replace(Ee,"")),`${e}/api/v3`):qe},P=(s,t,e)=>{let r=y(e.token||s.token);return r["X-Github-Next-Global-ID"]="1",r["Content-Type"]="application/json",r.Accept="application/vnd.github.merge-info-preview+json",s.request({url:as(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},us={user:!0,"user:email":!0,"read:user":!0},J=s=>s.some(t=>us[t]),N=(s=!1,t=!1,e)=>`
23
+ `,fr=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},ps=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),fr(e),qe.test(e)&&(e=e.replace(qe,"")),`${e}/api/graphql`):us},ie=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),fr(e),qe.test(e)&&(e=e.replace(qe,"")),`${e}/api/v3`):Se},P=(s,t,e)=>{let r=y(e.token||s.token);return r["X-Github-Next-Global-ID"]="1",r["Content-Type"]="application/json",r.Accept="application/vnd.github.merge-info-preview+json",s.request({url:ps(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},ds={user:!0,"user:email":!0,"read:user":!0},J=s=>s.some(t=>ds[t]),N=(s=!1,t=!1,e)=>`
24
24
  __typename
25
25
  ${X(e,["graphQLId"],"id")}
26
26
  ${X(e,["id"],"databaseId")}
@@ -29,7 +29,7 @@ ${X(e,["name","username"],"login")}
29
29
  ${t?X(e,["email"],"email"):""}
30
30
  ${X(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
31
31
  ${X(e,["url"],"url")}
32
- `,ls=(s=!1)=>`
32
+ `,cs=(s=!1)=>`
33
33
  latestReviews(first: 100) {
34
34
  nodes {
35
35
  author {
@@ -37,26 +37,26 @@ latestReviews(first: 100) {
37
37
  ${N(!1,s)}
38
38
  }
39
39
  ... on EnterpriseUserAccount {
40
- ${It(!1)}
40
+ ${Rt(!1)}
41
41
  }
42
42
  }
43
43
  state
44
44
  }
45
45
  }
46
- `,fr=(s=!1)=>`
46
+ `,Ir=(s=!1)=>`
47
47
  __typename
48
48
  id
49
49
  databaseId
50
50
  login
51
51
  avatarUrl${s?"(size: $avatarSize)":""}
52
52
  url
53
- `,It=(s=!1)=>`
53
+ `,Rt=(s=!1)=>`
54
54
  __typename
55
55
  id
56
56
  login
57
57
  avatarUrl${s?"(size: $avatarSize)":""}
58
58
  url
59
- `,De=(s,t=!1,e)=>`
59
+ `,Ae=(s,t=!1,e)=>`
60
60
  id
61
61
  ${!e||H(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
62
62
  number
@@ -67,10 +67,10 @@ author {
67
67
  ${N(!1,t)}
68
68
  }
69
69
  ... on Bot {
70
- ${fr(!1)}
70
+ ${Ir(!1)}
71
71
  }
72
72
  ... on EnterpriseUserAccount {
73
- ${It(!1)}
73
+ ${Rt(!1)}
74
74
  }
75
75
  }
76
76
  commits(last: 1) {
@@ -83,7 +83,7 @@ commits(last: 1) {
83
83
  contexts(first: 100) {
84
84
  totalCount
85
85
  nodes {
86
- ${!e||H(e,"CHECK_RUN")?is:""}
86
+ ${!e||H(e,"CHECK_RUN")?ls:""}
87
87
  ... on StatusContext {
88
88
  context
89
89
  createdAt
@@ -158,22 +158,22 @@ reviewRequests(first: 100) {
158
158
  }
159
159
  }
160
160
  }
161
- ${!e||H(e,"LATEST_REVIEWS")?ls(t):""}
161
+ ${!e||H(e,"LATEST_REVIEWS")?cs(t):""}
162
162
  additions
163
163
  deletions
164
164
  changedFiles
165
165
  mergeable
166
166
  mergeStateStatus
167
167
  milestone {
168
- ${Se}
168
+ ${Ce}
169
169
  }
170
170
  labels(first: 100) {
171
171
  nodes {
172
- ${Ce}
172
+ ${De}
173
173
  }
174
174
  }
175
175
  ${!e||H(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
176
- `,ps=(s=!1,t)=>`
176
+ `,gs=(s=!1,t)=>`
177
177
  id
178
178
  ${!t||H(t,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
179
179
  title
@@ -182,10 +182,10 @@ author {
182
182
  ${N(!1,s)}
183
183
  }
184
184
  ... on Bot {
185
- ${fr(!1)}
185
+ ${Ir(!1)}
186
186
  }
187
187
  ... on EnterpriseUserAccount {
188
- ${It(!1)}
188
+ ${Rt(!1)}
189
189
  }
190
190
  }
191
191
  closedAt
@@ -214,14 +214,14 @@ assignees(first: 100) {
214
214
  }
215
215
  state
216
216
  milestone {
217
- ${Se}
217
+ ${Ce}
218
218
  }
219
219
  labels(first: 100) {
220
220
  nodes {
221
- ${Ce}
221
+ ${De}
222
222
  }
223
223
  }
224
- `,ds={"-linked":"-linked",archived:"archived",assignee:"assignee",author:"author",base:"base",closed:"closed",commenter:"commenter",comments:"comments",created:"created",draft:"draft",head:"head",label:"label",language:"language",linked:"linked",in:"in",interactions:"interactions",involves:"involves",is:"is",mentions:"mentions",merged:"merged",milestone:"milestone",no:"no",org:"org",project:"project",reactions:"reactions",repo:"repo",review:"review","reviewed-by":"reviewed-by","review-requested":"review-requested",state:"state",status:"status",team:"team","team-review-requested":"team-review-requested",type:"type",updated:"updated",user:"user","user-review-requested":"user-review-requested"},cs=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Rt=s=>{let t=[];return(s.match(cs)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];ds[n]&&t.push(r)}}),t},yt=(s,t,e,r)=>{let n=s==="issue";return{query:`
224
+ `,ms={"-linked":"-linked",archived:"archived",assignee:"assignee",author:"author",base:"base",closed:"closed",commenter:"commenter",comments:"comments",created:"created",draft:"draft",head:"head",label:"label",language:"language",linked:"linked",in:"in",interactions:"interactions",involves:"involves",is:"is",mentions:"mentions",merged:"merged",milestone:"milestone",no:"no",org:"org",project:"project",reactions:"reactions",repo:"repo",review:"review","reviewed-by":"reviewed-by","review-requested":"review-requested",state:"state",status:"status",team:"team","team-review-requested":"team-review-requested",type:"type",updated:"updated",user:"user","user-review-requested":"user-review-requested"},hs=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),yt=s=>{let t=[];return(s.match(hs)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];ms[n]&&t.push(r)}}),t},bt=(s,t,e,r)=>{let n=s==="issue";return{query:`
225
225
  query SearchIssuesOrPullRequests($query: String! $after: String) {
226
226
  search(type:ISSUE query:$query first: ${r.maxPageSize} after:$after) {
227
227
  pageInfo {
@@ -230,18 +230,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
230
230
  }
231
231
  nodes {
232
232
  ... on ${n?"Issue":"PullRequest"} {
233
- ${n?ps(r.supportsEmail,r.enterpriseVersion??null):De(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
233
+ ${n?gs(r.supportsEmail,r.enterpriseVersion??null):Ae(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
234
234
  }
235
235
  }
236
236
  }
237
- }`,variables:{query:`is:${s} is:open ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},gs="Field 'isDraft' doesn't exist on type 'PullRequest'",Ae=(s=[])=>s.some(t=>(t==null?void 0:t.message)===gs),ms=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,hs=`
237
+ }`,variables:{query:`is:${s} is:open ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},fs="Field 'isDraft' doesn't exist on type 'PullRequest'",Ue=(s=[])=>s.some(t=>(t==null?void 0:t.message)===fs),Is=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Rs=`
238
238
  \
239
- +`,Ir=(s,t,e,r)=>{let n=ms.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(hs,`
239
+ +`,Rr=(s,t,e,r)=>{let n=Is.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(Rs,`
240
240
  +`).split(`
241
241
  `).slice(1),u=o-1,l=i-1,p=a.map(g=>{let m,I;switch(g[0]){case"-":{m="DELETED",u+=1,I=`${g.slice(1)}
242
242
  `;break}case"+":{m="ADDED",l+=1,I=`${g.slice(1)}
243
243
  `;break}default:m="UNMODIFIED",l+=1,u+=1,I=`${g}
244
- `}return{line:I,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=t;if(d!==null&&c!==null&&r!==null&&d<c){let g=0,m=p.length,I=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let f=0;f<p.length;f++){let h=p[f][I];h===d?g=f:h===c&&(m=f)}p=p.slice(g,m+1)}return p};var bt=`
244
+ `}return{line:I,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=t;if(d!==null&&c!==null&&r!==null&&d<c){let g=0,m=p.length,I=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let f=0;f<p.length;f++){let h=p[f][I];h===d?g=f:h===c&&(m=f)}p=p.slice(g,m+1)}return p};var Pt=`
245
245
  id
246
246
  databaseId
247
247
  owner {
@@ -254,7 +254,7 @@ defaultBranchRef {
254
254
  name
255
255
  }
256
256
  viewerPermission
257
- `,vt={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},fs={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Is={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Rs={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},ys={OPEN:"OPEN",CLOSED:"CLOSED"},bs=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Et=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Ps=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Pt=s=>({id:s.databaseId.toString(),graphQLId:s.id,namespace:s.owner.login,name:s.name,webUrl:s.url,httpsUrl:s.url.endsWith(".git")?s.url:`${s.url}.git`,sshUrl:s.sshUrl,defaultBranch:s.defaultBranchRef,permissions:Ps(s.viewerPermission)}),ws=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),Rr=s=>({id:s.id.toString(),graphQLId:s.node_id,namespace:s.owner.login,name:s.name,webUrl:s.html_url,httpsUrl:s.clone_url,sshUrl:s.ssh_url,defaultBranch:{name:s.default_branch},permissions:ws(s.permissions)}),vs=s=>({path:s.path,isDirectory:s.type==="tree"}),Es={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},qs={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},B=(s,t=qs)=>{let e={};return t.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),t.graphQLId&&(e.graphQLId=s.id),t.name&&(e.name=s.name??s.login),t.username&&(e.username=s.login),t.email&&(e.email=s.email??null),t.avatarUrl&&(e.avatarUrl=s.avatarUrl),t.url&&(e.url=s.url),e},Ss=(s,t)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return s!=="COMPLETED"?e[s]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[t]},Cs=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],wt=s=>{var i,a,u,l,p,d,c,g,m,I,f,w;let t=null;s.author?t=s.author:t=vt;let e=(((i=s.reviewRequests)==null?void 0:i.nodes)||[]).filter(G).filter(h=>!h.asCodeOwner),r=(a=s.headRepository)==null?void 0:a.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=(u=s.repository)==null?void 0:u.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(h=>h.requestedReviewer&&"__typename"in h.requestedReviewer).map(h=>({reviewer:B(h.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((((l=s.latestReviews)==null?void 0:l.nodes)||[]).filter(G).map(h=>{let R=vt;return h.author&&h.author.__typename&&(R=h.author),{reviewer:B(R),state:fs[h.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,number:s.number,state:Es[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?B(t):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:s.repository.sshUrl}},headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:((g=(c=(d=(p=s.commits.nodes)==null?void 0:p.filter(G)[0])==null?void 0:d.commit.statusCheckRollup)==null?void 0:c.contexts.nodes)==null?void 0:g.filter(G).map(h=>"context"in h?{completedAt:null,description:h.description,name:h.context,state:Cs(h.state),startedAt:new Date(h.createdAt),stage:null,url:h.targetUrl}:{completedAt:h.completedAt?new Date(h.completedAt):null,description:null,name:h.name,state:Ss(h.status,h.conclusion),startedAt:h.startedAt?new Date(h.startedAt):null,stage:null,url:h.permalink}))??[]},headRef:s.headRef?{name:s.headRef.name,oid:((m=s.headRef.target)==null?void 0:m.oid)??null}:null,baseRef:s.baseRef?{name:s.baseRef.name,oid:((I=s.baseRef.target)==null?void 0:I.oid)??null}:null,url:s.url,updatedDate:new Date(s.updatedAt),closedDate:s.closedAt?new Date(s.closedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees.nodes?s.assignees.nodes.filter(G).map(h=>B(h)):null,reviews:o,reviewDecision:F(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:Rs[s.mergeStateStatus]??Is[s.mergeable],milestone:s.milestone?qt(s.milestone):null,labels:((w=(f=s.labels)==null?void 0:f.nodes)==null?void 0:w.filter(G).map(Et))??[],permissions:{canMerge:bs.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Ds=s=>{var f,w;let{comments:t,isOutdated:e,isResolved:r,originalLine:n,originalStartLine:o,startDiffSide:i}=s,a=(f=t.nodes)==null?void 0:f[0];if(!a)return null;let{author:u,body:l,databaseId:p,fullDatabaseId:d,id:c,path:g,publishedAt:m,url:I}=a;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:m?new Date(m):null,diffLines:Ir(a.diffHunk,n,o,i),id:d??p.toString(),isOutdated:e,isResolved:r,graphQLId:c,filename:g,replies:((w=t.nodes)==null?void 0:w.filter(G).slice(1).map(As))??[],url:I}},As=s=>({author:s.author?{avatarUrl:s.author.avatarUrl,email:null,name:s.author.login}:null,body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId.toString(),url:s.url}),Us=s=>{var e,r,n;let t=null;return s.author?t=s.author:t=vt,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?B(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:ys[s.state],color:null},type:null,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login}},url:s.url,updatedDate:new Date(s.updatedAt),assignees:((e=s.assignees.nodes)==null?void 0:e.filter(G).map(o=>B(o)))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?qt(s.milestone):null,labels:((n=(r=s.labels)==null?void 0:r.nodes)==null?void 0:n.filter(G).map(Et))??[]}},qt=s=>({id:s.number.toString(),graphQLId:s.id.toString(),number:s.number,title:s.title,description:s.description,isOpen:s.state=="OPEN",url:s.url,startDate:null,dueDate:s.dueOn?new Date(s.dueOn):null}),ae=class extends x{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let r=e.token||this.config.token;if(!r)return[];let n=this._scopesCache[r];if(!n){let i=(await P(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[r]=n}return n}async getEnterpriseVersion(e){let r=e.baseUrl||this.config.baseUrl;if(!r)return null;let n=this._enterpriseVersionsCache[r];if(!n){let o=await this.config.request({url:`${ie(this.config,e)}/meta`,headers:y(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[r]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,r,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(qe)?e:r?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(r)}`:""}async getCurrentUser(e={},r={}){var u;if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=ir(e.fields),o=await this.getScopes(r),i=await P(this.config,{query:`
257
+ `,Et={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},ys={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},bs={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Ps={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},ws={OPEN:"OPEN",CLOSED:"CLOSED"},vs=["ADMIN","MAINTAIN","TRIAGE","WRITE"],qt=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Es=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),wt=s=>({id:s.databaseId.toString(),graphQLId:s.id,namespace:s.owner.login,name:s.name,webUrl:s.url,httpsUrl:s.url.endsWith(".git")?s.url:`${s.url}.git`,sshUrl:s.sshUrl,defaultBranch:s.defaultBranchRef,permissions:Es(s.viewerPermission)}),qs=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),yr=s=>({id:s.id.toString(),graphQLId:s.node_id,namespace:s.owner.login,name:s.name,webUrl:s.html_url,httpsUrl:s.clone_url,sshUrl:s.ssh_url,defaultBranch:{name:s.default_branch},permissions:qs(s.permissions)}),Ss=s=>({path:s.path,isDirectory:s.type==="tree"}),Cs={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Ds={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},B=(s,t=Ds)=>{let e={};return t.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),t.graphQLId&&(e.graphQLId=s.id),t.name&&(e.name=s.name??s.login),t.username&&(e.username=s.login),t.email&&(e.email=s.email??null),t.avatarUrl&&(e.avatarUrl=s.avatarUrl),t.url&&(e.url=s.url),e},As=(s,t)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return s!=="COMPLETED"?e[s]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[t]},Us=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],vt=s=>{var i,a,u,l,p,d,c,g,m,I,f,w;let t=null;s.author?t=s.author:t=Et;let e=(((i=s.reviewRequests)==null?void 0:i.nodes)||[]).filter(G).filter(h=>!h.asCodeOwner),r=(a=s.headRepository)==null?void 0:a.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=(u=s.repository)==null?void 0:u.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(h=>h.requestedReviewer&&"__typename"in h.requestedReviewer).map(h=>({reviewer:B(h.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((((l=s.latestReviews)==null?void 0:l.nodes)||[]).filter(G).map(h=>{let R=Et;return h.author&&h.author.__typename&&(R=h.author),{reviewer:B(R),state:ys[h.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,number:s.number,state:Cs[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?B(t):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:s.repository.sshUrl}},headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:((g=(c=(d=(p=s.commits.nodes)==null?void 0:p.filter(G)[0])==null?void 0:d.commit.statusCheckRollup)==null?void 0:c.contexts.nodes)==null?void 0:g.filter(G).map(h=>"context"in h?{completedAt:null,description:h.description,name:h.context,state:Us(h.state),startedAt:new Date(h.createdAt),stage:null,url:h.targetUrl}:{completedAt:h.completedAt?new Date(h.completedAt):null,description:null,name:h.name,state:As(h.status,h.conclusion),startedAt:h.startedAt?new Date(h.startedAt):null,stage:null,url:h.permalink}))??[]},headRef:s.headRef?{name:s.headRef.name,oid:((m=s.headRef.target)==null?void 0:m.oid)??null}:null,baseRef:s.baseRef?{name:s.baseRef.name,oid:((I=s.baseRef.target)==null?void 0:I.oid)??null}:null,url:s.url,updatedDate:new Date(s.updatedAt),closedDate:s.closedAt?new Date(s.closedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees.nodes?s.assignees.nodes.filter(G).map(h=>B(h)):null,reviews:o,reviewDecision:F(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:Ps[s.mergeStateStatus]??bs[s.mergeable],milestone:s.milestone?St(s.milestone):null,labels:((w=(f=s.labels)==null?void 0:f.nodes)==null?void 0:w.filter(G).map(qt))??[],permissions:{canMerge:vs.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Ls=s=>{var f,w;let{comments:t,isOutdated:e,isResolved:r,originalLine:n,originalStartLine:o,startDiffSide:i}=s,a=(f=t.nodes)==null?void 0:f[0];if(!a)return null;let{author:u,body:l,databaseId:p,fullDatabaseId:d,id:c,path:g,publishedAt:m,url:I}=a;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:m?new Date(m):null,diffLines:Rr(a.diffHunk,n,o,i),id:d??p.toString(),isOutdated:e,isResolved:r,graphQLId:c,filename:g,replies:((w=t.nodes)==null?void 0:w.filter(G).slice(1).map($s))??[],url:I}},$s=s=>({author:s.author?{avatarUrl:s.author.avatarUrl,email:null,name:s.author.login}:null,body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId.toString(),url:s.url}),Gs=s=>{var e,r,n;let t=null;return s.author?t=s.author:t=Et,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?B(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:ws[s.state],color:null},type:null,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login}},url:s.url,updatedDate:new Date(s.updatedAt),assignees:((e=s.assignees.nodes)==null?void 0:e.filter(G).map(o=>B(o)))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?St(s.milestone):null,labels:((n=(r=s.labels)==null?void 0:r.nodes)==null?void 0:n.filter(G).map(qt))??[]}},St=s=>({id:s.number.toString(),graphQLId:s.id.toString(),number:s.number,title:s.title,description:s.description,isOpen:s.state=="OPEN",url:s.url,startDate:null,dueDate:s.dueOn?new Date(s.dueOn):null}),ae=class extends x{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let r=e.token||this.config.token;if(!r)return[];let n=this._scopesCache[r];if(!n){let i=(await P(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[r]=n}return n}async getEnterpriseVersion(e){let r=e.baseUrl||this.config.baseUrl;if(!r)return null;let n=this._enterpriseVersionsCache[r];if(!n){let o=await this.config.request({url:`${ie(this.config,e)}/meta`,headers:y(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[r]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,r,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(Se)?e:r?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(r)}`:""}async getCurrentUser(e={},r={}){var u;if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=ar(e.fields),o=await this.getScopes(r),i=await P(this.config,{query:`
258
258
  query getCurrentUser {
259
259
  viewer {
260
260
  ${N(!1,J(o),n)}
@@ -320,7 +320,7 @@ mutation createCommitOnBranch(
320
320
  }
321
321
  }
322
322
  }
323
- `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([p,d])=>({contents:yr.Base64.encode(d),path:p})),deletions:o.map(p=>({path:p}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},r);if(!l.body.data)throw new b("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,r={}){var a,u,l;let n=await this.getScopes(r),o=await P(this.config,{query:`
323
+ `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([p,d])=>({contents:br.Base64.encode(d),path:p})),deletions:o.map(p=>({path:p}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},r);if(!l.body.data)throw new b("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,r={}){var a,u,l;let n=await this.getScopes(r),o=await P(this.config,{query:`
324
324
  query getAccountForEmail($query: String! $avatarSize: Int) {
325
325
  search(query: $query, type: USER, first: 1) {
326
326
  nodes {
@@ -374,19 +374,19 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
374
374
  `,variables:{cursor:e.cursor,first:U,login:e.org}},r);if(!((a=(i=n.body.data)==null?void 0:i.viewer.organization)!=null&&a.membersWithRole)&&((u=n.body.errors)!=null&&u.length))throw new b("Could not read the members of the organization",n.body.errors);let o=((p=(l=n.body.data)==null?void 0:l.viewer.organization)==null?void 0:p.membersWithRole.nodes)||[];return{pageInfo:{hasNextPage:((c=(d=n.body.data)==null?void 0:d.viewer.organization)==null?void 0:c.membersWithRole.pageInfo.hasNextPage)??!1,endCursor:((m=(g=n.body.data)==null?void 0:g.viewer.organization)==null?void 0:m.membersWithRole.pageInfo.endCursor)??null},data:o.map(I=>B({...I,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(I.avatarUrl,I.email,r)}))}}async getRepo(e,r={}){var o;let n=await P(this.config,{query:`
375
375
  query getRepo($owner: String!, $name: String!) {
376
376
  repository(owner: $owner, name: $name) {
377
- ${bt}
377
+ ${Pt}
378
378
  }
379
379
  }
380
- `,variables:{owner:e.namespace,name:e.name}},r);if(!((o=n.body.data)!=null&&o.repository))throw new b(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:Pt(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},p)=>`
380
+ `,variables:{owner:e.namespace,name:e.name}},r);if(!((o=n.body.data)!=null&&o.repository))throw new b(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:wt(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},p)=>`
381
381
  getRepo_${p}: repository(owner: "${u}", name: "${l}") {
382
- ${bt}
382
+ ${Pt}
383
383
  }
384
384
  `).join(`
385
385
  `),o=await P(this.config,{query:`
386
386
  query batchGetRepos {
387
387
  ${n}
388
388
  }
389
- `},r);if(!o.body.data)throw new b("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(Pt(p)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,r,n,o){let i=[];for(let d=0;d<r;d++)i.push(n(e+d));let a=await Promise.all(i),u=[];for(let d of a){if(!d.body)throw new Error(d.statusText||"Unknown error");u=u.concat(d.body.map(c=>o(c)))}let l=a.every(d=>d.body.length===100),p=e+r;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?p:null}}}async getReposForCurrentUser(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${ie(this.config,r)}/user/repos?${n.toString()}&page=${i}`,headers:{...y(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,Rr)}async getReposForOrg(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${ie(this.config,r)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...y(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,n,Rr)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await P(this.config,{query:`
389
+ `},r);if(!o.body.data)throw new b("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(wt(p)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,r,n,o){let i=[];for(let d=0;d<r;d++)i.push(n(e+d));let a=await Promise.all(i),u=[];for(let d of a){if(!d.body)throw new Error(d.statusText||"Unknown error");u=u.concat(d.body.map(c=>o(c)))}let l=a.every(d=>d.body.length===100),p=e+r;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?p:null}}}async getReposForCurrentUser(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${ie(this.config,r)}/user/repos?${n.toString()}&page=${i}`,headers:{...y(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,yr)}async getReposForOrg(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${ie(this.config,r)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...y(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,n,yr)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await P(this.config,{query:`
390
390
  query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
391
391
  search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
392
392
  pageInfo {
@@ -395,12 +395,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
395
395
  }
396
396
  nodes {
397
397
  ... on Repository {
398
- ${bt}
398
+ ${Pt}
399
399
  }
400
400
  }
401
401
  }
402
402
  }
403
- `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:U}},r);if(!n.body.data)throw new b("Could not fetch repos for usernames",n.body.errors);let o=n.body.data.search.nodes||[];return{pageInfo:n.body.data.search.pageInfo,data:o.map(Pt)}}async getReposForOwners(e,r={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},r)}async getRefs(e,r,n={}){var u;let o=await P(this.config,{query:`
403
+ `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:U}},r);if(!n.body.data)throw new b("Could not fetch repos for usernames",n.body.errors);let o=n.body.data.search.nodes||[];return{pageInfo:n.body.data.search.pageInfo,data:o.map(wt)}}async getReposForOwners(e,r={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},r)}async getRefs(e,r,n={}){var u;let o=await P(this.config,{query:`
404
404
  query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
405
405
  repository(owner: $owner, name: $name) {
406
406
  refs(refPrefix: $refPrefix first: $first after: $cursor) {
@@ -460,7 +460,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
460
460
  }
461
461
  }
462
462
  }
463
- `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},r),o=(a=n.body.data)==null?void 0:a.repository;if(!o)throw new b("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new b("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new b("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(u=>{var l;return{startingLine:u.startingLine,endingLine:u.endingLine,commit:{oid:u.commit.oid,parentOids:((l=u.commit.parents.nodes)==null?void 0:l.map(p=>p.oid))||[],authoredDate:new Date(u.commit.authoredDate),author:u.commit.author?{name:u.commit.author.name,email:u.commit.author.email,avatarUrl:u.commit.author.avatarUrl}:null,committedDate:new Date(u.commit.committedDate),committer:u.commit.committer?{name:u.commit.committer.name,email:u.commit.committer.email,avatarUrl:u.commit.committer.avatarUrl}:null,message:u.commit.message,fileCount:u.commit.changedFilesIfAvailable,additions:u.commit.additions,deletions:u.commit.deletions}}})}}}async getFileContents(e,r={}){let n=await this.config.request({url:`${ie(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...y(r.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async searchPullRequests(e,r={}){var p;let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=J(o),a=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return yt("pr",c,e.cursor,{maxPageSize:e.maxPageSize??gr,supportsEmail:i,supportsDrafts:d,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await P(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await P(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new b("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:((p=l.search.nodes)==null?void 0:p.filter(G).map(wt))||[]}}async searchIssues(e,r={}){var l;let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=J(o),a=await P(this.config,yt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??mr,enterpriseVersion:n}),r),{data:u}=a.body;if(!u)throw new b("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:((l=u.search.nodes)==null?void 0:l.filter(G).map(Us))||[]}}async getPullRequestsAssociatedWithUser(e,r={}){var o;let n=[`involves:${e.username}`];return(o=e.repos)!=null&&o.length&&e.repos.forEach(i=>{n.push(`repo:${i.namespace}/${i.name}`)}),e.labelNames&&e.labelNames.forEach(i=>{n.push(`label:"${i}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async getPullRequestsForRepos(e,r={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=Rt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),p&&g.push(`mentions:${p}`),d&&d.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c},r)}async getPullRequestForRepo(e,r={}){var d;let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=J(o),a=c=>({query:`query getPullRequest(
463
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},r),o=(a=n.body.data)==null?void 0:a.repository;if(!o)throw new b("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new b("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new b("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(u=>{var l;return{startingLine:u.startingLine,endingLine:u.endingLine,commit:{oid:u.commit.oid,parentOids:((l=u.commit.parents.nodes)==null?void 0:l.map(p=>p.oid))||[],authoredDate:new Date(u.commit.authoredDate),author:u.commit.author?{name:u.commit.author.name,email:u.commit.author.email,avatarUrl:u.commit.author.avatarUrl}:null,committedDate:new Date(u.commit.committedDate),committer:u.commit.committer?{name:u.commit.committer.name,email:u.commit.committer.email,avatarUrl:u.commit.committer.avatarUrl}:null,message:u.commit.message,fileCount:u.commit.changedFilesIfAvailable,additions:u.commit.additions,deletions:u.commit.deletions}}})}}}async getFileContents(e,r={}){let n=await this.config.request({url:`${ie(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...y(r.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async searchPullRequests(e,r={}){var p;let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=J(o),a=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return bt("pr",c,e.cursor,{maxPageSize:e.maxPageSize??mr,supportsEmail:i,supportsDrafts:d,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await P(this.config,a(!0),r);u.body.errors&&Ue(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await P(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new b("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:((p=l.search.nodes)==null?void 0:p.filter(G).map(vt))||[]}}async searchIssues(e,r={}){var l;let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=J(o),a=await P(this.config,bt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??hr,enterpriseVersion:n}),r),{data:u}=a.body;if(!u)throw new b("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:((l=u.search.nodes)==null?void 0:l.filter(G).map(Gs))||[]}}async getPullRequestsAssociatedWithUser(e,r={}){var o;let n=[`involves:${e.username}`];return(o=e.repos)!=null&&o.length&&e.repos.forEach(i=>{n.push(`repo:${i.namespace}/${i.name}`)}),e.labelNames&&e.labelNames.forEach(i=>{n.push(`label:"${i}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async getPullRequestsForRepos(e,r={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=yt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),p&&g.push(`mentions:${p}`),d&&d.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c},r)}async getPullRequestForRepo(e,r={}){var d;let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=J(o),a=c=>({query:`query getPullRequest(
464
464
  $owner: String!
465
465
  $name: String!
466
466
  $number: Int!
@@ -470,18 +470,18 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
470
470
  name: $name
471
471
  ) {
472
472
  pullRequest(number: $number) {
473
- ${De(c,i,n)}
473
+ ${Ae(c,i,n)}
474
474
  }
475
475
  }
476
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await P(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await P(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new b("Could not fetch pull request by number",u.body.errors);let p=(d=u.body.data)==null?void 0:d.repository.pullRequest;return{data:p?wt(p):null}}async getPullRequestByGraphQLId(e,r={}){var d;let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=J(o),a=c=>({query:`query getPullRequest(
476
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await P(this.config,a(!0),r);u.body.errors&&Ue(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await P(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new b("Could not fetch pull request by number",u.body.errors);let p=(d=u.body.data)==null?void 0:d.repository.pullRequest;return{data:p?vt(p):null}}async getPullRequestByGraphQLId(e,r={}){var d;let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=J(o),a=c=>({query:`query getPullRequest(
477
477
  $graphQLId: ID!
478
478
  ) {
479
479
  node(id: $graphQLId) {
480
480
  ... on PullRequest {
481
- ${De(c,i,n)}
481
+ ${Ae(c,i,n)}
482
482
  }
483
483
  }
484
- }`,variables:{graphQLId:e.graphQLId}}),u=await P(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await P(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new b("Could not fetch pull request by id",u.body.errors);let p=(d=u.body.data)==null?void 0:d.node;return{data:p?wt(p):null}}async closePullRequest(e,r={}){var a,u,l;let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
484
+ }`,variables:{graphQLId:e.graphQLId}}),u=await P(this.config,a(!0),r);u.body.errors&&Ue(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await P(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new b("Could not fetch pull request by id",u.body.errors);let p=(d=u.body.data)==null?void 0:d.node;return{data:p?vt(p):null}}async closePullRequest(e,r={}){var a,u,l;let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
485
485
  closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
486
486
  pullRequest {
487
487
  id
@@ -589,13 +589,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
589
589
  }
590
590
  }
591
591
  }
592
- }`,l=await P(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),p=((g=(c=l.body.data)==null?void 0:c.repository.pullRequest.reviewThreads.nodes)==null?void 0:g.filter(G).reduce((f,w)=>{var E,D;if(!((D=(E=w.comments.nodes)==null?void 0:E[0])!=null&&D.pullRequestReview))return f;let h=w.comments.nodes[0].pullRequestReview,R=Ds(w);return R&&(f[h.id]||(f[h.id]=[]),f[h.id].push(R)),f},{}))??{};return{data:((I=(m=l.body.data)==null?void 0:m.repository.pullRequest.reviews.nodes)==null?void 0:I.filter(G).filter(f=>p[f.id]).map(f=>({author:f.author?{avatarUrl:f.author.avatarUrl,email:null,name:f.author.login}:null,body:f.body,createdAt:f.publishedAt?new Date(f.publishedAt):null,id:f.fullDatabaseId??f.databaseId.toString(),graphQLId:f.id,reviewComments:p[f.id],url:f.url})))??[]}}async getIssuesAssociatedWithUser(e,r={}){var c;let[n,o]=((c=e.cursor)==null?void 0:c.split(";"))||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(g=>{i.push(`label:"${g}"`)});let[a,u]=await Promise.all([n==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)]),l={},p=[],d=g=>{l[g.id]||(l[g.id]=!0,p.push(g))};return a==null||a.data.forEach(d),u==null||u.data.forEach(d),{pageInfo:{hasNextPage:(a==null?void 0:a.pageInfo.hasNextPage)||(u==null?void 0:u.pageInfo.hasNextPage)||!1,endCursor:`${(a==null?void 0:a.pageInfo.hasNextPage)&&(a==null?void 0:a.pageInfo.endCursor)||"null"};${(u==null?void 0:u.pageInfo.hasNextPage)&&(u==null?void 0:u.pageInfo.endCursor)||"null"}`},data:p}}async setPullRequestLabels(e,r={}){var u,l,p;let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
592
+ }`,l=await P(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),p=((g=(c=l.body.data)==null?void 0:c.repository.pullRequest.reviewThreads.nodes)==null?void 0:g.filter(G).reduce((f,w)=>{var E,D;if(!((D=(E=w.comments.nodes)==null?void 0:E[0])!=null&&D.pullRequestReview))return f;let h=w.comments.nodes[0].pullRequestReview,R=Ls(w);return R&&(f[h.id]||(f[h.id]=[]),f[h.id].push(R)),f},{}))??{};return{data:((I=(m=l.body.data)==null?void 0:m.repository.pullRequest.reviews.nodes)==null?void 0:I.filter(G).filter(f=>p[f.id]).map(f=>({author:f.author?{avatarUrl:f.author.avatarUrl,email:null,name:f.author.login}:null,body:f.body,createdAt:f.publishedAt?new Date(f.publishedAt):null,id:f.fullDatabaseId??f.databaseId.toString(),graphQLId:f.id,reviewComments:p[f.id],url:f.url})))??[]}}async getIssuesAssociatedWithUser(e,r={}){var c;let[n,o]=((c=e.cursor)==null?void 0:c.split(";"))||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(g=>{i.push(`label:"${g}"`)});let[a,u]=await Promise.all([n==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)]),l={},p=[],d=g=>{l[g.id]||(l[g.id]=!0,p.push(g))};return a==null||a.data.forEach(d),u==null||u.data.forEach(d),{pageInfo:{hasNextPage:(a==null?void 0:a.pageInfo.hasNextPage)||(u==null?void 0:u.pageInfo.hasNextPage)||!1,endCursor:`${(a==null?void 0:a.pageInfo.hasNextPage)&&(a==null?void 0:a.pageInfo.endCursor)||"null"};${(u==null?void 0:u.pageInfo.hasNextPage)&&(u==null?void 0:u.pageInfo.endCursor)||"null"}`},data:p}}async setPullRequestLabels(e,r={}){var u,l,p;let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
593
593
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
594
594
  pullRequest {
595
595
  id
596
596
  }
597
597
  }
598
- }`,a=await P(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(d=>{if(!d.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return d.graphQLId})}},r);if(!((p=(l=(u=a.body.data)==null?void 0:u.updatePullRequest)==null?void 0:l.pullRequest)!=null&&p.id))throw new b("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=Rt(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(d=>{n.push(`repo:${d.namespace}/${d.name}`)}),i&&i.forEach(d=>{n.push(`assignee:${d}`)}),a&&n.push(`updated:<${a}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),p&&p.forEach(d=>{n.push(`label:"${d}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async closeIssueWithReason(e,r={}){var u,l,p;let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
598
+ }`,a=await P(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(d=>{if(!d.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return d.graphQLId})}},r);if(!((p=(l=(u=a.body.data)==null?void 0:u.updatePullRequest)==null?void 0:l.pullRequest)!=null&&p.id))throw new b("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=yt(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(d=>{n.push(`repo:${d.namespace}/${d.name}`)}),i&&i.forEach(d=>{n.push(`assignee:${d}`)}),a&&n.push(`updated:<${a}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),p&&p.forEach(d=>{n.push(`label:"${d}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async closeIssueWithReason(e,r={}){var u,l,p;let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
599
599
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
600
600
  issue {
601
601
  id
@@ -636,7 +636,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
636
636
  repository(owner: $owner, name: $name) {
637
637
  milestones(first: $first, after: $cursor) {
638
638
  nodes {
639
- ${Se}
639
+ ${Ce}
640
640
  }
641
641
  pageInfo {
642
642
  endCursor
@@ -645,12 +645,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
645
645
  }
646
646
  }
647
647
  }
648
- `,variables:{owner:n,name:o,cursor:i,first:U}},r);if(!a.body.data)throw new b("Could not fetch milestones",a.body.errors);return{pageInfo:((u=a.body.data.repository.milestones)==null?void 0:u.pageInfo)??{endCursor:null,hasNextPage:!1},data:((p=(l=a.body.data.repository.milestones)==null?void 0:l.nodes)==null?void 0:p.map(qt))??[]}}async getLabelsForRepo(e,r={}){var u,l,p;let{repo:{namespace:n,name:o},cursor:i}=e,a=await P(this.config,{query:`
648
+ `,variables:{owner:n,name:o,cursor:i,first:U}},r);if(!a.body.data)throw new b("Could not fetch milestones",a.body.errors);return{pageInfo:((u=a.body.data.repository.milestones)==null?void 0:u.pageInfo)??{endCursor:null,hasNextPage:!1},data:((p=(l=a.body.data.repository.milestones)==null?void 0:l.nodes)==null?void 0:p.map(St))??[]}}async getLabelsForRepo(e,r={}){var u,l,p;let{repo:{namespace:n,name:o},cursor:i}=e,a=await P(this.config,{query:`
649
649
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
650
650
  repository(owner: $owner, name: $name) {
651
651
  labels(first: $first, after: $cursor) {
652
652
  nodes {
653
- ${Ce}
653
+ ${De}
654
654
  }
655
655
  pageInfo {
656
656
  endCursor
@@ -659,7 +659,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
659
659
  }
660
660
  }
661
661
  }
662
- `,variables:{owner:n,name:o,cursor:i,first:U}},r);if(!a.body.data)throw new b("Could not fetch labels",a.body.errors);return{pageInfo:((u=a.body.data.repository.labels)==null?void 0:u.pageInfo)??{endCursor:null,hasNextPage:!1},data:((p=(l=a.body.data.repository.labels)==null?void 0:l.nodes)==null?void 0:p.map(Et))??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${ie(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...y(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(vs)}}};var Ls="https://gitlab.com/api/v4",$s="https://gitlab.com/api/graphql",St=/\/api\/v\d+$/,br=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},Ue=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),br(e),St.test(e)||(e=e+"/api/v4"),e):Ls},Gs=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),br(e),St.test(e)&&(e=e.replace(St,"")),`${e}/api/graphql`):$s},v=(s,t,e)=>{let r=y(e.token||s.token);return s.request({url:Gs(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},Le=s=>s==null?void 0:s.map(t=>`"${t.message}"`).join(", ");var Lt=s=>s.split("/").slice(0,-1).join("/"),$t=s=>s.split("/").at(-1)??"",$e=s=>({id:s.id.replace(ue,""),graphQLId:s.id,namespace:Lt(s.fullPath),name:$t(s.fullPath),webUrl:s.webUrl}),Pr=s=>({id:s.id.replace(ue,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:Lt(s.fullPath),name:$t(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Ts={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Os={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var ks="gid://gitlab/User/",ue="gid://gitlab/Project/",xs="gid://gitlab/MergeRequest/",Ns="gid://gitlab/Issue/",_s="gid://gitlab/ProjectLabel/",Bs="gid://gitlab/Milestone/",Qs="gid://gitlab/Ci::Build/",Gt=`
662
+ `,variables:{owner:n,name:o,cursor:i,first:U}},r);if(!a.body.data)throw new b("Could not fetch labels",a.body.errors);return{pageInfo:((u=a.body.data.repository.labels)==null?void 0:u.pageInfo)??{endCursor:null,hasNextPage:!1},data:((p=(l=a.body.data.repository.labels)==null?void 0:l.nodes)==null?void 0:p.map(qt))??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${ie(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...y(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(Ss)}}};var Ts="https://gitlab.com/api/v4",Os="https://gitlab.com/api/graphql",Ct=/\/api\/v\d+$/,Pr=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},Le=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Pr(e),Ct.test(e)||(e=e+"/api/v4"),e):Ts},ks=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Pr(e),Ct.test(e)&&(e=e.replace(Ct,"")),`${e}/api/graphql`):Os},v=(s,t,e)=>{let r=y(e.token||s.token);return s.request({url:ks(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},$e=s=>s==null?void 0:s.map(t=>`"${t.message}"`).join(", ");var $t=s=>s.split("/").slice(0,-1).join("/"),Gt=s=>s.split("/").at(-1)??"",Ge=s=>({id:s.id.replace(ue,""),graphQLId:s.id,namespace:$t(s.fullPath),name:Gt(s.fullPath),webUrl:s.webUrl}),wr=s=>({id:s.id.replace(ue,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:$t(s.fullPath),name:Gt(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),xs={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Ns={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var _s="gid://gitlab/User/",ue="gid://gitlab/Project/",Bs="gid://gitlab/MergeRequest/",Qs="gid://gitlab/Issue/",js="gid://gitlab/ProjectLabel/",Fs="gid://gitlab/Milestone/",Ms="gid://gitlab/Ci::Build/",Tt=`
663
663
  description
664
664
  dueDate
665
665
  id
@@ -668,7 +668,7 @@ startDate
668
668
  state
669
669
  title
670
670
  webPath
671
- `,Ct=`
671
+ `,Dt=`
672
672
  id
673
673
  fullPath
674
674
  webUrl
@@ -689,12 +689,12 @@ username
689
689
  publicEmail
690
690
  avatarUrl
691
691
  webUrl
692
- `,Tt=`
692
+ `,Ot=`
693
693
  color
694
694
  description
695
695
  id
696
696
  title
697
- `,Dt=`
697
+ `,At=`
698
698
  author {
699
699
  ${V}
700
700
  }
@@ -711,7 +711,7 @@ id
711
711
  iid
712
712
  labels {
713
713
  nodes {
714
- ${Tt}
714
+ ${Ot}
715
715
  }
716
716
  }
717
717
  state
@@ -722,9 +722,9 @@ upvotes
722
722
  userNotesCount
723
723
  webUrl
724
724
  milestone {
725
- ${Gt}
725
+ ${Tt}
726
726
  }
727
- `,js=`
727
+ `,zs=`
728
728
  stages {
729
729
  nodes {
730
730
  jobs {
@@ -740,7 +740,7 @@ stages {
740
740
  name
741
741
  }
742
742
  }
743
- `,wr=(s,t,e)=>`
743
+ `,vr=(s,t,e)=>`
744
744
  id
745
745
  state
746
746
  author {
@@ -784,33 +784,35 @@ reviewers {
784
784
  mergeStatusEnum
785
785
  labels {
786
786
  nodes {
787
- ${Tt}
787
+ ${Ot}
788
788
  }
789
789
  }
790
790
  ${s?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
791
- ${t?`milestone { ${Gt} }`:""}
792
- ${e?`headPipeline { ${js} }`:""}
793
- `,Y=s=>`${s.namespace}/${s.name}`,Fs=s=>`${s.namespace}/${s.name}`,zs=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),At=s=>{var t;return{id:s.id.replace(ue,""),graphQLId:s.id,namespace:Lt(s.fullPath),name:$t(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:(t=s.repository)!=null&&t.rootRef?{name:s.repository.rootRef}:null,permissions:zs(s.userPermissions)}},Ms=s=>({path:s.path,isDirectory:s.type==="tree"}),Ws={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},K=(s,t,e)=>{let r=s.avatarUrl;return!t&&(r!=null&&r.startsWith("/"))?r=`https://gitlab.com${r}`:t&&(r!=null&&r.startsWith("/"))&&e&&(r=`${e.replace(/\/+?$/,"")}${r}`),{id:s.id.replace(ks,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},Ot=s=>({color:s.color,description:s.description,id:s.id.replace(_s,""),graphQLId:s.id,name:s.title}),Hs=(s,t)=>s?s==="FAILED"&&t?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[s]:null,Js=(s,t,e)=>{var n;let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:K(s,t,e),state:(n=s.mergeRequestInteraction)!=null&&n.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},vr=(s,t,e,r,n)=>{var i,a,u,l,p,d,c,g,m,I,f,w;let o=(i=s.reviewers)!=null&&i.nodes?s.reviewers.nodes.map(h=>Js(h,r,n)):null;return{id:s.id.replace(xs,""),graphQLId:s.id,title:s.title,number:parseInt(s.iid,10),state:Ws[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?K(s.author,r,n):null,createdDate:new Date(s.createdAt),isDraft:s.draft,repository:{id:t.id,graphQLId:t.graphQLId,name:t.name,owner:{login:t.namespace},remoteInfo:t.httpsUrl&&t.sshUrl?{cloneUrlHTTPS:t.httpsUrl,cloneUrlSSH:t.sshUrl}:null},headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:((l=(u=(a=s.headPipeline)==null?void 0:a.stages)==null?void 0:u.nodes)==null?void 0:l.flatMap(h=>{var R,E;return((E=(R=h.jobs)==null?void 0:R.nodes)==null?void 0:E.map(D=>({completedAt:D.finishedAt?new Date(D.finishedAt):null,description:null,name:D.name??null,state:Hs(D.status,D.allowFailure),stage:h.name??null,startedAt:new Date(D.createdAt),url:`${t.webUrl}/-/jobs/${D.id.replace(Qs,"")}`})))??[]}))??[]},baseRef:{name:s.targetBranch,oid:((p=s.diffRefs)==null?void 0:p.baseSha)??null},headRef:{name:s.sourceBranch,oid:((d=s.diffRefs)==null?void 0:d.headSha)??null},url:s.webUrl,updatedDate:new Date(s.updatedAt),closedDate:s.mergedAt?new Date(s.mergedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:(c=s.assignees)!=null&&c.nodes?s.assignees.nodes.map(h=>K(h,r,n)):null,reviews:o,reviewDecision:F(o),additions:((g=s.diffStatsSummary)==null?void 0:g.additions)||0,deletions:((m=s.diffStatsSummary)==null?void 0:m.deletions)||0,fileCount:((I=s.diffStatsSummary)==null?void 0:I.fileCount)||0,commitCount:s.commitCount||0,mergeableState:Os[s.mergeStatusEnum],milestone:s.milestone?kt(s.milestone,t.webUrl):null,labels:((w=(f=s.labels)==null?void 0:f.nodes)==null?void 0:w.map(Ot))??[],permissions:null}},Ut=(s,t,e,r)=>{var n,o;return{author:K(s.author,e,r),assignees:s.assignees.nodes.map(i=>K(i,e,r)),commentCount:s.userNotesCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:s.description,graphQLId:s.id,id:s.id.replace(Ns,""),labels:((o=(n=s.labels)==null?void 0:n.nodes)==null?void 0:o.map(Ot))??[],number:s.iid,repository:{id:t.id.replace(ue,""),graphQLId:t.id,name:t.name,owner:{login:t.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?kt(s.milestone,t.webUrl):null}},kt=(s,t)=>({id:s.id.replace(Bs,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${t}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),le=class extends x{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){var o;let n=(o=(await v(this.config,{query:`
791
+ ${t?`milestone { ${Tt} }`:""}
792
+ ${e?`headPipeline { ${zs} }`:""}
793
+ `,Y=s=>`${s.namespace}/${s.name}`,Ws=s=>`${s.namespace}/${s.name}`,Hs=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),Ut=s=>{var t;return{id:s.id.replace(ue,""),graphQLId:s.id,namespace:$t(s.fullPath),name:Gt(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:(t=s.repository)!=null&&t.rootRef?{name:s.repository.rootRef}:null,permissions:Hs(s.userPermissions)}},Js=s=>({path:s.path,isDirectory:s.type==="tree"}),Vs={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},qr=(s,t,e)=>!t&&(s!=null&&s.startsWith("/"))?`https://gitlab.com${s}`:t&&(s!=null&&s.startsWith("/"))&&e?`${e.replace(/\/+?$/,"")}${s}`:s,K=(s,t,e)=>{let r=qr(s.avatarUrl,t,e);return{id:s.id.replace(_s,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},kt=s=>({color:s.color,description:s.description,id:s.id.replace(js,""),graphQLId:s.id,name:s.title}),Ks=(s,t)=>s?s==="FAILED"&&t?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[s]:null,Xs=(s,t,e)=>{var n;let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:K(s,t,e),state:(n=s.mergeRequestInteraction)!=null&&n.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},Er=(s,t,e,r,n)=>{var i,a,u,l,p,d,c,g,m,I,f,w;let o=(i=s.reviewers)!=null&&i.nodes?s.reviewers.nodes.map(h=>Xs(h,r,n)):null;return{id:s.id.replace(Bs,""),graphQLId:s.id,title:s.title,number:parseInt(s.iid,10),state:Vs[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?K(s.author,r,n):null,createdDate:new Date(s.createdAt),isDraft:s.draft,repository:{id:t.id,graphQLId:t.graphQLId,name:t.name,owner:{login:t.namespace},remoteInfo:t.httpsUrl&&t.sshUrl?{cloneUrlHTTPS:t.httpsUrl,cloneUrlSSH:t.sshUrl}:null},headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:((l=(u=(a=s.headPipeline)==null?void 0:a.stages)==null?void 0:u.nodes)==null?void 0:l.flatMap(h=>{var R,E;return((E=(R=h.jobs)==null?void 0:R.nodes)==null?void 0:E.map(D=>({completedAt:D.finishedAt?new Date(D.finishedAt):null,description:null,name:D.name??null,state:Ks(D.status,D.allowFailure),stage:h.name??null,startedAt:new Date(D.createdAt),url:`${t.webUrl}/-/jobs/${D.id.replace(Ms,"")}`})))??[]}))??[]},baseRef:{name:s.targetBranch,oid:((p=s.diffRefs)==null?void 0:p.baseSha)??null},headRef:{name:s.sourceBranch,oid:((d=s.diffRefs)==null?void 0:d.headSha)??null},url:s.webUrl,updatedDate:new Date(s.updatedAt),closedDate:s.mergedAt?new Date(s.mergedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:(c=s.assignees)!=null&&c.nodes?s.assignees.nodes.map(h=>K(h,r,n)):null,reviews:o,reviewDecision:F(o),additions:((g=s.diffStatsSummary)==null?void 0:g.additions)||0,deletions:((m=s.diffStatsSummary)==null?void 0:m.deletions)||0,fileCount:((I=s.diffStatsSummary)==null?void 0:I.fileCount)||0,commitCount:s.commitCount||0,mergeableState:Ns[s.mergeStatusEnum],milestone:s.milestone?xt(s.milestone,t.webUrl):null,labels:((w=(f=s.labels)==null?void 0:f.nodes)==null?void 0:w.map(kt))??[],permissions:null}},Lt=(s,t,e,r)=>{var n,o;return{author:K(s.author,e,r),assignees:s.assignees.nodes.map(i=>K(i,e,r)),commentCount:s.userNotesCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:s.description,graphQLId:s.id,id:s.id.replace(Qs,""),labels:((o=(n=s.labels)==null?void 0:n.nodes)==null?void 0:o.map(kt))??[],number:s.iid,repository:{id:t.id.replace(ue,""),graphQLId:t.id,name:t.name,owner:{login:t.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?xt(s.milestone,t.webUrl):null}},xt=(s,t)=>({id:s.id.replace(Fs,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${t}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),le=class extends x{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){var o;let n=(o=(await v(this.config,{query:`
794
794
  query getCurrentUser {
795
795
  currentUser {
796
796
  ${V}
797
797
  }
798
798
  }
799
- `},e)).body.data)==null?void 0:o.currentUser;if(!n)throw new Error("Current user not found.");return{data:K(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(t,e={}){var i,a,u,l;let r=Y(t.repo),o=(l=(u=(a=(i=(await v(this.config,{query:`
799
+ `},e)).body.data)==null?void 0:o.currentUser;if(!n)throw new Error("Current user not found.");return{data:K(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(t,e={}){var a,u,l,p;let r=Y(t.repo),o=(p=(l=(u=(a=(await v(this.config,{query:`
800
800
  query getUserForCommit($fullPath: ID!, $oid: String!) {
801
801
  project(fullPath: $fullPath) {
802
802
  repository {
803
803
  tree(ref: $oid) {
804
804
  lastCommit {
805
+ author {
806
+ avatarUrl
807
+ }
805
808
  authorName
806
809
  authorEmail
807
- authorGravatar
808
810
  }
809
811
  }
810
812
  }
811
813
  }
812
814
  }
813
- `,variables:{fullPath:r,oid:t.oid}},e)).body.data)==null?void 0:i.project)==null?void 0:a.repository)==null?void 0:u.tree)==null?void 0:l.lastCommit;if(!o)throw new Error("Commit not found.");return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:o.authorGravatar}}}async getAccountForEmail(t,e={}){var o,i,a;let n=(a=(i=(o=(await v(this.config,{query:`
815
+ `,variables:{fullPath:r,oid:t.oid}},e)).body.data)==null?void 0:a.project)==null?void 0:u.repository)==null?void 0:l.tree)==null?void 0:p.lastCommit;if(!o)throw new Error("Commit not found.");let i=qr(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(t,e={}){var o,i,a;let n=(a=(i=(o=(await v(this.config,{query:`
814
816
  query getAccountForEmail($email: String!) {
815
817
  users(search: $email) {
816
818
  nodes {
@@ -848,19 +850,19 @@ query getAccountsForRepo(
848
850
  `,variables:{fullPath:`${r}/${n}`,after:o}},e),a=(d=(p=(l=(u=i.body.data)==null?void 0:u.project)==null?void 0:l.projectMembers)==null?void 0:p.nodes)==null?void 0:d.map(I=>I.user).filter(I=>I!==null);return{pageInfo:((m=(g=(c=i.body.data)==null?void 0:c.project)==null?void 0:g.projectMembers)==null?void 0:m.pageInfo)??{endCursor:null,hasNextPage:!1},data:(a==null?void 0:a.map(I=>K(I,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))??[]}}async getRepo(t,e={}){var o;let r=Y(t),n=await v(this.config,{query:`
849
851
  query getRepo($fullPath: ID!) {
850
852
  project(fullPath: $fullPath) {
851
- ${Ct}
853
+ ${Dt}
852
854
  }
853
855
  }
854
- `,variables:{fullPath:r}},e);if(!((o=n.body.data)!=null&&o.project))throw new Error(`Repository ${r} not found`);return{data:At(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(Y).map((u,l)=>`
856
+ `,variables:{fullPath:r}},e);if(!((o=n.body.data)!=null&&o.project))throw new Error(`Repository ${r} not found`);return{data:Ut(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(Y).map((u,l)=>`
855
857
  getRepo_${l}: project(fullPath: "${u}") {
856
- ${Ct}
858
+ ${Dt}
857
859
  }
858
860
  `).join(`
859
861
  `),o=await v(this.config,{query:`
860
862
  query batchGetRepos {
861
863
  ${n}
862
864
  }
863
- `},e);if(!o.body.data)throw new Error(Le(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(At(p)):a.push({input:u})}),{data:i,errors:a}}async getRepos(t,e={}){let r=[];for(let i=0;i<t.length;i+=15)r.push(t.slice(i,i+15));return(await Promise.all(r.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(t,e={}){var o,i,a,u,l;let r=await v(this.config,{query:`
865
+ `},e);if(!o.body.data)throw new Error($e(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(Ut(p)):a.push({input:u})}),{data:i,errors:a}}async getRepos(t,e={}){let r=[];for(let i=0;i<t.length;i+=15)r.push(t.slice(i,i+15));return(await Promise.all(r.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(t,e={}){var o,i,a,u,l;let r=await v(this.config,{query:`
864
866
  query getReposForCurrentUser($after: String) {
865
867
  projects(membership: true first: 100 after: $after) {
866
868
  pageInfo {
@@ -868,11 +870,11 @@ query getReposForCurrentUser($after: String) {
868
870
  hasNextPage
869
871
  }
870
872
  nodes {
871
- ${Ct}
873
+ ${Dt}
872
874
  }
873
875
  }
874
876
  }
875
- `,variables:{after:t.cursor}},e);if(!((o=r.body.data)!=null&&o.projects))throw new Error(Le(r.body.errors)||r.statusText||"Unknown error");let n=((a=(i=r.body.data)==null?void 0:i.projects)==null?void 0:a.nodes)||[];return{pageInfo:(l=(u=r.body.data)==null?void 0:u.projects)==null?void 0:l.pageInfo,data:n.map(At)}}async getRefs(t,e,r={}){var u;let n=Y(e.repo),o=new URL(`${Ue(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",((u=e.page)==null?void 0:u.toString())||"1"),o.searchParams.set("per_page",U.toString());let i=await this.config.request({url:o.toString(),headers:y(r.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(l=>({name:l.name,commit:{oid:l.commit.id,authoredDate:new Date(l.commit.authored_date),committedDate:new Date(l.commit.committed_date)}}))}}async getBranches(t,e={}){return this.getRefs("branches",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getBlame(t,e={}){let r=Y(t.repo),n=new URL(`${Ue(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/blame`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:y(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(t,e={}){var a,u,l,p;let r="";(a=t.repo)!=null&&a.id?r=`projectId:"${t.repo.id}"`:(u=t.repo)!=null&&u.namespace&&((l=t.repo)!=null&&l.name)&&(r=`projectPath:"${t.repo.namespace}/${t.repo.name}"`);let n=Ts[t.association],o=await v(this.config,{query:`
877
+ `,variables:{after:t.cursor}},e);if(!((o=r.body.data)!=null&&o.projects))throw new Error($e(r.body.errors)||r.statusText||"Unknown error");let n=((a=(i=r.body.data)==null?void 0:i.projects)==null?void 0:a.nodes)||[];return{pageInfo:(l=(u=r.body.data)==null?void 0:u.projects)==null?void 0:l.pageInfo,data:n.map(Ut)}}async getRefs(t,e,r={}){var u;let n=Y(e.repo),o=new URL(`${Le(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",((u=e.page)==null?void 0:u.toString())||"1"),o.searchParams.set("per_page",U.toString());let i=await this.config.request({url:o.toString(),headers:y(r.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(l=>({name:l.name,commit:{oid:l.commit.id,authoredDate:new Date(l.commit.authored_date),committedDate:new Date(l.commit.committed_date)}}))}}async getBranches(t,e={}){return this.getRefs("branches",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getBlame(t,e={}){let r=Y(t.repo),n=new URL(`${Le(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/blame`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:y(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(t,e={}){var a,u,l,p;let r="";(a=t.repo)!=null&&a.id?r=`projectId:"${t.repo.id}"`:(u=t.repo)!=null&&u.namespace&&((l=t.repo)!=null&&l.name)&&(r=`projectPath:"${t.repo.namespace}/${t.repo.name}"`);let n=xs[t.association],o=await v(this.config,{query:`
876
878
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
877
879
  user(username: $username) {
878
880
  ${n}(state:opened first:100 after:$cursor labels: $labelNames${r?` ${r}`:""}) {
@@ -881,12 +883,12 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
881
883
  hasNextPage
882
884
  }
883
885
  nodes {
884
- ${wr(!0,!0,!0)}
886
+ ${vr(!0,!0,!0)}
885
887
  }
886
888
  }
887
889
  }
888
890
  }
889
- `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!o.body.data)throw new Error(Le(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[n];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:((p=i.nodes)==null?void 0:p.filter(d=>t.includeFromArchivedRepos||!d.project.archived).map(d=>vr(d,Pr(d.project),Pr(d.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))||[]}}async getPullRequestsAssociatedWithUser(t,e={}){var D,S;let[r,n,o]=((D=t.cursor)==null?void 0:D.split(";"))||[void 0,void 0,void 0],i=(r==null?void 0:r.split("-"))||[],a=(n==null?void 0:n.split("-"))||[],u=(o==null?void 0:o.split("-"))||[],l=[],p=[],d=[],c=0;do{let A=t.repos&&t.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:i[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...A&&{repo:A}},e)),a[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...A&&{repo:A}},e)),u[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...A&&{repo:A}},e)),c++}while(c<(((S=t.repos)==null?void 0:S.length)||0));let g=[l,p,d].flat(),m=await Promise.all(g),I={},f=[],w=A=>{I[A.id]||(I[A.id]=!0,f.push(A))},h=!1,E=m.map((A,Zt)=>{var er;let ge="";return A&&A.data.forEach(w),A!=null&&A.pageInfo.hasNextPage?(h=!0,ge+=`${A.pageInfo.endCursor||"null"}`):ge+="null",(er=t.repos)!=null&&er.length&&(Zt+1)%t.repos.length!==0?ge+="-":Zt+1<m.length&&(ge+=";"),ge}).join("");return{pageInfo:{hasNextPage:h,endCursor:E},data:f}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=t||{},u={},l=[],p=[],d=(c,g,m)=>{l.push(`$${c}: ${m}`),p.push(`${c}: $${c}`),u[c]=g};return e&&d("updatedBefore",e,"Time"),n&&d("authorUsername",n,"String"),o&&d("assigneeUsername",o[0],"String"),i&&d("labelName",i,"[String]"),r!=null&&d("draft",r,"Boolean"),a&&d("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(t,e={},r){var f,w,h;let{cursor:n,repo:o}=t||{},i=Y(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),p={fullPath:i,...a},d=await v(this.config,{query:`
891
+ `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!o.body.data)throw new Error($e(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[n];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:((p=i.nodes)==null?void 0:p.filter(d=>t.includeFromArchivedRepos||!d.project.archived).map(d=>Er(d,wr(d.project),wr(d.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))||[]}}async getPullRequestsAssociatedWithUser(t,e={}){var D,S;let[r,n,o]=((D=t.cursor)==null?void 0:D.split(";"))||[void 0,void 0,void 0],i=(r==null?void 0:r.split("-"))||[],a=(n==null?void 0:n.split("-"))||[],u=(o==null?void 0:o.split("-"))||[],l=[],p=[],d=[],c=0;do{let A=t.repos&&t.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:i[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...A&&{repo:A}},e)),a[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...A&&{repo:A}},e)),u[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...A&&{repo:A}},e)),c++}while(c<(((S=t.repos)==null?void 0:S.length)||0));let g=[l,p,d].flat(),m=await Promise.all(g),I={},f=[],w=A=>{I[A.id]||(I[A.id]=!0,f.push(A))},h=!1,E=m.map((A,er)=>{var tr;let ge="";return A&&A.data.forEach(w),A!=null&&A.pageInfo.hasNextPage?(h=!0,ge+=`${A.pageInfo.endCursor||"null"}`):ge+="null",(tr=t.repos)!=null&&tr.length&&(er+1)%t.repos.length!==0?ge+="-":er+1<m.length&&(ge+=";"),ge}).join("");return{pageInfo:{hasNextPage:h,endCursor:E},data:f}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=t||{},u={},l=[],p=[],d=(c,g,m)=>{l.push(`$${c}: ${m}`),p.push(`${c}: $${c}`),u[c]=g};return e&&d("updatedBefore",e,"Time"),n&&d("authorUsername",n,"String"),o&&d("assigneeUsername",o[0],"String"),i&&d("labelName",i,"[String]"),r!=null&&d("draft",r,"Boolean"),a&&d("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(t,e={},r){var f,w,h;let{cursor:n,repo:o}=t||{},i=Y(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),p={fullPath:i,...a},d=await v(this.config,{query:`
890
892
  query getPullRequestsForRepo(
891
893
  $fullPath: ID!
892
894
  $after: String
@@ -911,12 +913,12 @@ query getPullRequestsForRepo(
911
913
  hasNextPage
912
914
  }
913
915
  nodes {
914
- ${wr(!1,!0,!0)}
916
+ ${vr(!1,!0,!0)}
915
917
  }
916
918
  }
917
919
  }
918
920
  }
919
- `,variables:{...p,after:n}},e),c=[],g=(f=d.body.data)==null?void 0:f.project;if(!r&&(g!=null&&g.archived))return{pageInfo:null,data:[]};let m=$e(g||{id:"",fullPath:"",webUrl:""});return(((w=g==null?void 0:g.mergeRequests)==null?void 0:w.nodes)||[]).forEach(R=>{c.push(vr(R,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:(h=g==null?void 0:g.mergeRequests)==null?void 0:h.pageInfo,data:c}}async getPullRequestsForRepo(t,e={}){return this.getPullRequestsForRepoBase(t,e,!1)}async getPullRequestsForRepos(t,e={}){let{repos:r,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=t;return{data:(await Promise.all(r.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,t.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(t,e={}){var a,u,l;let{pullRequest:r}=t,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
921
+ `,variables:{...p,after:n}},e),c=[],g=(f=d.body.data)==null?void 0:f.project;if(!r&&(g!=null&&g.archived))return{pageInfo:null,data:[]};let m=Ge(g||{id:"",fullPath:"",webUrl:""});return(((w=g==null?void 0:g.mergeRequests)==null?void 0:w.nodes)||[]).forEach(R=>{c.push(Er(R,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:(h=g==null?void 0:g.mergeRequests)==null?void 0:h.pageInfo,data:c}}async getPullRequestsForRepo(t,e={}){return this.getPullRequestsForRepoBase(t,e,!1)}async getPullRequestsForRepos(t,e={}){let{repos:r,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=t;return{data:(await Promise.all(r.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,t.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(t,e={}){var a,u,l;let{pullRequest:r}=t,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
920
922
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
921
923
  errors,
922
924
  mergeRequest {
@@ -981,18 +983,18 @@ query getPullRequestsForRepo(
981
983
  id
982
984
  }
983
985
  }
984
- }`;if(!((p=(l=(u=(await v(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:o}},e)).body.data)==null?void 0:u.mergeRequestSetLabels)==null?void 0:l.mergeRequest)!=null&&p.id))throw new Error("Could not set pull request labels")}async getIssue(t,e={}){var o,i,a;let r=Fs(t),n=await v(this.config,{query:`
986
+ }`;if(!((p=(l=(u=(await v(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:o}},e)).body.data)==null?void 0:u.mergeRequestSetLabels)==null?void 0:l.mergeRequest)!=null&&p.id))throw new Error("Could not set pull request labels")}async getIssue(t,e={}){var o,i,a;let r=Ws(t),n=await v(this.config,{query:`
985
987
  query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
986
988
  project(fullPath: $projectId) {
987
989
  id
988
990
  fullPath
989
991
  webUrl
990
992
  issue(iid: $issueNumber) {
991
- ${Dt}
993
+ ${At}
992
994
  }
993
995
  }
994
996
  }
995
- `,variables:{issueNumber:t.number,projectId:r}},e);if(!((o=n.body.data)!=null&&o.project))throw new Error(`Repository ${r} not found`);if(!((a=(i=n.body.data)==null?void 0:i.project)!=null&&a.issue))throw new Error(`Issue ${t.number} not found`);return{data:Ut(n.body.data.project.issue,$e(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(t){let{updatedBefore:e,authorLogin:r,assigneeLogins:n,labelNames:o}=t||{},i={},a=[],u=[],l=(p,d,c)=>{a.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),i[p]=d};return e&&l("updatedBefore",e,"Time"),r&&l("authorUsername",r,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(t,e={}){var f,w,h;let{cursor:r,repo:n}=t||{},o=Y(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:o,...i},p=`
997
+ `,variables:{issueNumber:t.number,projectId:r}},e);if(!((o=n.body.data)!=null&&o.project))throw new Error(`Repository ${r} not found`);if(!((a=(i=n.body.data)==null?void 0:i.project)!=null&&a.issue))throw new Error(`Issue ${t.number} not found`);return{data:Lt(n.body.data.project.issue,Ge(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(t){let{updatedBefore:e,authorLogin:r,assigneeLogins:n,labelNames:o}=t||{},i={},a=[],u=[],l=(p,d,c)=>{a.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),i[p]=d};return e&&l("updatedBefore",e,"Time"),r&&l("authorUsername",r,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(t,e={}){var f,w,h;let{cursor:r,repo:n}=t||{},o=Y(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:o,...i},p=`
996
998
  query GetIssuesFromProject(
997
999
  $fullPath: ID!
998
1000
  $after: String
@@ -1012,7 +1014,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1012
1014
  ${u.length?u.join(" "):""}
1013
1015
  ) {
1014
1016
  nodes {
1015
- ${Dt}
1017
+ ${At}
1016
1018
  }
1017
1019
  pageInfo {
1018
1020
  endCursor
@@ -1020,7 +1022,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1020
1022
  }
1021
1023
  }
1022
1024
  }
1023
- }`,d=await v(this.config,{query:p,variables:{...l,after:r}},e),c=[],g=(f=d.body.data)==null?void 0:f.project,m=$e(g||{id:"",fullPath:"",webUrl:""});return(((w=g==null?void 0:g.issues)==null?void 0:w.nodes)||[]).forEach(R=>{c.push(Ut(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:((h=g==null?void 0:g.issues)==null?void 0:h.pageInfo)??{endCursor:null,hasNextPage:!1},data:c.sort((R,E)=>(R.updatedDate||R.createdDate).getTime()-(E.updatedDate||E.createdDate).getTime())}}async getIssuesForRepos(t,e={}){var g,m,I,f,w;let{cursor:r}=t||{},n=t.repoIds.map(h=>h.toString().startsWith(ue)?h:`${ue}${h}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(t),u={projectIds:n,...o},l=`
1025
+ }`,d=await v(this.config,{query:p,variables:{...l,after:r}},e),c=[],g=(f=d.body.data)==null?void 0:f.project,m=Ge(g||{id:"",fullPath:"",webUrl:""});return(((w=g==null?void 0:g.issues)==null?void 0:w.nodes)||[]).forEach(R=>{c.push(Lt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:((h=g==null?void 0:g.issues)==null?void 0:h.pageInfo)??{endCursor:null,hasNextPage:!1},data:c.sort((R,E)=>(R.updatedDate||R.createdDate).getTime()-(E.updatedDate||E.createdDate).getTime())}}async getIssuesForRepos(t,e={}){var g,m,I,f,w;let{cursor:r}=t||{},n=t.repoIds.map(h=>h.toString().startsWith(ue)?h:`${ue}${h}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(t),u={projectIds:n,...o},l=`
1024
1026
  query GetIssuesFromProject(
1025
1027
  $projectIds: [ID!]
1026
1028
  $after: String
@@ -1046,12 +1048,12 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1046
1048
  ${a.length?a.join(" "):""}
1047
1049
  ) {
1048
1050
  nodes {
1049
- ${Dt}
1051
+ ${At}
1050
1052
  }
1051
1053
  }
1052
1054
  }
1053
1055
  }
1054
- }`,p=await v(this.config,{query:l,variables:{...u,after:r}},e),d=[];return(((m=(g=p.body.data)==null?void 0:g.projects)==null?void 0:m.nodes)||[]).forEach(h=>{var D;if(!t.includeFromArchivedRepos&&h.archived)return;let R=$e(h);(((D=h.issues)==null?void 0:D.nodes)||[]).forEach(S=>d.push(Ut(S,R,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:((w=(f=(I=p.body)==null?void 0:I.data)==null?void 0:f.projects)==null?void 0:w.pageInfo)??{endCursor:null,hasNextPage:!1},data:d.sort((h,R)=>(h.updatedDate||h.createdDate).getTime()-(R.updatedDate||R.createdDate).getTime())}}async setIssueState(t,e={}){var a,u,l;let{issue:r,state:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1056
+ }`,p=await v(this.config,{query:l,variables:{...u,after:r}},e),d=[];return(((m=(g=p.body.data)==null?void 0:g.projects)==null?void 0:m.nodes)||[]).forEach(h=>{var D;if(!t.includeFromArchivedRepos&&h.archived)return;let R=Ge(h);(((D=h.issues)==null?void 0:D.nodes)||[]).forEach(S=>d.push(Lt(S,R,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:((w=(f=(I=p.body)==null?void 0:I.data)==null?void 0:f.projects)==null?void 0:w.pageInfo)??{endCursor:null,hasNextPage:!1},data:d.sort((h,R)=>(h.updatedDate||h.createdDate).getTime()-(R.updatedDate||R.createdDate).getTime())}}async setIssueState(t,e={}){var a,u,l;let{issue:r,state:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1055
1057
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1056
1058
  issue {
1057
1059
  id
@@ -1091,7 +1093,7 @@ query getLabelsForRepo(
1091
1093
  webUrl
1092
1094
  milestones(after: $after) {
1093
1095
  nodes {
1094
- ${Gt}
1096
+ ${Tt}
1095
1097
  }
1096
1098
  pageInfo {
1097
1099
  endCursor
@@ -1100,7 +1102,7 @@ query getLabelsForRepo(
1100
1102
  }
1101
1103
  }
1102
1104
  }
1103
- `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:((l=(u=(a=i.body.data)==null?void 0:a.project)==null?void 0:u.milestones)==null?void 0:l.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=(p=i.body.data)==null?void 0:p.project)==null?void 0:d.milestones)==null?void 0:c.nodes)==null?void 0:g.map(m=>{var I,f;return kt(m,((f=(I=i.body.data)==null?void 0:I.project)==null?void 0:f.webUrl)||"")}))??[]}}async getLabelsForRepo(t,e={}){var a,u,l,p,d,c,g;let{repo:{namespace:r,name:n},cursor:o}=t,i=await v(this.config,{query:`
1105
+ `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:((l=(u=(a=i.body.data)==null?void 0:a.project)==null?void 0:u.milestones)==null?void 0:l.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=(p=i.body.data)==null?void 0:p.project)==null?void 0:d.milestones)==null?void 0:c.nodes)==null?void 0:g.map(m=>{var I,f;return xt(m,((f=(I=i.body.data)==null?void 0:I.project)==null?void 0:f.webUrl)||"")}))??[]}}async getLabelsForRepo(t,e={}){var a,u,l,p,d,c,g;let{repo:{namespace:r,name:n},cursor:o}=t,i=await v(this.config,{query:`
1104
1106
  query getLabelsForRepo(
1105
1107
  $fullPath: ID!
1106
1108
  $after: String
@@ -1110,7 +1112,7 @@ query getLabelsForRepo(
1110
1112
  ) {
1111
1113
  labels(after: $after) {
1112
1114
  nodes {
1113
- ${Tt}
1115
+ ${Ot}
1114
1116
  }
1115
1117
  pageInfo {
1116
1118
  endCursor
@@ -1119,5 +1121,5 @@ query getLabelsForRepo(
1119
1121
  }
1120
1122
  }
1121
1123
  }
1122
- `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:((l=(u=(a=i.body.data)==null?void 0:a.project)==null?void 0:u.labels)==null?void 0:l.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=(p=i.body.data)==null?void 0:p.project)==null?void 0:d.labels)==null?void 0:c.nodes)==null?void 0:g.map(Ot))??[]}}async getTreeForRepo(t,e={}){let r=Y(t.repo),n=new URL(t.cursor??`${Ue(this.config,e)}/projects/${encodeURIComponent(r)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",t.branch);let o=await this.config.request({url:n.toString(),headers:y(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(Ms),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var Vs="https://api.atlassian.com/ex/jira",Ge=100,xt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Er="/rest/api/2/search/jql",qr="/rest/api/2/search",Nt=(s,t,e,r)=>{var a,u,l,p;let n=s.fields.assignee,o=!r,i=(s.fields[(t==null?void 0:t.Sprint)??""]??[]).filter(d=>typeof d=="object");return{id:s.id,commentCount:s.fields.comment.comments.length,number:s.key,title:s.fields.summary,url:e?`${e}/browse/${s.key}`:null,closedDate:null,createdDate:new Date(s.fields.created),author:Te(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[Te(n,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:r??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:Zs(s.fields.status),statusTransitions:((a=s.transitions)==null?void 0:a.map(Ks))??[],components:((u=s.fields.components)==null?void 0:u.map(Xs))??[],type:s.fields.issuetype.name,upvoteCount:((l=s.fields.votes)==null?void 0:l.votes)||0,labels:((p=s.fields.labels)==null?void 0:p.map(d=>({color:null,description:null,id:null,name:d})))??[],sprints:i.map(en),fixVersions:s.fields.fixVersions.map(tn)}},Ks=s=>{let t;switch(s.to.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:t}}},Xs=s=>({description:s.description??null,id:s.id,name:s.name}),Ys=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,Te=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:Ys(s,t,e)}),Zs=s=>{let t;switch(s.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:t}},en=s=>({id:s.id.toString(),name:s.name,isActive:s.state==="active",startDate:s.startDate?new Date(s.startDate):null,endDate:s.endDate?new Date(s.endDate):null,completedDate:s.completeDate?new Date(s.completeDate):null}),tn=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),Z=(s,t,e)=>e?`${t.baseUrl||Vs}/${e}`:`${(t==null?void 0:t.baseUrl)||s.baseUrl}`,Oe=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${Z(s,e,r)}/rest/api/2/field`,headers:y(e.token||s.token)})).body},ke=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${Z(s,r,o)}/rest/api/2/issue/${n}?fields=${xt.join(",")}&expand=transitions`,headers:y(r.token||s.token)});return{data:Nt(a.body,i,e,o)}},xe=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1123
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(w=>u.push(`labels = "${w}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?qr:Er,c=new URL(`${Z(s,r,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",Ge.toString()),c.searchParams.set("fields",xt.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:y(r.token||s.token)}),m=g.body.issues.map(w=>Nt(w,a,e,o)),I=!1,f="";return p?(I=m.length==Ge,f=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,f=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:f}}},Sr=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=[...xt],l=a==null?void 0:a.Sprint;l&&u.push(l);let p=!o,d=p?qr:Er,c=new URL(`${Z(s,r,o)}${d}`);c.searchParams.set("jql",i.join(" AND ")),c.searchParams.set("maxResults",Ge.toString()),c.searchParams.set("fields",u.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:y(r.token||s.token)}),m=g.body.issues.map(w=>Nt(w,a,e,o)),I=!1,f="";return p?(I=m.length==Ge,f=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,f=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:f}}},Ne=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=t||{},c=[`project = "${l}"`,"statusCategory != Done"];return o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(g=>c.push(`labels = "${g}"`)),Sr(s,{resourceId:p,jql:c,cursor:u,fields:d},e,r)},_e=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=t||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),Sr(s,{resourceId:p,jql:g,fields:d,cursor:u},e,r)},Be=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...y(e.token||s.token),"Content-Type":"application/json"}})},Qe=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...y(e.token||s.token),"Content-Type":"application/json"}})},je=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...y(e.token||s.token),"Content-Type":"application/json"}})},Fe=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${Z(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:y(e.token||s.token)})).body}};var fe="https://api.atlassian.com/ex/jira",_t=100,pe=class extends W{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Oe(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){var i;let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),((i=this._resourceUrlCache[n])==null?void 0:i[e.resourceId])??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||fe}/${e.resourceId}/rest/api/2/myself`,headers:y(r.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:y(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||fe}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",_t.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:y(r.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,r={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await ar(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},r))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||fe}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",_t.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:y(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Te(p,a,!1))}}async getComponentsForJiraProject(e,r={}){return await Fe(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await ke(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Ne(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await _e(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await xe(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await je(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o==null?void 0:o.id};await this.config.request({method:"PUT",url:`${r.baseUrl||fe}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...y(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await Qe(this.config,e,r)}async setIssueLabels(e,r={}){await Be(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||fe}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",_t.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:y(r.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var de=class extends x{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=(e==null?void 0:e.baseUrl)||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await Oe(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/myself`,headers:y((e==null?void 0:e.token)||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/project`,headers:y((e==null?void 0:e.token)||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await ke(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Ne(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await _e(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await xe(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await je(this.config,e,r)}async setIssueLabels(e,r={}){await Be(this.config,e,r)}async setIssueComponents(e,r={}){await Qe(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:y(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await Fe(this.config,e,r)}};var z="https://api.trello.com",rn=1e3,sn=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),nn=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},ce=class extends W{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||z}/1/members/me?key=${t.appKey}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||z}/1/members/me/boards?fields=name&key=${t.appKey}&token=${e.token||this.config.token}&filter=open`,headers:y(e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||z}/1/boards/${n}/lists?key=${r}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||z}/1/members/${n}/?key=${r}&token=${e.token||this.config.token}`});return{data:sn(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||z}/1/boards/${n}/members?key=${r}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(c=>r.push(`label:"${c}"`));let p=`${i?`${i}`:""}${r.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||z}/1/search?key=${n}&query=${p}&cards_limit=${rn}&token=${e.token||this.config.token}&card_members=true`,headers:y(e.token||this.config.token)})).body.cards.map(c=>nn(c,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||z}/1/cards/${e.id}?key=${t}&token=${n.token||this.config.token}&${r}`,headers:y(n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:o}=t;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:o}=t,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(t,e={}){let{appKey:r,issue:n,labels:o}=t,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||z}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(i)}`,headers:y(e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(t,e={}){let{appKey:r,issue:n,archived:o}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||z}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&closed=${o}`,headers:y(e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||z}/1/boards/${n}/labels?key=${r}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var ze={};Q(ze,{default:()=>on});var on={};var Me={};Q(Me,{default:()=>an});var an={};var We={};Q(We,{restApiPullRequestToCommonPullRequest:()=>un});var un=s=>he(s);var nt={};Q(nt,{decode:()=>Bt,decodeV0:()=>cn,encode:()=>dn,validate:()=>pn});var O=(e=>(e.Zero="0",e.One="1",e))(O||{}),k=(e=>(e.PullRequest="pr",e.Issue="issue",e))(k||{}),T=(d=>(d.Azure="azure",d.AzureDevOpsServer="azureDevOpsServer",d.Github="github",d.GithubEnterprise="githubEnterprise",d.Gitlab="gitlab",d.GitlabSelfHosted="gitlabSelfHosted",d.Bitbucket="bitbucket",d.BitbucketServer="bitbucketServer",d.Jira="jira",d.JiraServer="jiraServer",d.Trello="trello",d))(T||{});var He=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var Je=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var Ve=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var Ke=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var Xe=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Ye=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Ze=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var et=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var tt=class{constructor(){}validate(t){if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.projectId||!t.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider=="jira"?(e.push(""),e.push(t.resourceId)):(e.push(t.domain),e.push("")),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:t[4]==""?null:t[4],accountOrOrgId:null,organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var rt=class{constructor(){}validate(t){if(!t.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.accountOrOrgId||!t.projectId||!t.entityId)throw new Error("Missing required fields for Trello issue uniqueId");let e=[];return e.push("trello"),e.push("issue"),e.push("1"),e.push(""),e.push(t.accountOrOrgId),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:t[4],organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var st=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new Je:new He;case"bitbucket":case"bitbucketServer":return t==="pr"?new Ke:new Ve;case"github":case"githubEnterprise":return t==="pr"?new Ye:new Xe;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new et:new Ze;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new tt;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new rt;default:throw new Error("unknown provider")}},ln=s=>{if(!s.entityType)throw new Error("entityType is required");if(!s.provider)throw new Error("provider is required");if(!s.entityId)throw new Error("entityID is required")},pn=s=>{if(s.version==="0"){ln(s);return}st(s.provider,s.entityType).validate(s)},dn=s=>st(s.provider,s.entityType).encode(s),Bt=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return st(t[0],t[1]).decode(t)},cn=(s,t,e)=>{if(!e)throw new Error("entityID is required");try{let r=JSON.parse(e);if(!r||!r.length)throw new Error("Invalid pull request uniqueId");let n=[s,t,"0",...r];return st(s,t).decode(n)}catch{return{provider:s,entityType:t,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var ot={};Q(ot,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>$r,CHANGES_REQUESTED_BUCKET_ID:()=>Ht,CONFLICTS_ACTION_CATEGORY:()=>Ur,CONFLICTS_BUCKET_ID:()=>Mt,DRAFT_ACTION_CATEGORY:()=>Or,DRAFT_BUCKET_ID:()=>Kt,FAILING_CI_ACTION_CATEGORY:()=>Ar,FAILING_CI_BUCKET_ID:()=>zt,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Lr,NEEDS_MY_REVIEW_BUCKET_ID:()=>Wt,OTHER_ACTION_CATEGORY:()=>kr,OTHER_BUCKET_ID:()=>Xt,PINNED_BUCKET_ID:()=>Qt,READY_TO_MERGE_ACTION_CATEGORY:()=>Cr,READY_TO_MERGE_BUCKET_ID:()=>jt,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>Gr,REVIEWER_COMMENTED_BUCKET_ID:()=>Jt,SNOOZED_BUCKET_ID:()=>Yt,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Dr,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Ft,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>Tr,WAITING_FOR_REVIEW_BUCKET_ID:()=>Vt,getActionablePullRequests:()=>xr,groupPullRequestsByAssignee:()=>hn,groupPullRequestsByAuthor:()=>fn,groupPullRequestsByGitKrakenTeam:()=>bn,groupPullRequestsByRepo:()=>mn,groupPullRequestsByReviewer:()=>In,groupPullRequestsByWorkspace:()=>yn,groupPullRequestsIntoBuckets:()=>gn});var _=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Qt="pinned",jt="readyToMerge",Ft="unassignedReviewers",zt="failingCI",Mt="conflicts",Wt="needsMyReview",Ht="changesRequested",Jt="reviewerCommented",Vt="waitingForReview",Kt="draft",Xt="other",Yt="snoozed",Cr="readyToMerge",Dr="unassignedReviewers",Ar="failingCI",Ur="conflicts",Lr="needsMyReview",$r="changesRequested",Gr="reviewerCommented",Tr="waitingForReview",Or="draft",kr="other",xr=(s,t,e)=>s.map(r=>{var u,l,p,d,c,g,m,I,f,w,h,R,E,D;let o={...r,...{suggestedActionCategory:kr,priority:1e3,viewer:{canMerge:!1,isAuthor:!1,isAssignee:!1,isReviewer:!1,shouldMerge:!1,shouldAssignReviewer:!1,waitingOnReviews:!1,shouldReview:!1},failingCI:!1,hasConflicts:!1,changeRequestReviewCount:0,codeSuggestionsCount:0,commentReviewCount:0,approvalReviewCount:0}};t&&(o.viewer.isAuthor=((u=r.author)==null?void 0:u.id)===t.id,o.viewer.isAssignee=((l=r.assignees)==null?void 0:l.some(S=>S.id===t.id))??!1,o.viewer.isReviewer=((p=r.reviews)==null?void 0:p.some(S=>S.reviewer.id===t.id))??!1),o.viewer.canMerge=((d=r.permissions)==null?void 0:d.canMerge)??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=((g=(c=r.headCommit)==null?void 0:c.buildStatuses)==null?void 0:g.some(S=>S.state==="ERROR"||S.state==="FAILED"))||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=((m=r.reviews)==null?void 0:m.filter(S=>S.state==="COMMENTED").length)??0,o.approvalReviewCount=((I=r.reviews)==null?void 0:I.filter(S=>S.state==="APPROVED").length)??0,o.changeRequestReviewCount=((f=r.reviews)==null?void 0:f.filter(S=>S.state==="CHANGES_REQUESTED").length)??0;let i=(w=e==null?void 0:e.enrichedItemsByUniqueId)==null?void 0:w[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(S=>S.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(S=>S.type==="snooze")&&(o.viewer.snoozed=!0));let a=((R=(h=e==null?void 0:e.codeSuggestionsCountByPrUuid)==null?void 0:h[r.uuid])==null?void 0:R.count)||0;return a&&(o.codeSuggestionsCount=a),(!t||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&r.mergeableState==="MERGEABLE"&&(!r.reviewDecision||r.reviewDecision==="APPROVED")&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=Cr),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=Or),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=Tr,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=Gr),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Ar),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=Ur),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=$r),(!t||o.viewer.isAuthor)&&!((E=r.reviews)!=null&&E.length)&&(o.suggestedActionCategory=Dr,o.viewer.shouldAssignReviewer=!0),t&&((D=r.reviews)!=null&&D.some(S=>S.reviewer.id===t.id&&S.state==="REVIEW_REQUESTED"))&&(o.suggestedActionCategory=Lr,o.viewer.shouldReview=!0),o}),gn=(s,t,e)=>{var i,a,u,l,p,d,c,g,m,I,f,w;let r={pinned:_(Qt,"Pinned","thumbtack",((i=e==null?void 0:e.bucketPriorityOverride)==null?void 0:i.pinned)??-1),readyToMerge:_(jt,"Ready to Merge","code-merge",((a=e==null?void 0:e.bucketPriorityOverride)==null?void 0:a.readyToMerge)??0),unassignedReviewers:_(Ft,"Unassigned Reviewers","user-plus",((u=e==null?void 0:e.bucketPriorityOverride)==null?void 0:u.unassignedReviewers)??1),failingCI:_(zt,"Failing CI","circle-x",((l=e==null?void 0:e.bucketPriorityOverride)==null?void 0:l.failingCI)??2),conflicts:_(Mt,"Resolve Conflicts","triangle-exclamation",((p=e==null?void 0:e.bucketPriorityOverride)==null?void 0:p.conflicts)??3),needsMyReview:_(Wt,"Needs My Review","eye",((d=e==null?void 0:e.bucketPriorityOverride)==null?void 0:d.needsMyReview)??4),changesRequested:_(Ht,"Suggested Changes","file-plus",((c=e==null?void 0:e.bucketPriorityOverride)==null?void 0:c.changesRequested)??5),reviewerCommented:_(Jt,"Reviewer Commented","comment",((g=e==null?void 0:e.bucketPriorityOverride)==null?void 0:g.reviewerCommented)??6),waitingForReview:_(Vt,"Waiting for Review","circle-pause",((m=e==null?void 0:e.bucketPriorityOverride)==null?void 0:m.waitingForReview)??7),draft:_(Kt,"Draft","compass-drafting",((I=e==null?void 0:e.bucketPriorityOverride)==null?void 0:I.draft)??8),other:_(Xt,"Other","ellipsis",((f=e==null?void 0:e.bucketPriorityOverride)==null?void 0:f.other)??9),snoozed:_(Yt,"Snoozed","snooze",((w=e==null?void 0:e.bucketPriorityOverride)==null?void 0:w.snoozed)??10)},o=xr(s,t,e).reduce((h,R)=>(h[R.uuid]=R,h),{});return s.forEach(h=>{let R=o[h.uuid],E=!0;if(R.viewer.snoozed){r[Yt].pullRequests.push(h);return}R.viewer.pinned&&r[Qt].pullRequests.push(h),(!t||R.viewer.isAuthor||R.viewer.isAssignee&&!R.viewer.isReviewer)&&!R.isDraft&&R.viewer.canMerge&&R.mergeableState==="MERGEABLE"&&(!h.reviewDecision||h.reviewDecision==="APPROVED")&&(r[jt].pullRequests.push(h),E=!1),R.viewer.shouldAssignReviewer&&(r[Ft].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.failingCI&&(r[zt].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.hasConflicts&&(r[Mt].pullRequests.push(h),E=!1),R.viewer.shouldReview&&(r[Wt].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&(R.reviewDecision==="CHANGES_REQUESTED"||R.codeSuggestionsCount>0)&&(r[Ht].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.reviewDecision==="COMMENTED"&&(r[Jt].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.reviewDecision==="REVIEW_REQUESTED"&&(r[Vt].pullRequests.push(h),E=!1),R.isDraft&&(r[Kt].pullRequests.push(h),E=!1),E&&r[Xt].pullRequests.push(h)}),Object.values(r).forEach(h=>{h.pullRequests.sort((R,E)=>o[R.uuid].priority-o[E.uuid].priority)}),r},mn=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),te(t)},hn=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Re(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),te(e)},fn=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Re(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),te(e)},In=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Re(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),te(e)},Rn=s=>{var t;return s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:((t=s.providerData)==null?void 0:t.repositories.nodes.map(e=>`${s.provider}-${e.repositoryId}`))??[]},yn=(s,t)=>{let e="internal-no-workspace",r={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(t.length){let n=t.reduce((o,i)=>(Rn(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Bt(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,p=u.reduce((d,c)=>n[c]?d.concat(n[c]):d,[]);p!=null&&p.length&&p.forEach(d=>{l=!0;let c=d.id;r[c]?r[c].pullRequests.push(o):r[c]={name:d.name,priority:0,pullRequests:[o],id:c,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return te(r)},bn=(s,t,e,r)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(i=>{var l,p,d;let a=!1,u=new Set;u.add((l=i.author)==null?void 0:l.id),(p=i.assignees)==null||p.forEach(c=>u.add(c.id)),(d=i.reviews)==null||d.forEach(c=>u.add(c.reviewer.id)),r.forEach(c=>{var m;if((m=c.members)==null?void 0:m.some(I=>{var w,h;let f=(h=(w=t[I.id])==null?void 0:w[e])==null?void 0:h.providerID;return f&&u.has(f)})){a=!0;let I=c.id;o[I]?o[I].pullRequests.push(i):o[I]={name:c.name,priority:0,pullRequests:[i],id:I,teamData:c}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,te(o)};var it={};Q(it,{getPullRequestRank:()=>Pn});var Pn=(s,t,e)=>{var i,a,u;let r=0,n,o;return(i=s.reviews)==null||i.forEach(l=>{l.reviewer.id===t&&(n=l.state),l.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":l.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),((a=s.author)==null?void 0:a.id)===t?r+=1e3:(u=s.assignees)!=null&&u.find(l=>l.id===t)?r+=900:n==="REVIEW_REQUESTED"?r+=800:e&&(r+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:o=="CHANGES_REQUESTED"&&(r+=70),r};var at={};Q(at,{default:()=>wn});var wn={};var ut={};Q(ut,{default:()=>vn});var vn={};var lt={};Q(lt,{default:()=>En});var En={};var Nr=s=>{let t={request:s==null?void 0:s.request};return{azureDevOps:new se({...t,...s==null?void 0:s.azureDevOps}),bitbucket:new ne({...t,...s==null?void 0:s.bitbucket}),bitbucketServer:new oe({...t,...s==null?void 0:s.bitbucketServer}),github:new ae({...t,...s==null?void 0:s.github}),gitlab:new le({...t,...s==null?void 0:s.gitlab}),jira:new pe({...t,...s==null?void 0:s.jira}),jiraServer:new de({...t,...s==null?void 0:s.jiraServer}),trello:new ce({...t,...s==null?void 0:s.trello})}};var _r=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(_r||{});var Br=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(Br||{});var qn=Nr;var Sn={azureDevOps:ze,bitbucket:Me,bitbucketServer:We,github:it,gitlab:at,gitProvider:ot,jira:ut,trello:lt,entityIdentifier:nt};
1124
+ `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:((l=(u=(a=i.body.data)==null?void 0:a.project)==null?void 0:u.labels)==null?void 0:l.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=(p=i.body.data)==null?void 0:p.project)==null?void 0:d.labels)==null?void 0:c.nodes)==null?void 0:g.map(kt))??[]}}async getTreeForRepo(t,e={}){let r=Y(t.repo),n=new URL(t.cursor??`${Le(this.config,e)}/projects/${encodeURIComponent(r)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",t.branch);let o=await this.config.request({url:n.toString(),headers:y(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(Js),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var Ys="https://api.atlassian.com/ex/jira",Te=100,Nt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Sr="/rest/api/2/search/jql",Cr="/rest/api/2/search",_t=(s,t,e,r)=>{var a,u,l,p;let n=s.fields.assignee,o=!r,i=(s.fields[(t==null?void 0:t.Sprint)??""]??[]).filter(d=>typeof d=="object");return{id:s.id,commentCount:s.fields.comment.comments.length,number:s.key,title:s.fields.summary,url:e?`${e}/browse/${s.key}`:null,closedDate:null,createdDate:new Date(s.fields.created),author:Oe(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[Oe(n,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:r??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:rn(s.fields.status),statusTransitions:((a=s.transitions)==null?void 0:a.map(Zs))??[],components:((u=s.fields.components)==null?void 0:u.map(en))??[],type:s.fields.issuetype.name,upvoteCount:((l=s.fields.votes)==null?void 0:l.votes)||0,labels:((p=s.fields.labels)==null?void 0:p.map(d=>({color:null,description:null,id:null,name:d})))??[],sprints:i.map(sn),fixVersions:s.fields.fixVersions.map(nn)}},Zs=s=>{let t;switch(s.to.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:t}}},en=s=>({description:s.description??null,id:s.id,name:s.name}),tn=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,Oe=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:tn(s,t,e)}),rn=s=>{let t;switch(s.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:t}},sn=s=>({id:s.id.toString(),name:s.name,isActive:s.state==="active",startDate:s.startDate?new Date(s.startDate):null,endDate:s.endDate?new Date(s.endDate):null,completedDate:s.completeDate?new Date(s.completeDate):null}),nn=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),Z=(s,t,e)=>e?`${t.baseUrl||Ys}/${e}`:`${(t==null?void 0:t.baseUrl)||s.baseUrl}`,ke=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${Z(s,e,r)}/rest/api/2/field`,headers:y(e.token||s.token)})).body},xe=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${Z(s,r,o)}/rest/api/2/issue/${n}?fields=${Nt.join(",")}&expand=transitions`,headers:y(r.token||s.token)});return{data:_t(a.body,i,e,o)}},Ne=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1125
+ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(w=>u.push(`labels = "${w}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?Cr:Sr,c=new URL(`${Z(s,r,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",Te.toString()),c.searchParams.set("fields",Nt.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:y(r.token||s.token)}),m=g.body.issues.map(w=>_t(w,a,e,o)),I=!1,f="";return p?(I=m.length==Te,f=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,f=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:f}}},Dr=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=[...Nt],l=a==null?void 0:a.Sprint;l&&u.push(l);let p=!o,d=p?Cr:Sr,c=new URL(`${Z(s,r,o)}${d}`);c.searchParams.set("jql",i.join(" AND ")),c.searchParams.set("maxResults",Te.toString()),c.searchParams.set("fields",u.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:y(r.token||s.token)}),m=g.body.issues.map(w=>_t(w,a,e,o)),I=!1,f="";return p?(I=m.length==Te,f=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,f=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:f}}},_e=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=t||{},c=[`project = "${l}"`,"statusCategory != Done"];return o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(g=>c.push(`labels = "${g}"`)),Dr(s,{resourceId:p,jql:c,cursor:u,fields:d},e,r)},Be=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=t||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),Dr(s,{resourceId:p,jql:g,fields:d,cursor:u},e,r)},Qe=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...y(e.token||s.token),"Content-Type":"application/json"}})},je=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...y(e.token||s.token),"Content-Type":"application/json"}})},Fe=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...y(e.token||s.token),"Content-Type":"application/json"}})},Me=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${Z(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:y(e.token||s.token)})).body}};var fe="https://api.atlassian.com/ex/jira",Bt=100,pe=class extends W{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await ke(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){var i;let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),((i=this._resourceUrlCache[n])==null?void 0:i[e.resourceId])??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||fe}/${e.resourceId}/rest/api/2/myself`,headers:y(r.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:y(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||fe}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Bt.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:y(r.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,r={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await ur(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},r))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||fe}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Bt.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:y(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Oe(p,a,!1))}}async getComponentsForJiraProject(e,r={}){return await Me(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await xe(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await _e(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Be(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Ne(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await Fe(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o==null?void 0:o.id};await this.config.request({method:"PUT",url:`${r.baseUrl||fe}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...y(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await je(this.config,e,r)}async setIssueLabels(e,r={}){await Qe(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||fe}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Bt.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:y(r.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var de=class extends x{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=(e==null?void 0:e.baseUrl)||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await ke(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/myself`,headers:y((e==null?void 0:e.token)||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/project`,headers:y((e==null?void 0:e.token)||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await xe(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await _e(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Be(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Ne(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await Fe(this.config,e,r)}async setIssueLabels(e,r={}){await Qe(this.config,e,r)}async setIssueComponents(e,r={}){await je(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:y(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await Me(this.config,e,r)}};var M="https://api.trello.com",on=1e3,an=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),un=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},ce=class extends W{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||M}/1/members/me?key=${t.appKey}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||M}/1/members/me/boards?fields=name&key=${t.appKey}&token=${e.token||this.config.token}&filter=open`,headers:y(e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${n}/lists?key=${r}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||M}/1/members/${n}/?key=${r}&token=${e.token||this.config.token}`});return{data:an(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${n}/members?key=${r}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(c=>r.push(`label:"${c}"`));let p=`${i?`${i}`:""}${r.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/search?key=${n}&query=${p}&cards_limit=${on}&token=${e.token||this.config.token}&card_members=true`,headers:y(e.token||this.config.token)})).body.cards.map(c=>un(c,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||M}/1/cards/${e.id}?key=${t}&token=${n.token||this.config.token}&${r}`,headers:y(n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:o}=t;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:o}=t,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(t,e={}){let{appKey:r,issue:n,labels:o}=t,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(i)}`,headers:y(e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(t,e={}){let{appKey:r,issue:n,archived:o}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&closed=${o}`,headers:y(e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${n}/labels?key=${r}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var ze={};Q(ze,{default:()=>ln});var ln={};var We={};Q(We,{default:()=>pn});var pn={};var nt={};Q(nt,{decode:()=>Qt,decodeV0:()=>mn,encode:()=>gn,validate:()=>cn});var O=(e=>(e.Zero="0",e.One="1",e))(O||{}),k=(e=>(e.PullRequest="pr",e.Issue="issue",e))(k||{}),T=(d=>(d.Azure="azure",d.AzureDevOpsServer="azureDevOpsServer",d.Github="github",d.GithubEnterprise="githubEnterprise",d.Gitlab="gitlab",d.GitlabSelfHosted="gitlabSelfHosted",d.Bitbucket="bitbucket",d.BitbucketServer="bitbucketServer",d.Jira="jira",d.JiraServer="jiraServer",d.Trello="trello",d))(T||{});var He=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var Je=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var Ve=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var Ke=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var Xe=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Ye=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Ze=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var et=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var tt=class{constructor(){}validate(t){if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.projectId||!t.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider=="jira"?(e.push(""),e.push(t.resourceId)):(e.push(t.domain),e.push("")),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:t[4]==""?null:t[4],accountOrOrgId:null,organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var rt=class{constructor(){}validate(t){if(!t.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.accountOrOrgId||!t.projectId||!t.entityId)throw new Error("Missing required fields for Trello issue uniqueId");let e=[];return e.push("trello"),e.push("issue"),e.push("1"),e.push(""),e.push(t.accountOrOrgId),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:t[4],organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var st=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new Je:new He;case"bitbucket":case"bitbucketServer":return t==="pr"?new Ke:new Ve;case"github":case"githubEnterprise":return t==="pr"?new Ye:new Xe;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new et:new Ze;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new tt;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new rt;default:throw new Error("unknown provider")}},dn=s=>{if(!s.entityType)throw new Error("entityType is required");if(!s.provider)throw new Error("provider is required");if(!s.entityId)throw new Error("entityID is required")},cn=s=>{if(s.version==="0"){dn(s);return}st(s.provider,s.entityType).validate(s)},gn=s=>st(s.provider,s.entityType).encode(s),Qt=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return st(t[0],t[1]).decode(t)},mn=(s,t,e)=>{if(!e)throw new Error("entityID is required");try{let r=JSON.parse(e);if(!r||!r.length)throw new Error("Invalid pull request uniqueId");let n=[s,t,"0",...r];return st(s,t).decode(n)}catch{return{provider:s,entityType:t,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var ot={};Q(ot,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>Tr,CHANGES_REQUESTED_BUCKET_ID:()=>Jt,CONFLICTS_ACTION_CATEGORY:()=>$r,CONFLICTS_BUCKET_ID:()=>Wt,DRAFT_ACTION_CATEGORY:()=>xr,DRAFT_BUCKET_ID:()=>Xt,FAILING_CI_ACTION_CATEGORY:()=>Lr,FAILING_CI_BUCKET_ID:()=>zt,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Gr,NEEDS_MY_REVIEW_BUCKET_ID:()=>Ht,OTHER_ACTION_CATEGORY:()=>Nr,OTHER_BUCKET_ID:()=>Yt,PINNED_BUCKET_ID:()=>jt,READY_TO_MERGE_ACTION_CATEGORY:()=>Ar,READY_TO_MERGE_BUCKET_ID:()=>Ft,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>Or,REVIEWER_COMMENTED_BUCKET_ID:()=>Vt,SNOOZED_BUCKET_ID:()=>Zt,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Ur,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Mt,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>kr,WAITING_FOR_REVIEW_BUCKET_ID:()=>Kt,getActionablePullRequests:()=>_r,groupPullRequestsByAssignee:()=>In,groupPullRequestsByAuthor:()=>Rn,groupPullRequestsByGitKrakenTeam:()=>wn,groupPullRequestsByRepo:()=>fn,groupPullRequestsByReviewer:()=>yn,groupPullRequestsByWorkspace:()=>Pn,groupPullRequestsIntoBuckets:()=>hn});var _=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),jt="pinned",Ft="readyToMerge",Mt="unassignedReviewers",zt="failingCI",Wt="conflicts",Ht="needsMyReview",Jt="changesRequested",Vt="reviewerCommented",Kt="waitingForReview",Xt="draft",Yt="other",Zt="snoozed",Ar="readyToMerge",Ur="unassignedReviewers",Lr="failingCI",$r="conflicts",Gr="needsMyReview",Tr="changesRequested",Or="reviewerCommented",kr="waitingForReview",xr="draft",Nr="other",_r=(s,t,e)=>s.map(r=>{var u,l,p,d,c,g,m,I,f,w,h,R,E,D;let o={...r,...{suggestedActionCategory:Nr,priority:1e3,viewer:{canMerge:!1,isAuthor:!1,isAssignee:!1,isReviewer:!1,shouldMerge:!1,shouldAssignReviewer:!1,waitingOnReviews:!1,shouldReview:!1},failingCI:!1,hasConflicts:!1,changeRequestReviewCount:0,codeSuggestionsCount:0,commentReviewCount:0,approvalReviewCount:0}};t&&(o.viewer.isAuthor=((u=r.author)==null?void 0:u.id)===t.id,o.viewer.isAssignee=((l=r.assignees)==null?void 0:l.some(S=>S.id===t.id))??!1,o.viewer.isReviewer=((p=r.reviews)==null?void 0:p.some(S=>S.reviewer.id===t.id))??!1),o.viewer.canMerge=((d=r.permissions)==null?void 0:d.canMerge)??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=((g=(c=r.headCommit)==null?void 0:c.buildStatuses)==null?void 0:g.some(S=>S.state==="ERROR"||S.state==="FAILED"))||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=((m=r.reviews)==null?void 0:m.filter(S=>S.state==="COMMENTED").length)??0,o.approvalReviewCount=((I=r.reviews)==null?void 0:I.filter(S=>S.state==="APPROVED").length)??0,o.changeRequestReviewCount=((f=r.reviews)==null?void 0:f.filter(S=>S.state==="CHANGES_REQUESTED").length)??0;let i=(w=e==null?void 0:e.enrichedItemsByUniqueId)==null?void 0:w[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(S=>S.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(S=>S.type==="snooze")&&(o.viewer.snoozed=!0));let a=((R=(h=e==null?void 0:e.codeSuggestionsCountByPrUuid)==null?void 0:h[r.uuid])==null?void 0:R.count)||0;return a&&(o.codeSuggestionsCount=a),(!t||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&r.mergeableState==="MERGEABLE"&&(!r.reviewDecision||r.reviewDecision==="APPROVED")&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=Ar),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=xr),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=kr,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=Or),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Lr),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=$r),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=Tr),(!t||o.viewer.isAuthor)&&!((E=r.reviews)!=null&&E.length)&&(o.suggestedActionCategory=Ur,o.viewer.shouldAssignReviewer=!0),t&&((D=r.reviews)!=null&&D.some(S=>S.reviewer.id===t.id&&S.state==="REVIEW_REQUESTED"))&&(o.suggestedActionCategory=Gr,o.viewer.shouldReview=!0),o}),hn=(s,t,e)=>{var i,a,u,l,p,d,c,g,m,I,f,w;let r={pinned:_(jt,"Pinned","thumbtack",((i=e==null?void 0:e.bucketPriorityOverride)==null?void 0:i.pinned)??-1),readyToMerge:_(Ft,"Ready to Merge","code-merge",((a=e==null?void 0:e.bucketPriorityOverride)==null?void 0:a.readyToMerge)??0),unassignedReviewers:_(Mt,"Unassigned Reviewers","user-plus",((u=e==null?void 0:e.bucketPriorityOverride)==null?void 0:u.unassignedReviewers)??1),failingCI:_(zt,"Failing CI","circle-x",((l=e==null?void 0:e.bucketPriorityOverride)==null?void 0:l.failingCI)??2),conflicts:_(Wt,"Resolve Conflicts","triangle-exclamation",((p=e==null?void 0:e.bucketPriorityOverride)==null?void 0:p.conflicts)??3),needsMyReview:_(Ht,"Needs My Review","eye",((d=e==null?void 0:e.bucketPriorityOverride)==null?void 0:d.needsMyReview)??4),changesRequested:_(Jt,"Suggested Changes","file-plus",((c=e==null?void 0:e.bucketPriorityOverride)==null?void 0:c.changesRequested)??5),reviewerCommented:_(Vt,"Reviewer Commented","comment",((g=e==null?void 0:e.bucketPriorityOverride)==null?void 0:g.reviewerCommented)??6),waitingForReview:_(Kt,"Waiting for Review","circle-pause",((m=e==null?void 0:e.bucketPriorityOverride)==null?void 0:m.waitingForReview)??7),draft:_(Xt,"Draft","compass-drafting",((I=e==null?void 0:e.bucketPriorityOverride)==null?void 0:I.draft)??8),other:_(Yt,"Other","ellipsis",((f=e==null?void 0:e.bucketPriorityOverride)==null?void 0:f.other)??9),snoozed:_(Zt,"Snoozed","snooze",((w=e==null?void 0:e.bucketPriorityOverride)==null?void 0:w.snoozed)??10)},o=_r(s,t,e).reduce((h,R)=>(h[R.uuid]=R,h),{});return s.forEach(h=>{let R=o[h.uuid],E=!0;if(R.viewer.snoozed){r[Zt].pullRequests.push(h);return}R.viewer.pinned&&r[jt].pullRequests.push(h),(!t||R.viewer.isAuthor||R.viewer.isAssignee&&!R.viewer.isReviewer)&&!R.isDraft&&R.viewer.canMerge&&R.mergeableState==="MERGEABLE"&&(!h.reviewDecision||h.reviewDecision==="APPROVED")&&(r[Ft].pullRequests.push(h),E=!1),R.viewer.shouldAssignReviewer&&(r[Mt].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.failingCI&&(r[zt].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.hasConflicts&&(r[Wt].pullRequests.push(h),E=!1),R.viewer.shouldReview&&(r[Ht].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&(R.reviewDecision==="CHANGES_REQUESTED"||R.codeSuggestionsCount>0)&&(r[Jt].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.reviewDecision==="COMMENTED"&&(r[Vt].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.reviewDecision==="REVIEW_REQUESTED"&&(r[Kt].pullRequests.push(h),E=!1),R.isDraft&&(r[Xt].pullRequests.push(h),E=!1),E&&r[Yt].pullRequests.push(h)}),Object.values(r).forEach(h=>{h.pullRequests.sort((R,E)=>o[R.uuid].priority-o[E.uuid].priority)}),r},fn=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),te(t)},In=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Re(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),te(e)},Rn=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Re(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),te(e)},yn=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Re(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),te(e)},bn=s=>{var t;return s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:((t=s.providerData)==null?void 0:t.repositories.nodes.map(e=>`${s.provider}-${e.repositoryId}`))??[]},Pn=(s,t)=>{let e="internal-no-workspace",r={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(t.length){let n=t.reduce((o,i)=>(bn(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Qt(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,p=u.reduce((d,c)=>n[c]?d.concat(n[c]):d,[]);p!=null&&p.length&&p.forEach(d=>{l=!0;let c=d.id;r[c]?r[c].pullRequests.push(o):r[c]={name:d.name,priority:0,pullRequests:[o],id:c,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return te(r)},wn=(s,t,e,r)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(i=>{var l,p,d;let a=!1,u=new Set;u.add((l=i.author)==null?void 0:l.id),(p=i.assignees)==null||p.forEach(c=>u.add(c.id)),(d=i.reviews)==null||d.forEach(c=>u.add(c.reviewer.id)),r.forEach(c=>{var m;if((m=c.members)==null?void 0:m.some(I=>{var w,h;let f=(h=(w=t[I.id])==null?void 0:w[e])==null?void 0:h.providerID;return f&&u.has(f)})){a=!0;let I=c.id;o[I]?o[I].pullRequests.push(i):o[I]={name:c.name,priority:0,pullRequests:[i],id:I,teamData:c}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,te(o)};var it={};Q(it,{getPullRequestRank:()=>vn});var vn=(s,t,e)=>{var i,a,u;let r=0,n,o;return(i=s.reviews)==null||i.forEach(l=>{l.reviewer.id===t&&(n=l.state),l.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":l.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),((a=s.author)==null?void 0:a.id)===t?r+=1e3:(u=s.assignees)!=null&&u.find(l=>l.id===t)?r+=900:n==="REVIEW_REQUESTED"?r+=800:e&&(r+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:o=="CHANGES_REQUESTED"&&(r+=70),r};var at={};Q(at,{default:()=>En});var En={};var ut={};Q(ut,{default:()=>qn});var qn={};var lt={};Q(lt,{default:()=>Sn});var Sn={};var Br=s=>{let t={request:s==null?void 0:s.request};return{azureDevOps:new se({...t,...s==null?void 0:s.azureDevOps}),bitbucket:new ne({...t,...s==null?void 0:s.bitbucket}),bitbucketServer:new oe({...t,...s==null?void 0:s.bitbucketServer}),github:new ae({...t,...s==null?void 0:s.github}),gitlab:new le({...t,...s==null?void 0:s.gitlab}),jira:new pe({...t,...s==null?void 0:s.jira}),jiraServer:new de({...t,...s==null?void 0:s.jiraServer}),trello:new ce({...t,...s==null?void 0:s.trello})}};var Qr=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(Qr||{});var jr=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(jr||{});var Cn=Br;var Dn={azureDevOps:ze,bitbucket:We,bitbucketServer:ve,github:it,gitlab:at,gitProvider:ot,jira:ut,trello:lt,entityIdentifier:nt};