@gitkraken/provider-apis 0.27.3 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Tr=Object.create;var me=Object.defineProperty;var Or=Object.getOwnPropertyDescriptor;var kr=Object.getOwnPropertyNames;var xr=Object.getPrototypeOf,Nr=Object.prototype.hasOwnProperty;var B=(s,t)=>{for(var e in t)me(s,e,{get:t[e],enumerable:!0})},Ht=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of kr(t))!Nr.call(s,n)&&n!==e&&me(s,n,{get:()=>t[n],enumerable:!(r=Or(t,n))||r.enumerable});return s};var _r=(s,t,e)=>(e=s!=null?Tr(xr(s)):{},Ht(t||!s||!s.__esModule?me(e,"default",{value:s,enumerable:!0}):e,s)),Br=s=>Ht(me({},"__esModule",{value:!0}),s);var In={};B(In,{AzureDevOps:()=>te,AzureDevopsUtils:()=>Qe,Bitbucket:()=>re,BitbucketServer:()=>se,BitbucketServerUtils:()=>Fe,BitbucketUtils:()=>je,EntityIdentifierProviderType:()=>$,EntityIdentifierUtils:()=>tt,EntityType:()=>O,EntityVersion:()=>T,GitBuildStatusStage:()=>Jt,GitBuildStatusState:()=>de,GitDiffLineType:()=>at,GitHub:()=>oe,GitHubIssueCloseReason:()=>Gr,GitHubUtils:()=>st,GitIssueState:()=>ye,GitLab:()=>ae,GitLabUtils:()=>nt,GitMergeStrategy:()=>ee,GitProviderUtils:()=>rt,GitPullRequestMergeableState:()=>M,GitPullRequestReviewState:()=>F,GitPullRequestState:()=>Y,GraphQLErrors:()=>b,Jira:()=>ue,JiraServer:()=>le,JiraUtils:()=>ot,PullRequestAsyncStatus:()=>$r,Trello:()=>pe,TrelloUtils:()=>it,Utils:()=>fn,default:()=>hn,isFetch:()=>fe});module.exports=Br(In);var Jt=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(Jt||{}),de=(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))(de||{}),ee=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ee||{}),Y=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(Y||{}),F=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(F||{}),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||{}),at=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(at||{});var Vt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},J=s=>!s||s.length===0?null:s.reduce((t,e)=>Vt[e.state]>Vt[t]?e.state:t,"APPROVED"),he=(s,t)=>s.name||s.username||s.email||t,Z=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 D=100;var Kt=_r(require("node-fetch")),Xt=globalThis.fetch||Kt.default;var Qr=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},ut=s=>async({url:t,...e})=>{let r=await s(t,e);return Qr(r)};var fe=(s,t=!1)=>s.name==="fetch"||t;var N=class{constructor(t){let e=(t==null?void 0:t.request)||Xt;this.config={...t,request:fe(e,t==null?void 0:t.forceIsFetch)?ut(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&fe(t.request,(t==null?void 0:t.forceIsFetch)??this.config.forceIsFetch)?ut(t.request):this.config.request}}},Q=class extends N{};var y=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},Yt=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,V=(s,t,e)=>!s||t.some(r=>s[r])?e:"",Zt=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 E=(s,t={})=>y(t.token||s.token,t.isPAT||s.isPAT),er=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/");var tr="https://app.vssps.visualstudio.com/_apis",C="https://dev.azure.com",jr={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Fr={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},lt=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Re=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Mr=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"}},Ie=(s,t)=>{var n;let e=[],r=[];return t.reviewers.forEach(o=>{let i={reviewer:lt(o),state:Fr[o.vote??0]||"REVIEW_REQUESTED"};o.isRequired&&e.push(i),r.push(i)}),{id:t.pullRequestId.toString(),title:t.title,number:t.codeReviewId,state:jr[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:lt(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:Re(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Re(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:er(t),assignees:t.reviewers.map(lt),reviews:r,reviewDecision:J(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:Mr(t.mergeStatus),labels:((n=t.labels)==null?void 0:n.map(o=>({color:null,description:null,id:o.id,name:o.name})))??[],permissions:null}},rr=(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:Re(t.defaultBranch)}:null,permissions:null}),zr=(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(f=>({color:null,description:null,id:null,name:f.trim()})))??[]}},te=class extends N{async getCurrentUser(t={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=await this.config.request({url:`${tr}/profile/profiles/me`,headers:E(this.config,e)});return{data:{id:r.body.id,name:r.body.displayName,username:r.body.displayName,email:r.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(t,e={}){let n=(await this.config.request({url:`${C}/${encodeURIComponent(t.namespace)}/_apis/ConnectionData`,headers:E(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}}}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}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/commits/${t.oid}`,headers:E(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(t,e={}){return{data:(await this.config.request({url:`${tr}/accounts?memberId=${t.userId}&api-version=6.0`,headers:E(this.config,e)})).body.value.map(n=>({id:n.accountId,name:n.accountName}))}}async getAzureProjects(t,e={}){let r=new URL(`${C}/${encodeURIComponent(t.namespace)}/_apis/projects`);r.searchParams.set("$top",D.toString()),t.cursor&&r.searchParams.set("$skip",t.cursor);let n=await this.config.request({url:r.toString(),headers:E(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:`https://vssps.dev.azure.com/${encodeURIComponent(r)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:E(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(t,e={}){let{namespace:r,projectScopeDescriptor:n,cursor:o}=t,i=new URL(`https://vssps.dev.azure.com/${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:E(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:E(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}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`,headers:E(this.config,e)});return{data:rr(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}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories`,headers:E(this.config,e)})).body.value.map(n=>rr(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}/${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",D.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:E(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:Re(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:`${e.baseUrl||C}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${r}&%24skip=${(u-1)*r}`,headers:E(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=>Ie(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(Ie(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}=t,l=i||1,p=new URL(`${e.baseUrl||C}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return p.searchParams.set("searchCriteria.status","1"),p.searchParams.set("$top",r.toString()),p.searchParams.set("$skip",((l-1)*r).toString()),a&&a.length&&p.searchParams.set("searchCriteria.reviewerId",a[0]),u&&p.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:p.toString(),headers:E(this.config,e)})}async getPullRequestsForProject(t,e={}){let n=t.page||1,o=await this.getPullRequestsForProjectBase(t,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:n+1},data:o.body.value.map(i=>Ie(t.namespace,i))}}async getPullRequestsForProjects(t,e={}){let{projects:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(await this.getPullRequestsForProjectBase({...o,...t},e)).body.value.forEach(a=>{n.push(Ie(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:`${e.baseUrl||C}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...E(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:`${r.baseUrl||C}/${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:{...E(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:`${e.baseUrl||C}/${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:{...E(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:`${e.baseUrl||C}/${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:{...E(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:`${e.baseUrl||C}/${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:{...E(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:`${e.baseUrl||C}/${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:{...E(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(I=>d.push(`[System.Tags] Contains '${I}'`));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:`${e.baseUrl||C}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...E(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(I=>I.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let f=await this.config.request({url:`${e.baseUrl||C}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...E(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:f.body.value.map(I=>zr(t.namespace,t.project,I,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:`${e.baseUrl||C}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.1`,body:JSON.stringify(a),headers:{...E(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,f=o[d.permissions];for(let I of f)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][I]=!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:`${r.baseUrl||C}/${encodeURIComponent(t.project.namespace)}/${encodeURIComponent(t.project.name)}/_apis/wit/workitems/${t.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...E(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:`${e.baseUrl||C}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...E(this.config,e)}})).body.value}}async getLabelsForProject(t,e={}){let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||C}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...E(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}};var A=(s,t={})=>y(t.token||s.token,t.isPAT||s.isPAT);var U="https://api.bitbucket.org/2.0",Wr={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},dt=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}),sr=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}},pt=s=>{let t=s.id;return{id:t.toString(),title:s.title,number:t,state:Wr[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:dt(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:null},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:null,reviewDecision:null,additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:null,mergeableState:"UNKNOWN",permissions:null}},Hr=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}}},re=class extends N{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:`${U}/user`,headers:A(this.config,e)});return{data:dt(r.body)}}async getUserForCommit(t,e={}){var i;let n=(await this.config.request({url:`${U}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:A(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:`${U}/repositories/${t.namespace}/${t.name}`,headers:A(this.config,e)});return{data:sr(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(`${U}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",D.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:A(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(sr)}}async getBranches(t,e={}){var i;let r=new URL(`${U}/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",D.toString());let n=await this.config.request({url:r.toString(),headers:A(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(`${U}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",D.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:A(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(`${U}/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:A(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(`${U}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);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:A(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(pt)}}async getPullRequestsForRepoBase(t,e={}){var n;let r=new URL(`${U}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests?state=OPEN`);return r.searchParams.set("page",((n=t.page)==null?void 0:n.toString())||"1"),r.searchParams.set("pagelen","50"),await this.config.request({url:r.toString(),headers:A(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.uuid!==t.authorLogin)return null;r.push(pt(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=>{if(t.authorLogin&&i.author.uuid!==t.authorLogin)return null;r.push(pt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){var i;let r=new URL(`${U}/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:A(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>dt(a.user))}}async getReposPermissionsForCurrentUser(t,e={}){var i;let r=new URL(`${U}/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:A(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]:Hr(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:`${U}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:A(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:`${U}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...A(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:`${U}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...A(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var ct=s=>({name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??null,id:s.id.toString(),username:s.name,url:s.links.self[0].href}),ce=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:ct(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:ct(s.author.user),assignees:null,reviews:r,reviewDecision:J(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:"UNKNOWN",permissions:null,version:s.version}},nr=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}},se=class extends Q{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:ct(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:nr(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(nr)}}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(ce(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(ce(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(ce)}}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 dr=require("js-base64");var ye=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ye||{});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 Jr={AS_CODE_OWNER:[3,0,0],CHECK_RUN:[3,0,0],LATEST_REVIEWS:[3,0,0],VIEWER_CAN_MERGE_AS_ADMIN:[3,5,0]},or=15,ir=100,L=s=>!!s,be=(s,t)=>{let e=Jr[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Pe="https://api.github.com",Vr=`${Pe}/graphql`,ve=`
1
+ "use strict";var Tr=Object.create;var he=Object.defineProperty;var Or=Object.getOwnPropertyDescriptor;var kr=Object.getOwnPropertyNames;var xr=Object.getPrototypeOf,Nr=Object.prototype.hasOwnProperty;var B=(s,t)=>{for(var e in t)he(s,e,{get:t[e],enumerable:!0})},Ht=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of kr(t))!Nr.call(s,n)&&n!==e&&he(s,n,{get:()=>t[n],enumerable:!(r=Or(t,n))||r.enumerable});return s};var _r=(s,t,e)=>(e=s!=null?Tr(xr(s)):{},Ht(t||!s||!s.__esModule?he(e,"default",{value:s,enumerable:!0}):e,s)),Br=s=>Ht(he({},"__esModule",{value:!0}),s);var In={};B(In,{AzureDevOps:()=>te,AzureDevopsUtils:()=>Qe,Bitbucket:()=>re,BitbucketServer:()=>se,BitbucketServerUtils:()=>Fe,BitbucketUtils:()=>je,EntityIdentifierProviderType:()=>$,EntityIdentifierUtils:()=>tt,EntityType:()=>O,EntityVersion:()=>T,GitBuildStatusStage:()=>Jt,GitBuildStatusState:()=>ce,GitDiffLineType:()=>at,GitHub:()=>ie,GitHubIssueCloseReason:()=>Gr,GitHubUtils:()=>st,GitIssueState:()=>be,GitLab:()=>ue,GitLabUtils:()=>nt,GitMergeStrategy:()=>ee,GitProviderUtils:()=>rt,GitPullRequestMergeableState:()=>M,GitPullRequestReviewState:()=>F,GitPullRequestState:()=>Y,GraphQLErrors:()=>b,Jira:()=>le,JiraServer:()=>pe,JiraUtils:()=>ot,PullRequestAsyncStatus:()=>$r,Trello:()=>de,TrelloUtils:()=>it,Utils:()=>fn,default:()=>hn,isFetch:()=>Ie});module.exports=Br(In);var Jt=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(Jt||{}),ce=(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))(ce||{}),ee=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ee||{}),Y=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(Y||{}),F=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(F||{}),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||{}),at=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(at||{});var Vt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},J=s=>!s||s.length===0?null:s.reduce((t,e)=>Vt[e.state]>Vt[t]?e.state:t,"APPROVED"),fe=(s,t)=>s.name||s.username||s.email||t,Z=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 D=100;var Kt=_r(require("node-fetch")),Xt=globalThis.fetch||Kt.default;var Qr=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},ut=s=>async({url:t,...e})=>{let r=await s(t,e);return Qr(r)};var Ie=(s,t=!1)=>s.name==="fetch"||t;var N=class{constructor(t){let e=(t==null?void 0:t.request)||Xt;this.config={...t,request:Ie(e,t==null?void 0:t.forceIsFetch)?ut(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&Ie(t.request,(t==null?void 0:t.forceIsFetch)??this.config.forceIsFetch)?ut(t.request):this.config.request}}},Q=class extends N{};var y=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},Yt=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,V=(s,t,e)=>!s||t.some(r=>s[r])?e:"",Zt=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 E=(s,t={})=>y(t.token||s.token,t.isPAT||s.isPAT),er=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/");var tr="https://app.vssps.visualstudio.com/_apis",C="https://dev.azure.com",jr={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Fr={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},lt=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),ye=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Mr=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"}},Re=(s,t)=>{var n;let e=[],r=[];return t.reviewers.forEach(o=>{let i={reviewer:lt(o),state:Fr[o.vote??0]||"REVIEW_REQUESTED"};o.isRequired&&e.push(i),r.push(i)}),{id:t.pullRequestId.toString(),title:t.title,number:t.codeReviewId,state:jr[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:lt(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:ye(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:ye(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:er(t),assignees:t.reviewers.map(lt),reviews:r,reviewDecision:J(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:Mr(t.mergeStatus),labels:((n=t.labels)==null?void 0:n.map(o=>({color:null,description:null,id:o.id,name:o.name})))??[],permissions:null}},rr=(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:ye(t.defaultBranch)}:null,permissions:null}),zr=(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(f=>({color:null,description:null,id:null,name:f.trim()})))??[]}},te=class extends N{async getCurrentUser(t={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=await this.config.request({url:`${tr}/profile/profiles/me`,headers:E(this.config,e)});return{data:{id:r.body.id,name:r.body.displayName,username:r.body.displayName,email:r.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(t,e={}){let n=(await this.config.request({url:`${C}/${encodeURIComponent(t.namespace)}/_apis/ConnectionData`,headers:E(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}}}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}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/commits/${t.oid}`,headers:E(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(t,e={}){return{data:(await this.config.request({url:`${tr}/accounts?memberId=${t.userId}&api-version=6.0`,headers:E(this.config,e)})).body.value.map(n=>({id:n.accountId,name:n.accountName}))}}async getAzureProjects(t,e={}){let r=new URL(`${C}/${encodeURIComponent(t.namespace)}/_apis/projects`);r.searchParams.set("$top",D.toString()),t.cursor&&r.searchParams.set("$skip",t.cursor);let n=await this.config.request({url:r.toString(),headers:E(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:`https://vssps.dev.azure.com/${encodeURIComponent(r)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:E(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(t,e={}){let{namespace:r,projectScopeDescriptor:n,cursor:o}=t,i=new URL(`https://vssps.dev.azure.com/${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:E(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:E(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}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`,headers:E(this.config,e)});return{data:rr(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}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories`,headers:E(this.config,e)})).body.value.map(n=>rr(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}/${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",D.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:E(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:ye(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:`${e.baseUrl||C}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${r}&%24skip=${(u-1)*r}`,headers:E(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=>Re(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(Re(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}=t,l=i||1,p=new URL(`${e.baseUrl||C}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return p.searchParams.set("searchCriteria.status","1"),p.searchParams.set("$top",r.toString()),p.searchParams.set("$skip",((l-1)*r).toString()),a&&a.length&&p.searchParams.set("searchCriteria.reviewerId",a[0]),u&&p.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:p.toString(),headers:E(this.config,e)})}async getPullRequestsForProject(t,e={}){let n=t.page||1,o=await this.getPullRequestsForProjectBase(t,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:n+1},data:o.body.value.map(i=>Re(t.namespace,i))}}async getPullRequestsForProjects(t,e={}){let{projects:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(await this.getPullRequestsForProjectBase({...o,...t},e)).body.value.forEach(a=>{n.push(Re(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:`${e.baseUrl||C}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...E(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:`${r.baseUrl||C}/${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:{...E(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:`${e.baseUrl||C}/${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:{...E(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:`${e.baseUrl||C}/${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:{...E(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:`${e.baseUrl||C}/${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:{...E(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:`${e.baseUrl||C}/${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:{...E(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(I=>d.push(`[System.Tags] Contains '${I}'`));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:`${e.baseUrl||C}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...E(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(I=>I.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let f=await this.config.request({url:`${e.baseUrl||C}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...E(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:f.body.value.map(I=>zr(t.namespace,t.project,I,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:`${e.baseUrl||C}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.1`,body:JSON.stringify(a),headers:{...E(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,f=o[d.permissions];for(let I of f)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][I]=!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:`${r.baseUrl||C}/${encodeURIComponent(t.project.namespace)}/${encodeURIComponent(t.project.name)}/_apis/wit/workitems/${t.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...E(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:`${e.baseUrl||C}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...E(this.config,e)}})).body.value}}async getLabelsForProject(t,e={}){let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||C}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...E(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}};var U=(s,t={})=>y(t.token||s.token,t.isPAT||s.isPAT);var A="https://api.bitbucket.org/2.0",Wr={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},dt=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}),sr=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}},pt=s=>{let t=s.id;return{id:t.toString(),title:s.title,number:t,state:Wr[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:dt(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:null},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:null,reviewDecision:null,additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:null,mergeableState:"UNKNOWN",permissions:null}},Hr=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}}},re=class extends N{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:`${A}/user`,headers:U(this.config,e)});return{data:dt(r.body)}}async getUserForCommit(t,e={}){var i;let n=(await this.config.request({url:`${A}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:U(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:`${A}/repositories/${t.namespace}/${t.name}`,headers:U(this.config,e)});return{data:sr(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(`${A}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",D.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:U(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(sr)}}async getBranches(t,e={}){var i;let r=new URL(`${A}/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",D.toString());let n=await this.config.request({url:r.toString(),headers:U(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(`${A}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",D.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:U(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(`${A}/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:U(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(`${A}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);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:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(pt)}}async getPullRequestsForRepoBase(t,e={}){var n;let r=new URL(`${A}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests?state=OPEN`);return r.searchParams.set("page",((n=t.page)==null?void 0:n.toString())||"1"),r.searchParams.set("pagelen","50"),await this.config.request({url:r.toString(),headers:U(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.uuid!==t.authorLogin)return null;r.push(pt(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=>{if(t.authorLogin&&i.author.uuid!==t.authorLogin)return null;r.push(pt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){var i;let r=new URL(`${A}/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:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(a=>dt(a.user))}}async getReposPermissionsForCurrentUser(t,e={}){var i;let r=new URL(`${A}/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:U(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]:Hr(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:`${A}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:U(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:`${A}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...U(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:`${A}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...U(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var ct=s=>({name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??null,id:s.id.toString(),username:s.name,url:s.links.self[0].href}),ge=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:ct(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:ct(s.author.user),assignees:null,reviews:r,reviewDecision:J(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:"UNKNOWN",permissions:null,version:s.version}},nr=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}},se=class extends Q{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:ct(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:nr(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(nr)}}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(ge(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(ge(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(ge)}}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 dr=require("js-base64");var be=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(be||{});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 Jr={AS_CODE_OWNER:[3,0,0],CHECK_RUN:[3,0,0],PR_ISSUE_FULL_DATABASE_ID:[3,12,0],LATEST_REVIEWS:[3,0,0],VIEWER_CAN_MERGE_AS_ADMIN:[3,5,0]},or=15,ir=100,L=s=>!!s,ne=(s,t)=>{let e=Jr[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},we="https://api.github.com",Vr=`${we}/graphql`,ve=`
2
2
  description
3
3
  dueOn
4
4
  id
@@ -15,12 +15,12 @@ url
15
15
  permalink
16
16
  startedAt
17
17
  }
18
- `,we=/\/api\/v\d+$/,Ee=`
18
+ `,Pe=/\/api\/v\d+$/,Ee=`
19
19
  color
20
20
  description
21
21
  id
22
22
  name
23
- `,ar=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.")},Xr=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),ar(e),we.test(e)&&(e=e.replace(we,"")),`${e}/api/graphql`):Vr},ne=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),ar(e),we.test(e)&&(e=e.replace(we,"")),`${e}/api/v3`):Pe},w=(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:Xr(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},Yr={user:!0,"user:email":!0,"read:user":!0},z=s=>s.some(t=>Yr[t]),k=(s=!1,t=!1,e)=>`
23
+ `,ar=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.")},Xr=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),ar(e),Pe.test(e)&&(e=e.replace(Pe,"")),`${e}/api/graphql`):Vr},oe=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),ar(e),Pe.test(e)&&(e=e.replace(Pe,"")),`${e}/api/v3`):we},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:Xr(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},Yr={user:!0,"user:email":!0,"read:user":!0},z=s=>s.some(t=>Yr[t]),k=(s=!1,t=!1,e)=>`
24
24
  __typename
25
25
  ${V(e,["graphQLId"],"id")}
26
26
  ${V(e,["id"],"databaseId")}
@@ -49,7 +49,7 @@ avatarUrl${s?"(size: $avatarSize)":""}
49
49
  url
50
50
  `,qe=(s,t=!1,e)=>`
51
51
  id
52
- databaseId
52
+ ${!e||ne(e,"PR_ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
53
53
  number
54
54
  title
55
55
  state
@@ -71,7 +71,7 @@ commits(last: 1) {
71
71
  contexts(first: 100) {
72
72
  totalCount
73
73
  nodes {
74
- ${!e||be(e,"CHECK_RUN")?Kr:""}
74
+ ${!e||ne(e,"CHECK_RUN")?Kr:""}
75
75
  ... on StatusContext {
76
76
  context
77
77
  createdAt
@@ -138,7 +138,7 @@ assignees(first: 100) {
138
138
  }
139
139
  reviewRequests(first: 100) {
140
140
  nodes {
141
- ${!e||be(e,"AS_CODE_OWNER")?"asCodeOwner":""}
141
+ ${!e||ne(e,"AS_CODE_OWNER")?"asCodeOwner":""}
142
142
  requestedReviewer {
143
143
  ... on User {
144
144
  ${k(!1,t)}
@@ -146,7 +146,7 @@ reviewRequests(first: 100) {
146
146
  }
147
147
  }
148
148
  }
149
- ${!e||be(e,"LATEST_REVIEWS")?Zr(t):""}
149
+ ${!e||ne(e,"LATEST_REVIEWS")?Zr(t):""}
150
150
  additions
151
151
  deletions
152
152
  changedFiles
@@ -160,10 +160,10 @@ labels(first: 100) {
160
160
  ${Ee}
161
161
  }
162
162
  }
163
- ${!e||be(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
164
- `,es=(s=!1)=>`
163
+ ${!e||ne(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
164
+ `,es=(s=!1,t)=>`
165
165
  id
166
- databaseId
166
+ ${!t||ne(t,"PR_ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
167
167
  title
168
168
  author {
169
169
  ... on User {
@@ -215,7 +215,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
215
215
  }
216
216
  nodes {
217
217
  ... on ${n?"Issue":"PullRequest"} {
218
- ${n?es(r.supportsEmail):qe(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
218
+ ${n?es(r.supportsEmail,r.enterpriseVersion??null):qe(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
219
219
  }
220
220
  }
221
221
  }
@@ -239,13 +239,13 @@ defaultBranchRef {
239
239
  name
240
240
  }
241
241
  viewerPermission
242
- `,Rt={__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"},is={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},as={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},us={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},ls={OPEN:"OPEN",CLOSED:"CLOSED"},ps=["ADMIN","MAINTAIN","TRIAGE","WRITE"],yt=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),ds=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),ft=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:ds(s.viewerPermission)}),cs=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),pr=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:cs(s.permissions)}),gs=s=>({path:s.path,isDirectory:s.type==="tree"}),ms={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},hs={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},_=(s,t=hs)=>{let e={};return t.id&&(e.id=s.databaseId.toString()),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},fs=(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]},Is=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],It=s=>{var i,a,u,l,p,d,c,g,m,f,I,P;let t=null;s.author?t=(s.author.__typename==="Bot",s.author):t=Rt;let e=(((i=s.reviewRequests)==null?void 0:i.nodes)||[]).filter(L).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:_(h.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((((l=s.latestReviews)==null?void 0:l.nodes)||[]).filter(L).map(h=>{let R=Rt;return h.author&&Object.keys(h.author).length>0&&(R=h.author),{reviewer:_(R),state:is[h.state]}}));return{id:s.databaseId.toString(),graphQLId:s.id,title:s.title,number:s.number,state:ms[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t?_(t):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId,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,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(L)[0])==null?void 0:d.commit.statusCheckRollup)==null?void 0:c.contexts.nodes)==null?void 0:g.filter(L).map(h=>"context"in h?{completedAt:null,description:h.description,name:h.context,state:Is(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:fs(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:((f=s.baseRef.target)==null?void 0:f.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(L).map(h=>_(h)):null,reviews:o,reviewDecision:J(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:us[s.mergeStateStatus]??as[s.mergeable],milestone:s.milestone?bt(s.milestone):null,labels:((P=(I=s.labels)==null?void 0:I.nodes)==null?void 0:P.filter(L).map(yt))??[],permissions:{canMerge:ps.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Rs=s=>{var f,I;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,id:d,path:c,publishedAt:g,url:m}=a;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:g?new Date(g):null,diffLines:lr(a.diffHunk,n,o,i),id:p,isOutdated:e,isResolved:r,graphQLId:d,filename:c,replies:((I=t.nodes)==null?void 0:I.filter(L).slice(1).map(ys))??[],url:m}},ys=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.databaseId,url:s.url}),bs=s=>{var e,r,n;let t=null;return s.author?t=(s.author.__typename==="Bot",s.author):t=Rt,{id:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:_(t),commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:ls[s.state],color:null},type:null,repository:{id:s.repository.databaseId,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(L).map(o=>_(o)))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?bt(s.milestone):null,labels:((n=(r=s.labels)==null?void 0:r.nodes)==null?void 0:n.filter(L).map(yt))??[]}},bt=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}),oe=class extends Q{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 w(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:`${ne(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(Pe)?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=Yt(e.fields),o=await this.getScopes(r),i=await w(this.config,{query:`
242
+ `,Rt={__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"},is={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},as={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},us={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},ls={OPEN:"OPEN",CLOSED:"CLOSED"},ps=["ADMIN","MAINTAIN","TRIAGE","WRITE"],yt=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),ds=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),ft=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:ds(s.viewerPermission)}),cs=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),pr=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:cs(s.permissions)}),gs=s=>({path:s.path,isDirectory:s.type==="tree"}),ms={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},hs={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},_=(s,t=hs)=>{let e={};return t.id&&(e.id=s.databaseId.toString()),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},fs=(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]},Is=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],It=s=>{var i,a,u,l,p,d,c,g,m,f,I,w;let t=null;s.author?t=(s.author.__typename==="Bot",s.author):t=Rt;let e=(((i=s.reviewRequests)==null?void 0:i.nodes)||[]).filter(L).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:_(h.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((((l=s.latestReviews)==null?void 0:l.nodes)||[]).filter(L).map(h=>{let R=Rt;return h.author&&Object.keys(h.author).length>0&&(R=h.author),{reviewer:_(R),state:is[h.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,number:s.number,state:ms[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t?_(t):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId,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,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(L)[0])==null?void 0:d.commit.statusCheckRollup)==null?void 0:c.contexts.nodes)==null?void 0:g.filter(L).map(h=>"context"in h?{completedAt:null,description:h.description,name:h.context,state:Is(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:fs(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:((f=s.baseRef.target)==null?void 0:f.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(L).map(h=>_(h)):null,reviews:o,reviewDecision:J(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:us[s.mergeStateStatus]??as[s.mergeable],milestone:s.milestone?bt(s.milestone):null,labels:((w=(I=s.labels)==null?void 0:I.nodes)==null?void 0:w.filter(L).map(yt))??[],permissions:{canMerge:ps.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Rs=s=>{var f,I;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,id:d,path:c,publishedAt:g,url:m}=a;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:g?new Date(g):null,diffLines:lr(a.diffHunk,n,o,i),id:p,isOutdated:e,isResolved:r,graphQLId:d,filename:c,replies:((I=t.nodes)==null?void 0:I.filter(L).slice(1).map(ys))??[],url:m}},ys=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.databaseId,url:s.url}),bs=s=>{var e,r,n;let t=null;return s.author?t=(s.author.__typename==="Bot",s.author):t=Rt,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:_(t),commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:ls[s.state],color:null},type:null,repository:{id:s.repository.databaseId,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(L).map(o=>_(o)))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?bt(s.milestone):null,labels:((n=(r=s.labels)==null?void 0:r.nodes)==null?void 0:n.filter(L).map(yt))??[]}},bt=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}),ie=class extends Q{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:`${oe(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(we)?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=Yt(e.fields),o=await this.getScopes(r),i=await P(this.config,{query:`
243
243
  query getCurrentUser {
244
244
  viewer {
245
245
  ${k(!1,z(o),n)}
246
246
  }
247
247
  }
248
- `},r),a=(u=i.body.data)==null?void 0:u.viewer;if(!a)throw new b("Current user not found.",i.body.errors);return{data:_(a,n)}}async getAccountsForRepo(e,r={}){var l,p,d,c,g;let n=await this.getScopes(r),{repo:{namespace:o,name:i},cursor:a}=e,u=await w(this.config,{query:`
248
+ `},r),a=(u=i.body.data)==null?void 0:u.viewer;if(!a)throw new b("Current user not found.",i.body.errors);return{data:_(a,n)}}async getAccountsForRepo(e,r={}){var l,p,d,c,g;let n=await this.getScopes(r),{repo:{namespace:o,name:i},cursor:a}=e,u=await P(this.config,{query:`
249
249
  query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
250
250
  repository(owner: $owner, name: $name) {
251
251
  assignableUsers(first: $first, after: $cursor) {
@@ -259,7 +259,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
259
259
  }
260
260
  }
261
261
  }
262
- `,variables:{owner:o,name:i,cursor:a,first:D}},r);if(!u.body.data)throw new b("Could not fetch accounts for repo",u.body.errors);return{pageInfo:((p=(l=u.body.data.repository)==null?void 0:l.assignableUsers)==null?void 0:p.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=u.body.data.repository)==null?void 0:d.assignableUsers)==null?void 0:c.nodes)==null?void 0:g.map(m=>_(m)))??[]}}async getUserForCommit(e,r={}){var a,u;let n=await w(this.config,{query:`
262
+ `,variables:{owner:o,name:i,cursor:a,first:D}},r);if(!u.body.data)throw new b("Could not fetch accounts for repo",u.body.errors);return{pageInfo:((p=(l=u.body.data.repository)==null?void 0:l.assignableUsers)==null?void 0:p.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=u.body.data.repository)==null?void 0:d.assignableUsers)==null?void 0:c.nodes)==null?void 0:g.map(m=>_(m)))??[]}}async getUserForCommit(e,r={}){var a,u;let n=await P(this.config,{query:`
263
263
  query getUserForCommit(
264
264
  $owner: String!
265
265
  $name: String!
@@ -278,7 +278,7 @@ query getUserForCommit(
278
278
  }
279
279
  }
280
280
  }
281
- `,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},r),o=(a=n.body.data)==null?void 0:a.repository;if(!o)throw new b("Repository not found.",n.body.errors);let i=(u=o.object)==null?void 0:u.author;if(!i)throw new b("Commit not found.",n.body.errors);return{data:{name:i.name,email:i.email,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}}}async createCommit(e,r={}){let{commitMessage:n,deletedFiles:o,newOrModifiedFiles:i,repo:a,target:u}=e,l=await w(this.config,{query:`
281
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},r),o=(a=n.body.data)==null?void 0:a.repository;if(!o)throw new b("Repository not found.",n.body.errors);let i=(u=o.object)==null?void 0:u.author;if(!i)throw new b("Commit not found.",n.body.errors);return{data:{name:i.name,email:i.email,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}}}async createCommit(e,r={}){let{commitMessage:n,deletedFiles:o,newOrModifiedFiles:i,repo:a,target:u}=e,l=await P(this.config,{query:`
282
282
  mutation createCommitOnBranch(
283
283
  $branchName: String!,
284
284
  $expectedHeadOid: GitObjectID!,
@@ -305,7 +305,7 @@ mutation createCommitOnBranch(
305
305
  }
306
306
  }
307
307
  }
308
- `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([p,d])=>({contents:dr.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 w(this.config,{query:`
308
+ `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([p,d])=>({contents:dr.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:`
309
309
  query getAccountForEmail($query: String! $avatarSize: Int) {
310
310
  search(query: $query, type: USER, first: 1) {
311
311
  nodes {
@@ -315,13 +315,13 @@ query getAccountForEmail($query: String! $avatarSize: Int) {
315
315
  }
316
316
  }
317
317
  }
318
- `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},r),i=(l=(u=(a=o.body.data)==null?void 0:a.search)==null?void 0:u.nodes)==null?void 0:l[0];if(!i)throw new b("Could not find user via email",o.body.errors);return{data:_({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getAccountForUsername(e,r={}){var a;let n=await this.getScopes(r),o=await w(this.config,{query:`
318
+ `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},r),i=(l=(u=(a=o.body.data)==null?void 0:a.search)==null?void 0:u.nodes)==null?void 0:l[0];if(!i)throw new b("Could not find user via email",o.body.errors);return{data:_({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getAccountForUsername(e,r={}){var a;let n=await this.getScopes(r),o=await P(this.config,{query:`
319
319
  query getUserForUsername($login: String! $avatarSize: Int) {
320
320
  user(login: $login) {
321
321
  ${k(!0,z(n))}
322
322
  }
323
323
  }
324
- `,variables:{login:e.username,avatarSize:e.avatarSize}},r),i=(a=o.body.data)==null?void 0:a.user;if(!i)throw new b("Could not find user via username",o.body.errors);return{data:_({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await w(this.config,{query:`
324
+ `,variables:{login:e.username,avatarSize:e.avatarSize}},r),i=(a=o.body.data)==null?void 0:a.user;if(!i)throw new b("Could not find user via username",o.body.errors);return{data:_({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await P(this.config,{query:`
325
325
  query getOrgsForCurrentUser($cursor: String, $first: Int!) {
326
326
  viewer {
327
327
  organizations(first: $first after: $cursor) {
@@ -340,7 +340,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
340
340
  }
341
341
  }
342
342
  }
343
- `,variables:{cursor:e.cursor,first:D}},r);if(!n.body.data)throw new b("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.body.data.viewer.organizations.pageInfo,data:o.map(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,r={}){var i,a,u,l,p,d,c,g,m;let n=await w(this.config,{query:`
343
+ `,variables:{cursor:e.cursor,first:D}},r);if(!n.body.data)throw new b("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.body.data.viewer.organizations.pageInfo,data:o.map(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,r={}){var i,a,u,l,p,d,c,g,m;let n=await P(this.config,{query:`
344
344
  query getOrgMember($cursor: String, $first: Int!, $login: String!) {
345
345
  viewer {
346
346
  organization(login: $login) {
@@ -356,7 +356,7 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
356
356
  }
357
357
  }
358
358
  }
359
- `,variables:{cursor:e.cursor,first:D,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(f=>_({...f,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(f.avatarUrl,f.email,r)}))}}async getRepo(e,r={}){var o;let n=await w(this.config,{query:`
359
+ `,variables:{cursor:e.cursor,first:D,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(f=>_({...f,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(f.avatarUrl,f.email,r)}))}}async getRepo(e,r={}){var o;let n=await P(this.config,{query:`
360
360
  query getRepo($owner: String!, $name: String!) {
361
361
  repository(owner: $owner, name: $name) {
362
362
  ${ht}
@@ -367,11 +367,11 @@ query getRepo($owner: String!, $name: String!) {
367
367
  ${ht}
368
368
  }
369
369
  `).join(`
370
- `),o=await w(this.config,{query:`
370
+ `),o=await P(this.config,{query:`
371
371
  query batchGetRepos {
372
372
  ${n}
373
373
  }
374
- `},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(ft(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:`${ne(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,pr)}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:`${ne(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,pr)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await w(this.config,{query:`
374
+ `},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(ft(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:`${oe(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,pr)}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:`${oe(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,pr)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await P(this.config,{query:`
375
375
  query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
376
376
  search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
377
377
  pageInfo {
@@ -385,7 +385,7 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
385
385
  }
386
386
  }
387
387
  }
388
- `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:D}},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(ft)}}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 w(this.config,{query:`
388
+ `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:D}},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(ft)}}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:`
389
389
  query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
390
390
  repository(owner: $owner, name: $name) {
391
391
  refs(refPrefix: $refPrefix first: $first after: $cursor) {
@@ -406,7 +406,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
406
406
  }
407
407
  }
408
408
  }
409
- `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:D}},n),i=(u=o.body.data)==null?void 0:u.repository;if(!i)throw new b("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(l=>{var d;let p=(d=l.target)!=null&&d.oid?l.target:null;return{name:l.name,commit:p?{oid:p.oid,authoredDate:new Date(p.authoredDate),committedDate:new Date(p.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,r={}){return this.getRefs("refs/heads/",e,r)}async getTags(e,r={}){return this.getRefs("refs/tags/",e,r)}async getBlame(e,r={}){var a;let n=await w(this.config,{query:`
409
+ `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:D}},n),i=(u=o.body.data)==null?void 0:u.repository;if(!i)throw new b("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(l=>{var d;let p=(d=l.target)!=null&&d.oid?l.target:null;return{name:l.name,commit:p?{oid:p.oid,authoredDate:new Date(p.authoredDate),committedDate:new Date(p.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,r={}){return this.getRefs("refs/heads/",e,r)}async getTags(e,r={}){return this.getRefs("refs/tags/",e,r)}async getBlame(e,r={}){var a;let n=await P(this.config,{query:`
410
410
  query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
411
411
  repository(owner: $owner, name: $name) {
412
412
  object(expression: $ref) {
@@ -445,7 +445,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
445
445
  }
446
446
  }
447
447
  }
448
- `,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:`${ne(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=z(o),a=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return mt("pr",c,e.cursor,{maxPageSize:e.maxPageSize??or,supportsEmail:i,supportsDrafts:d,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await w(this.config,a(!0),r);u.body.errors&&Se(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await w(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(L).map(It))||[]}}async searchIssues(e,r={}){var u;let n=await this.getScopes(r),o=z(n),i=await w(this.config,mt("issue",e.query,e.cursor,{supportsEmail:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??ir}),r),{data:a}=i.body;if(!a)throw new b("Could not search issues",i.body.errors);return{pageInfo:{hasNextPage:a.search.pageInfo.hasNextPage,endCursor:a.search.pageInfo.endCursor},data:((u=a.search.nodes)==null?void 0:u.filter(L).map(bs))||[]}}async getPullRequestsAssociatedWithUser(e,r={}){let n=[`involves:${e.username}`];return e.labelNames&&e.labelNames.forEach(o=>{n.push(`label:"${o}"`)}),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=gt(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=z(o),a=c=>({query:`query getPullRequest(
448
+ `,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:`${oe(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=z(o),a=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return mt("pr",c,e.cursor,{maxPageSize:e.maxPageSize??or,supportsEmail:i,supportsDrafts:d,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await P(this.config,a(!0),r);u.body.errors&&Se(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(L).map(It))||[]}}async searchIssues(e,r={}){var l;let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=z(o),a=await P(this.config,mt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??ir,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(L).map(bs))||[]}}async getPullRequestsAssociatedWithUser(e,r={}){let n=[`involves:${e.username}`];return e.labelNames&&e.labelNames.forEach(o=>{n.push(`label:"${o}"`)}),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=gt(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=z(o),a=c=>({query:`query getPullRequest(
449
449
  $owner: String!
450
450
  $name: String!
451
451
  $number: Int!
@@ -458,7 +458,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
458
458
  ${qe(c,i,n)}
459
459
  }
460
460
  }
461
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await w(this.config,a(!0),r);u.body.errors&&Se(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await w(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?It(p):null}}async getPullRequestByGraphQLId(e,r={}){var d;let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=z(o),a=c=>({query:`query getPullRequest(
461
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await P(this.config,a(!0),r);u.body.errors&&Se(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?It(p):null}}async getPullRequestByGraphQLId(e,r={}){var d;let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=z(o),a=c=>({query:`query getPullRequest(
462
462
  $graphQLId: ID!
463
463
  ) {
464
464
  node(id: $graphQLId) {
@@ -466,13 +466,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
466
466
  ${qe(c,i,n)}
467
467
  }
468
468
  }
469
- }`,variables:{graphQLId:e.graphQLId}}),u=await w(this.config,a(!0),r);u.body.errors&&Se(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await w(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?It(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!) {
469
+ }`,variables:{graphQLId:e.graphQLId}}),u=await P(this.config,a(!0),r);u.body.errors&&Se(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?It(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!) {
470
470
  closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
471
471
  pullRequest {
472
472
  id
473
473
  }
474
474
  }
475
- }`,i=await w(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:n}},r);if(!((l=(u=(a=i.body.data)==null?void 0:a.closePullRequest)==null?void 0:u.pullRequest)!=null&&l.id))throw new b("Could not close pull request",i.body.errors)}async mergePullRequest(e,r={}){var l,p,d,c;let{pullRequest:n,mergeStrategy:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!((l=n.headRef)!=null&&l.oid))throw new Error('GitHub requires "headRef.oid" for this function.');let i;switch(o){case"MERGE_COMMIT":{i="MERGE";break}case"REBASE":{i="REBASE";break}case"SQUASH":{i="SQUASH";break}}let a=`mutation MergePullRequest(
475
+ }`,i=await P(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:n}},r);if(!((l=(u=(a=i.body.data)==null?void 0:a.closePullRequest)==null?void 0:u.pullRequest)!=null&&l.id))throw new b("Could not close pull request",i.body.errors)}async mergePullRequest(e,r={}){var l,p,d,c;let{pullRequest:n,mergeStrategy:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!((l=n.headRef)!=null&&l.oid))throw new Error('GitHub requires "headRef.oid" for this function.');let i;switch(o){case"MERGE_COMMIT":{i="MERGE";break}case"REBASE":{i="REBASE";break}case"SQUASH":{i="SQUASH";break}}let a=`mutation MergePullRequest(
476
476
  $pullRequestGraphQLId: ID!,
477
477
  $expectedSourceSha: GitObjectID!,
478
478
  $mergeStrategy: PullRequestMergeMethod,
@@ -486,43 +486,43 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
486
486
  id
487
487
  }
488
488
  }
489
- }`,u=await w(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:n.graphQLId,expectedSourceSha:n.headRef.oid,mergeStrategy:i}},r);if(!((c=(d=(p=u.body.data)==null?void 0:p.mergePullRequest)==null?void 0:d.pullRequest)!=null&&c.id))throw new b("Could not merge pull request",u.body.errors)}async setPullRequestMilestone(e,r={}){var u,l,p;let{pullRequest:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
489
+ }`,u=await P(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:n.graphQLId,expectedSourceSha:n.headRef.oid,mergeStrategy:i}},r);if(!((c=(d=(p=u.body.data)==null?void 0:p.mergePullRequest)==null?void 0:d.pullRequest)!=null&&c.id))throw new b("Could not merge pull request",u.body.errors)}async setPullRequestMilestone(e,r={}){var u,l,p;let{pullRequest:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
490
490
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
491
491
  pullRequest {
492
492
  id
493
493
  }
494
494
  }
495
- }`,a=await w(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:n.graphQLId,milestoneGraphQLId:(o==null?void 0:o.graphQLId)??null}},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 milestone of pull request",a.body.errors)}async markPullRequestReadyForReview(e,r){var i,a,u;let n=`mutation MarkReadyToReview($pullRequestGraphQLId: ID!) {
495
+ }`,a=await P(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:n.graphQLId,milestoneGraphQLId:(o==null?void 0:o.graphQLId)??null}},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 milestone of pull request",a.body.errors)}async markPullRequestReadyForReview(e,r){var i,a,u;let n=`mutation MarkReadyToReview($pullRequestGraphQLId: ID!) {
496
496
  markPullRequestReadyForReview(input: { pullRequestId: $pullRequestGraphQLId }) {
497
497
  pullRequest {
498
498
  id
499
499
  }
500
500
  }
501
- }`,o=await w(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!((u=(a=(i=o.body.data)==null?void 0:i.markPullRequestReadyForReview)==null?void 0:a.pullRequest)!=null&&u.id))throw new b("Could not mark pull request ready to review",o.body.errors)}async convertPullRequestToDraft(e,r){var i,a,u;let n=`mutation ConvertToDraft($pullRequestGraphQLId: ID!) {
501
+ }`,o=await P(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!((u=(a=(i=o.body.data)==null?void 0:i.markPullRequestReadyForReview)==null?void 0:a.pullRequest)!=null&&u.id))throw new b("Could not mark pull request ready to review",o.body.errors)}async convertPullRequestToDraft(e,r){var i,a,u;let n=`mutation ConvertToDraft($pullRequestGraphQLId: ID!) {
502
502
  convertPullRequestToDraft(input: { pullRequestId: $pullRequestGraphQLId }) {
503
503
  pullRequest {
504
504
  id
505
505
  }
506
506
  }
507
- }`,o=await w(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!((u=(a=(i=o.body.data)==null?void 0:i.convertPullRequestToDraft)==null?void 0:a.pullRequest)!=null&&u.id))throw new b("Could not convert pull request to draft",o.body.errors)}async setPullRequestAsDraft(e,r={}){let{pullRequest:{graphQLId:n},isDraft:o}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');if(o){await this.convertPullRequestToDraft(n,r);return}await this.markPullRequestReadyForReview(n,r)}async setPullRequestReviewers(e,r={}){var d,c,g;let{pullRequest:{reviews:n,graphQLId:o},reviewers:i}=e;if(!n)throw new Error('GitHub requires "reviews" for this function');if(!o)throw new Error('GitHub requires "graphQLId" for this function.');let a=n.filter(m=>m.state!=="REVIEW_REQUESTED").map(m=>{if(!m.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return m.reviewer.graphQLId}),u=i.map(m=>{if(!m.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return m.graphQLId}).filter(m=>a.indexOf(m)===-1),l=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
507
+ }`,o=await P(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!((u=(a=(i=o.body.data)==null?void 0:i.convertPullRequestToDraft)==null?void 0:a.pullRequest)!=null&&u.id))throw new b("Could not convert pull request to draft",o.body.errors)}async setPullRequestAsDraft(e,r={}){let{pullRequest:{graphQLId:n},isDraft:o}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');if(o){await this.convertPullRequestToDraft(n,r);return}await this.markPullRequestReadyForReview(n,r)}async setPullRequestReviewers(e,r={}){var d,c,g;let{pullRequest:{reviews:n,graphQLId:o},reviewers:i}=e;if(!n)throw new Error('GitHub requires "reviews" for this function');if(!o)throw new Error('GitHub requires "graphQLId" for this function.');let a=n.filter(m=>m.state!=="REVIEW_REQUESTED").map(m=>{if(!m.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return m.reviewer.graphQLId}),u=i.map(m=>{if(!m.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return m.graphQLId}).filter(m=>a.indexOf(m)===-1),l=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
508
508
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds }) {
509
509
  pullRequest {
510
510
  id
511
511
  }
512
512
  }
513
- }`,p=await w(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},r);if(!((g=(c=(d=p.body.data)==null?void 0:d.requestReviews)==null?void 0:c.pullRequest)!=null&&g.id))throw new b("Could not set pull request reviewers",p.body.errors)}async reRequestPullRequestReviews(e,r={}){var p,d,c;let{pullRequest:{reviews:n,graphQLId:o},reviewers:i}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!n)throw new Error('GitHub requires "reviews" for this function.');let a=[];for(let g of i){if(!g.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!n.find(m=>m.reviewer.graphQLId===g.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(g.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
513
+ }`,p=await P(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},r);if(!((g=(c=(d=p.body.data)==null?void 0:d.requestReviews)==null?void 0:c.pullRequest)!=null&&g.id))throw new b("Could not set pull request reviewers",p.body.errors)}async reRequestPullRequestReviews(e,r={}){var p,d,c;let{pullRequest:{reviews:n,graphQLId:o},reviewers:i}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!n)throw new Error('GitHub requires "reviews" for this function.');let a=[];for(let g of i){if(!g.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!n.find(m=>m.reviewer.graphQLId===g.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(g.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
514
514
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
515
515
  pullRequest {
516
516
  id
517
517
  }
518
518
  }
519
- }`,l=await w(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:a}},r);if(!((c=(d=(p=l.body.data)==null?void 0:p.requestReviews)==null?void 0:d.pullRequest)!=null&&c.id))throw new b("Could not re-request pull request reviews",l.body.errors)}async setPullRequestAssignees(e,r={}){var l,p,d;let{pullRequest:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(c=>{if(!c.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return c.graphQLId}),a=`mutation SetPullRequestAssignees($pullRequestGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
519
+ }`,l=await P(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:a}},r);if(!((c=(d=(p=l.body.data)==null?void 0:p.requestReviews)==null?void 0:d.pullRequest)!=null&&c.id))throw new b("Could not re-request pull request reviews",l.body.errors)}async setPullRequestAssignees(e,r={}){var l,p,d;let{pullRequest:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(c=>{if(!c.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return c.graphQLId}),a=`mutation SetPullRequestAssignees($pullRequestGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
520
520
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
521
521
  pullRequest {
522
522
  id
523
523
  }
524
524
  }
525
- }`,u=await w(this.config,{query:a,variables:{pullRequestGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},r);if(!((d=(p=(l=u.body.data)==null?void 0:l.updatePullRequest)==null?void 0:p.pullRequest)!=null&&d.id))throw new b("Could not set pull request assignees",u.body.errors)}async getReviewsForPullRequest(e,r={}){var d,c,g,m;let{repo:{namespace:n,name:o},pullRequestId:i}=e,a=`query getPullRequests(
525
+ }`,u=await P(this.config,{query:a,variables:{pullRequestGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},r);if(!((d=(p=(l=u.body.data)==null?void 0:l.updatePullRequest)==null?void 0:p.pullRequest)!=null&&d.id))throw new b("Could not set pull request assignees",u.body.errors)}async getReviewsForPullRequest(e,r={}){var d,c,g,m;let{repo:{namespace:n,name:o},pullRequestId:i}=e,a=`query getPullRequests(
526
526
  $namespace: String!
527
527
  $name: String!
528
528
  $pullRequestId: Int!
@@ -574,49 +574,49 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
574
574
  }
575
575
  }
576
576
  }
577
- }`,u=await w(this.config,{query:a,variables:{namespace:n,name:o,pullRequestId:i}},r),l=((c=(d=u.body.data)==null?void 0:d.repository.pullRequest.reviewThreads.nodes)==null?void 0:c.filter(L).reduce((f,I)=>{var R,q;if(!((q=(R=I.comments.nodes)==null?void 0:R[0])!=null&&q.pullRequestReview))return f;let P=I.comments.nodes[0].pullRequestReview,h=Rs(I);return h&&(f[P.id]||(f[P.id]=[]),f[P.id].push(h)),f},{}))??{};return{data:((m=(g=u.body.data)==null?void 0:g.repository.pullRequest.reviews.nodes)==null?void 0:m.filter(L).filter(f=>l[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.databaseId,graphQLId:f.id,reviewComments:l[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!]) {
577
+ }`,u=await P(this.config,{query:a,variables:{namespace:n,name:o,pullRequestId:i}},r),l=((c=(d=u.body.data)==null?void 0:d.repository.pullRequest.reviewThreads.nodes)==null?void 0:c.filter(L).reduce((f,I)=>{var R,q;if(!((q=(R=I.comments.nodes)==null?void 0:R[0])!=null&&q.pullRequestReview))return f;let w=I.comments.nodes[0].pullRequestReview,h=Rs(I);return h&&(f[w.id]||(f[w.id]=[]),f[w.id].push(h)),f},{}))??{};return{data:((m=(g=u.body.data)==null?void 0:g.repository.pullRequest.reviews.nodes)==null?void 0:m.filter(L).filter(f=>l[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.databaseId,graphQLId:f.id,reviewComments:l[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!]) {
578
578
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
579
579
  pullRequest {
580
580
  id
581
581
  }
582
582
  }
583
- }`,a=await w(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=gt(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!) {
583
+ }`,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=gt(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!) {
584
584
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
585
585
  issue {
586
586
  id
587
587
  }
588
588
  }
589
- }`,a=await w(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId,reason:o}},r);if(!((p=(l=(u=a.body.data)==null?void 0:u.closeIssue)==null?void 0:l.issue)!=null&&p.id))throw new b("Could not close issue with reason",a.body.errors)}async closeIssue(e,r={}){var a,u,l;let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetIssueState($issueGraphQLId: ID!) {
589
+ }`,a=await P(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId,reason:o}},r);if(!((p=(l=(u=a.body.data)==null?void 0:u.closeIssue)==null?void 0:l.issue)!=null&&p.id))throw new b("Could not close issue with reason",a.body.errors)}async closeIssue(e,r={}){var a,u,l;let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetIssueState($issueGraphQLId: ID!) {
590
590
  updateIssue(input: { id: $issueGraphQLId, state: CLOSED }) {
591
591
  issue {
592
592
  id
593
593
  }
594
594
  }
595
- }`,i=await w(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!((l=(u=(a=i.body.data)==null?void 0:a.updateIssue)==null?void 0:u.issue)!=null&&l.id))throw new b("Could not close issue",i.body.errors)}async reOpenIssue(e,r={}){var a,u,l;let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ReOpenIssue($issueGraphQLId: ID!) {
595
+ }`,i=await P(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!((l=(u=(a=i.body.data)==null?void 0:a.updateIssue)==null?void 0:u.issue)!=null&&l.id))throw new b("Could not close issue",i.body.errors)}async reOpenIssue(e,r={}){var a,u,l;let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ReOpenIssue($issueGraphQLId: ID!) {
596
596
  reopenIssue(input: { issueId: $issueGraphQLId }) {
597
597
  issue {
598
598
  id
599
599
  }
600
600
  }
601
- }`,i=await w(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!((l=(u=(a=i.body.data)==null?void 0:a.reopenIssue)==null?void 0:u.issue)!=null&&l.id))throw new b("Could not reopen issue",i.body.errors)}async setIssueLabels(e,r={}){var l,p,d;let{issue:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(c=>c.graphQLId),a=`mutation SetIssueLabels($issueGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
601
+ }`,i=await P(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!((l=(u=(a=i.body.data)==null?void 0:a.reopenIssue)==null?void 0:u.issue)!=null&&l.id))throw new b("Could not reopen issue",i.body.errors)}async setIssueLabels(e,r={}){var l,p,d;let{issue:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(c=>c.graphQLId),a=`mutation SetIssueLabels($issueGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
602
602
  updateIssue(input: { id: $issueGraphQLId, labelIds: $labelGraphQLIds }) {
603
603
  issue {
604
604
  id
605
605
  }
606
606
  }
607
- }`,u=await w(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,labelGraphQLIds:i}},r);if(!((d=(p=(l=u.body.data)==null?void 0:l.updateIssue)==null?void 0:p.issue)!=null&&d.id))throw new b("Could not set issue labels",u.body.errors)}async setIssueMilestone(e,r={}){var u,l,p;let{issue:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(o&&!o.graphQLId)throw new Error('GitHub requires milestone "graphQLId" for this function.');let i=`mutation SetIssueMilestone($issueGraphQLId: ID!, $milestoneGraphQLId: ID) {
607
+ }`,u=await P(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,labelGraphQLIds:i}},r);if(!((d=(p=(l=u.body.data)==null?void 0:l.updateIssue)==null?void 0:p.issue)!=null&&d.id))throw new b("Could not set issue labels",u.body.errors)}async setIssueMilestone(e,r={}){var u,l,p;let{issue:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(o&&!o.graphQLId)throw new Error('GitHub requires milestone "graphQLId" for this function.');let i=`mutation SetIssueMilestone($issueGraphQLId: ID!, $milestoneGraphQLId: ID) {
608
608
  updateIssue(input: { id: $issueGraphQLId, milestoneId: $milestoneGraphQLId }) {
609
609
  issue {
610
610
  id
611
611
  }
612
612
  }
613
- }`,a=await w(this.config,{query:`${i}`,variables:{issueGraphQLId:n.graphQLId,milestoneGraphQLId:(o==null?void 0:o.graphQLId)??null}},r);if(!((p=(l=(u=a.body.data)==null?void 0:u.updateIssue)==null?void 0:l.issue)!=null&&p.id))throw new b("Could not set milestone of issue",a.body.errors)}async setIssueAssignees(e,r={}){var l,p,d;let{issue:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(c=>{if(!c.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return c.graphQLId}),a=`mutation SetIssueAssignees($issueGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
613
+ }`,a=await P(this.config,{query:`${i}`,variables:{issueGraphQLId:n.graphQLId,milestoneGraphQLId:(o==null?void 0:o.graphQLId)??null}},r);if(!((p=(l=(u=a.body.data)==null?void 0:u.updateIssue)==null?void 0:l.issue)!=null&&p.id))throw new b("Could not set milestone of issue",a.body.errors)}async setIssueAssignees(e,r={}){var l,p,d;let{issue:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(c=>{if(!c.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return c.graphQLId}),a=`mutation SetIssueAssignees($issueGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
614
614
  updateIssue(input: { id: $issueGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
615
615
  issue {
616
616
  id
617
617
  }
618
618
  }
619
- }`,u=await w(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},r);if(!((d=(p=(l=u.body.data)==null?void 0:l.updateIssue)==null?void 0:p.issue)!=null&&d.id))throw new b("Could not set issue assignees",u.body.errors)}async getMilestonesForRepo(e,r={}){var u,l,p;let{repo:{namespace:n,name:o},cursor:i}=e,a=await w(this.config,{query:`
619
+ }`,u=await P(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},r);if(!((d=(p=(l=u.body.data)==null?void 0:l.updateIssue)==null?void 0:p.issue)!=null&&d.id))throw new b("Could not set issue assignees",u.body.errors)}async getMilestonesForRepo(e,r={}){var u,l,p;let{repo:{namespace:n,name:o},cursor:i}=e,a=await P(this.config,{query:`
620
620
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
621
621
  repository(owner: $owner, name: $name) {
622
622
  milestones(first: $first, after: $cursor) {
@@ -630,7 +630,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
630
630
  }
631
631
  }
632
632
  }
633
- `,variables:{owner:n,name:o,cursor:i,first:D}},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(bt))??[]}}async getLabelsForRepo(e,r={}){var u,l,p;let{repo:{namespace:n,name:o},cursor:i}=e,a=await w(this.config,{query:`
633
+ `,variables:{owner:n,name:o,cursor:i,first:D}},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(bt))??[]}}async getLabelsForRepo(e,r={}){var u,l,p;let{repo:{namespace:n,name:o},cursor:i}=e,a=await P(this.config,{query:`
634
634
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
635
635
  repository(owner: $owner, name: $name) {
636
636
  labels(first: $first, after: $cursor) {
@@ -644,7 +644,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
644
644
  }
645
645
  }
646
646
  }
647
- `,variables:{owner:n,name:o,cursor:i,first:D}},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(yt))??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${ne(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(gs)}}};var ws="https://gitlab.com/api/v4",Ps="https://gitlab.com/api/graphql",cr=/\/api\/v\d+$/,gr=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.")},Ce=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),gr(e),e):ws},vs=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),gr(e),cr.test(e)&&(e=e.replace(cr,"")),`${e}/api/graphql`):Ps},v=(s,t,e)=>{let r=y(e.token||s.token);return s.request({url:vs(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},De=s=>s==null?void 0:s.map(t=>`"${t.message}"`).join(", ");var qt=s=>s.split("/").slice(0,-1).join("/"),St=s=>s.split("/").at(-1)??"",Ae=s=>({id:s.id.replace(ie,""),graphQLId:s.id,namespace:qt(s.fullPath),name:St(s.fullPath),webUrl:s.webUrl}),mr=s=>({id:s.id.replace(ie,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:qt(s.fullPath),name:St(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Es={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},qs={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Ss="gid://gitlab/User/",ie="gid://gitlab/Project/",Cs="gid://gitlab/MergeRequest/",Ds="gid://gitlab/Issue/",As="gid://gitlab/ProjectLabel/",Us="gid://gitlab/Milestone/",Ls="gid://gitlab/Ci::Build/",Ct=`
647
+ `,variables:{owner:n,name:o,cursor:i,first:D}},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(yt))??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${oe(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(gs)}}};var Ps="https://gitlab.com/api/v4",ws="https://gitlab.com/api/graphql",cr=/\/api\/v\d+$/,gr=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.")},Ce=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),gr(e),e):Ps},vs=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),gr(e),cr.test(e)&&(e=e.replace(cr,"")),`${e}/api/graphql`):ws},v=(s,t,e)=>{let r=y(e.token||s.token);return s.request({url:vs(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},De=s=>s==null?void 0:s.map(t=>`"${t.message}"`).join(", ");var qt=s=>s.split("/").slice(0,-1).join("/"),St=s=>s.split("/").at(-1)??"",Ue=s=>({id:s.id.replace(ae,""),graphQLId:s.id,namespace:qt(s.fullPath),name:St(s.fullPath),webUrl:s.webUrl}),mr=s=>({id:s.id.replace(ae,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:qt(s.fullPath),name:St(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Es={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},qs={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Ss="gid://gitlab/User/",ae="gid://gitlab/Project/",Cs="gid://gitlab/MergeRequest/",Ds="gid://gitlab/Issue/",Us="gid://gitlab/ProjectLabel/",As="gid://gitlab/Milestone/",Ls="gid://gitlab/Ci::Build/",Ct=`
648
648
  description
649
649
  dueDate
650
650
  id
@@ -653,7 +653,7 @@ startDate
653
653
  state
654
654
  title
655
655
  webPath
656
- `,wt=`
656
+ `,Pt=`
657
657
  id
658
658
  fullPath
659
659
  webUrl
@@ -679,7 +679,7 @@ color
679
679
  description
680
680
  id
681
681
  title
682
- `,Pt=`
682
+ `,wt=`
683
683
  author {
684
684
  ${W}
685
685
  }
@@ -776,7 +776,7 @@ labels {
776
776
  ${s?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
777
777
  ${t?`milestone { ${Ct} }`:""}
778
778
  ${e?`headPipeline { ${$s} }`:""}
779
- `,K=s=>`${s.namespace}/${s.name}`,Gs=s=>`${s.namespace}/${s.name}`,Ts=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),vt=s=>{var t;return{id:s.id.replace(ie,""),graphQLId:s.id,namespace:qt(s.fullPath),name:St(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:(t=s.repository)!=null&&t.rootRef?{name:s.repository.rootRef}:null,permissions:Ts(s.userPermissions)}},Os=s=>({path:s.path,isDirectory:s.type==="tree"}),ks={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},H=(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(Ss,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},At=s=>({color:s.color,description:s.description,id:s.id.replace(As,""),graphQLId:s.id,name:s.title}),xs=(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,Ns=(s,t,e)=>{var n;let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:H(s,t,e),state:(n=s.mergeRequestInteraction)!=null&&n.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},fr=(s,t,e,r,n)=>{var i,a,u,l,p,d,c,g,m,f,I,P;let o=(i=s.reviewers)!=null&&i.nodes?s.reviewers.nodes.map(h=>Ns(h,r,n)):null;return{id:s.id.replace(Cs,""),graphQLId:s.id,title:s.title,number:parseInt(s.iid,10),state:ks[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?H(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,q;return((q=(R=h.jobs)==null?void 0:R.nodes)==null?void 0:q.map(G=>({completedAt:G.finishedAt?new Date(G.finishedAt):null,description:null,name:G.name??null,state:xs(G.status,G.allowFailure),stage:h.name??null,startedAt:new Date(G.createdAt),url:`${t.webUrl}/-/jobs/${G.id.replace(Ls,"")}`})))??[]}))??[]},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=>H(h,r,n)):null,reviews:o,reviewDecision:s.approved?"APPROVED":J(o),additions:((g=s.diffStatsSummary)==null?void 0:g.additions)||0,deletions:((m=s.diffStatsSummary)==null?void 0:m.deletions)||0,fileCount:((f=s.diffStatsSummary)==null?void 0:f.fileCount)||0,commitCount:s.commitCount||0,mergeableState:qs[s.mergeStatusEnum],milestone:s.milestone?Ut(s.milestone,t.webUrl):null,labels:((P=(I=s.labels)==null?void 0:I.nodes)==null?void 0:P.map(At))??[],permissions:null}},Et=(s,t,e,r)=>{var n,o;return{author:H(s.author,e,r),assignees:s.assignees.nodes.map(i=>H(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(Ds,""),labels:((o=(n=s.labels)==null?void 0:n.nodes)==null?void 0:o.map(At))??[],number:s.iid,repository:{id:t.id.replace(ie,""),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?Ut(s.milestone,t.webUrl):null}},Ut=(s,t)=>({id:s.id.replace(Us,""),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}),ae=class extends Q{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){var o;let n=(o=(await v(this.config,{query:`
779
+ `,K=s=>`${s.namespace}/${s.name}`,Gs=s=>`${s.namespace}/${s.name}`,Ts=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),vt=s=>{var t;return{id:s.id.replace(ae,""),graphQLId:s.id,namespace:qt(s.fullPath),name:St(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:(t=s.repository)!=null&&t.rootRef?{name:s.repository.rootRef}:null,permissions:Ts(s.userPermissions)}},Os=s=>({path:s.path,isDirectory:s.type==="tree"}),ks={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},H=(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(Ss,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},Ut=s=>({color:s.color,description:s.description,id:s.id.replace(Us,""),graphQLId:s.id,name:s.title}),xs=(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,Ns=(s,t,e)=>{var n;let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:H(s,t,e),state:(n=s.mergeRequestInteraction)!=null&&n.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},fr=(s,t,e,r,n)=>{var i,a,u,l,p,d,c,g,m,f,I,w;let o=(i=s.reviewers)!=null&&i.nodes?s.reviewers.nodes.map(h=>Ns(h,r,n)):null;return{id:s.id.replace(Cs,""),graphQLId:s.id,title:s.title,number:parseInt(s.iid,10),state:ks[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?H(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,q;return((q=(R=h.jobs)==null?void 0:R.nodes)==null?void 0:q.map(G=>({completedAt:G.finishedAt?new Date(G.finishedAt):null,description:null,name:G.name??null,state:xs(G.status,G.allowFailure),stage:h.name??null,startedAt:new Date(G.createdAt),url:`${t.webUrl}/-/jobs/${G.id.replace(Ls,"")}`})))??[]}))??[]},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=>H(h,r,n)):null,reviews:o,reviewDecision:s.approved?"APPROVED":J(o),additions:((g=s.diffStatsSummary)==null?void 0:g.additions)||0,deletions:((m=s.diffStatsSummary)==null?void 0:m.deletions)||0,fileCount:((f=s.diffStatsSummary)==null?void 0:f.fileCount)||0,commitCount:s.commitCount||0,mergeableState:qs[s.mergeStatusEnum],milestone:s.milestone?At(s.milestone,t.webUrl):null,labels:((w=(I=s.labels)==null?void 0:I.nodes)==null?void 0:w.map(Ut))??[],permissions:null}},Et=(s,t,e,r)=>{var n,o;return{author:H(s.author,e,r),assignees:s.assignees.nodes.map(i=>H(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(Ds,""),labels:((o=(n=s.labels)==null?void 0:n.nodes)==null?void 0:o.map(Ut))??[],number:s.iid,repository:{id:t.id.replace(ae,""),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?At(s.milestone,t.webUrl):null}},At=(s,t)=>({id:s.id.replace(As,""),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}),ue=class extends Q{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){var o;let n=(o=(await v(this.config,{query:`
780
780
  query getCurrentUser {
781
781
  currentUser {
782
782
  ${W}
@@ -834,12 +834,12 @@ query getAccountsForRepo(
834
834
  `,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(f=>f.user).filter(f=>f!==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(f=>H(f,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))??[]}}async getRepo(t,e={}){var o;let r=K(t),n=await v(this.config,{query:`
835
835
  query getRepo($fullPath: ID!) {
836
836
  project(fullPath: $fullPath) {
837
- ${wt}
837
+ ${Pt}
838
838
  }
839
839
  }
840
840
  `,variables:{fullPath:r}},e);if(!((o=n.body.data)!=null&&o.project))throw new Error(`Repository ${r} not found`);return{data:vt(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(K).map((u,l)=>`
841
841
  getRepo_${l}: project(fullPath: "${u}") {
842
- ${wt}
842
+ ${Pt}
843
843
  }
844
844
  `).join(`
845
845
  `),o=await v(this.config,{query:`
@@ -854,7 +854,7 @@ query getReposForCurrentUser($after: String) {
854
854
  hasNextPage
855
855
  }
856
856
  nodes {
857
- ${wt}
857
+ ${Pt}
858
858
  }
859
859
  }
860
860
  }
@@ -872,7 +872,7 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
872
872
  }
873
873
  }
874
874
  }
875
- `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!n.body.data)throw new Error(De(n.body.errors)||n.statusText||"Unknown error");if(!n.body.data.user)throw new Error("User not found");let o=n.body.data.user[r];if(!o)throw new Error("Unexpected response");return{pageInfo:o.pageInfo,data:((i=o.nodes)==null?void 0:i.filter(a=>t.includeFromArchivedRepos||!a.project.archived).map(a=>fr(a,mr(a.project),mr(a.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))||[]}}async getPullRequestsAssociatedWithUser(t,e={}){var c;let[r,n,o]=((c=t.cursor)==null?void 0:c.split(";"))||[void 0,void 0,void 0],[i,a,u]=await Promise.all([r==="null"?null:this.getPullRequestsForUser({username:t.username,association:"authored",cursor:r,includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames},e),n==="null"?null:this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:n,includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames},e),o==="null"?null:this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:o,includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames},e)]),l={},p=[],d=g=>{l[g.id]||(l[g.id]=!0,p.push(g))};return i==null||i.data.forEach(d),a==null||a.data.forEach(d),u==null||u.data.forEach(d),{pageInfo:{hasNextPage:(i==null?void 0:i.pageInfo.hasNextPage)||(a==null?void 0:a.pageInfo.hasNextPage)||(u==null?void 0:u.pageInfo.hasNextPage)||!1,endCursor:`${(i==null?void 0:i.pageInfo.hasNextPage)&&(i==null?void 0:i.pageInfo.endCursor)||"null"};${(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}}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 I,P,h;let{cursor:n,repo:o}=t||{},i=K(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),p={fullPath:i,...a},d=await v(this.config,{query:`
875
+ `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!n.body.data)throw new Error(De(n.body.errors)||n.statusText||"Unknown error");if(!n.body.data.user)throw new Error("User not found");let o=n.body.data.user[r];if(!o)throw new Error("Unexpected response");return{pageInfo:o.pageInfo,data:((i=o.nodes)==null?void 0:i.filter(a=>t.includeFromArchivedRepos||!a.project.archived).map(a=>fr(a,mr(a.project),mr(a.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))||[]}}async getPullRequestsAssociatedWithUser(t,e={}){var c;let[r,n,o]=((c=t.cursor)==null?void 0:c.split(";"))||[void 0,void 0,void 0],[i,a,u]=await Promise.all([r==="null"?null:this.getPullRequestsForUser({username:t.username,association:"authored",cursor:r,includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames},e),n==="null"?null:this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:n,includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames},e),o==="null"?null:this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:o,includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames},e)]),l={},p=[],d=g=>{l[g.id]||(l[g.id]=!0,p.push(g))};return i==null||i.data.forEach(d),a==null||a.data.forEach(d),u==null||u.data.forEach(d),{pageInfo:{hasNextPage:(i==null?void 0:i.pageInfo.hasNextPage)||(a==null?void 0:a.pageInfo.hasNextPage)||(u==null?void 0:u.pageInfo.hasNextPage)||!1,endCursor:`${(i==null?void 0:i.pageInfo.hasNextPage)&&(i==null?void 0:i.pageInfo.endCursor)||"null"};${(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}}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 I,w,h;let{cursor:n,repo:o}=t||{},i=K(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),p={fullPath:i,...a},d=await v(this.config,{query:`
876
876
  query getPullRequestsForRepo(
877
877
  $fullPath: ID!
878
878
  $after: String
@@ -902,7 +902,7 @@ query getPullRequestsForRepo(
902
902
  }
903
903
  }
904
904
  }
905
- `,variables:{...p,after:n}},e),c=[],g=(I=d.body.data)==null?void 0:I.project;if(!r&&(g!=null&&g.archived))return{pageInfo:null,data:[]};let m=Ae(g||{id:"",fullPath:"",webUrl:""});return(((P=g==null?void 0:g.mergeRequests)==null?void 0:P.nodes)||[]).forEach(R=>{c.push(fr(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!) {
905
+ `,variables:{...p,after:n}},e),c=[],g=(I=d.body.data)==null?void 0:I.project;if(!r&&(g!=null&&g.archived))return{pageInfo:null,data:[]};let m=Ue(g||{id:"",fullPath:"",webUrl:""});return(((w=g==null?void 0:g.mergeRequests)==null?void 0:w.nodes)||[]).forEach(R=>{c.push(fr(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!) {
906
906
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
907
907
  errors,
908
908
  mergeRequest {
@@ -974,11 +974,11 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
974
974
  fullPath
975
975
  webUrl
976
976
  issue(iid: $issueNumber) {
977
- ${Pt}
977
+ ${wt}
978
978
  }
979
979
  }
980
980
  }
981
- `,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:Et(n.body.data.project.issue,Ae(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 I,P,h;let{cursor:r,repo:n}=t||{},o=K(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:o,...i},p=`
981
+ `,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:Et(n.body.data.project.issue,Ue(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 I,w,h;let{cursor:r,repo:n}=t||{},o=K(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:o,...i},p=`
982
982
  query GetIssuesFromProject(
983
983
  $fullPath: ID!
984
984
  $after: String
@@ -998,7 +998,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
998
998
  ${u.length?u.join(" "):""}
999
999
  ) {
1000
1000
  nodes {
1001
- ${Pt}
1001
+ ${wt}
1002
1002
  }
1003
1003
  pageInfo {
1004
1004
  endCursor
@@ -1006,7 +1006,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1006
1006
  }
1007
1007
  }
1008
1008
  }
1009
- }`,d=await v(this.config,{query:p,variables:{...l,after:r}},e),c=[],g=(I=d.body.data)==null?void 0:I.project,m=Ae(g||{id:"",fullPath:"",webUrl:""});return(((P=g==null?void 0:g.issues)==null?void 0:P.nodes)||[]).forEach(R=>{c.push(Et(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,q)=>(R.updatedDate||R.createdDate).getTime()-(q.updatedDate||q.createdDate).getTime())}}async getIssuesForRepos(t,e={}){var g,m,f,I,P;let{cursor:r}=t||{},n=t.repoIds.map(h=>h.toString().startsWith(ie)?h:`${ie}${h}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(t),u={projectIds:n,...o},l=`
1009
+ }`,d=await v(this.config,{query:p,variables:{...l,after:r}},e),c=[],g=(I=d.body.data)==null?void 0:I.project,m=Ue(g||{id:"",fullPath:"",webUrl:""});return(((w=g==null?void 0:g.issues)==null?void 0:w.nodes)||[]).forEach(R=>{c.push(Et(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,q)=>(R.updatedDate||R.createdDate).getTime()-(q.updatedDate||q.createdDate).getTime())}}async getIssuesForRepos(t,e={}){var g,m,f,I,w;let{cursor:r}=t||{},n=t.repoIds.map(h=>h.toString().startsWith(ae)?h:`${ae}${h}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(t),u={projectIds:n,...o},l=`
1010
1010
  query GetIssuesFromProject(
1011
1011
  $projectIds: [ID!]
1012
1012
  $after: String
@@ -1032,12 +1032,12 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1032
1032
  ${a.length?a.join(" "):""}
1033
1033
  ) {
1034
1034
  nodes {
1035
- ${Pt}
1035
+ ${wt}
1036
1036
  }
1037
1037
  }
1038
1038
  }
1039
1039
  }
1040
- }`,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 G;if(!t.includeFromArchivedRepos&&h.archived)return;let R=Ae(h);(((G=h.issues)==null?void 0:G.nodes)||[]).forEach(S=>d.push(Et(S,R,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:((P=(I=(f=p.body)==null?void 0:f.data)==null?void 0:I.projects)==null?void 0:P.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!) {
1040
+ }`,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 G;if(!t.includeFromArchivedRepos&&h.archived)return;let R=Ue(h);(((G=h.issues)==null?void 0:G.nodes)||[]).forEach(S=>d.push(Et(S,R,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:((w=(I=(f=p.body)==null?void 0:f.data)==null?void 0:I.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!) {
1041
1041
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1042
1042
  issue {
1043
1043
  id
@@ -1086,7 +1086,7 @@ query getLabelsForRepo(
1086
1086
  }
1087
1087
  }
1088
1088
  }
1089
- `,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 f,I;return Ut(m,((I=(f=i.body.data)==null?void 0:f.project)==null?void 0:I.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:`
1089
+ `,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 f,I;return At(m,((I=(f=i.body.data)==null?void 0:f.project)==null?void 0:I.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:`
1090
1090
  query getLabelsForRepo(
1091
1091
  $fullPath: ID!
1092
1092
  $after: String
@@ -1105,5 +1105,5 @@ query getLabelsForRepo(
1105
1105
  }
1106
1106
  }
1107
1107
  }
1108
- `,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(At))??[]}}async getTreeForRepo(t,e={}){let r=K(t.repo),n=new URL(t.cursor??`${Ce(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(Os),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var _s="https://api.atlassian.com/ex/jira",Ue=100,Lt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Ir="/rest/api/2/search/jql",Rr="/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:Le(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[Le(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:Fs(s.fields.status),statusTransitions:((a=s.transitions)==null?void 0:a.map(Bs))??[],components:((u=s.fields.components)==null?void 0:u.map(Qs))??[],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(Ms),fixVersions:s.fields.fixVersions.map(zs)}},Bs=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}}},Qs=s=>({description:s.description??null,id:s.id,name:s.name}),js=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,Le=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:js(s,t,e)}),Fs=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}},Ms=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}),zs=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),X=(s,t,e)=>e?`${t.baseUrl||_s}/${e}`:`${(t==null?void 0:t.baseUrl)||s.baseUrl}`,$e=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${X(s,e,r)}/rest/api/2/field`,headers:y(e.token||s.token)})).body},Ge=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${X(s,r,o)}/rest/api/2/issue/${n}?fields=${Lt.join(",")}&expand=transitions`,headers:y(r.token||s.token)});return{data:$t(a.body,i,e,o)}},Te=async(s,t,e,r={})=>{let{page:n,resourceId:o,labelNames:i,fields:a}=t||{},u=n??0,l=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1109
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(I=>l.push(`labels = "${I}"`));let p=`${l.join(" AND ")} ORDER BY updated DESC`,c=!o?Rr:Ir,m=(await s.request({url:`${X(s,r,o)}${c}?jql=${p}&startAt=${u}&maxResults=${Ue}&fields=${Lt.join(",")}&expand=transitions`,headers:y(r.token||s.token)})).body.issues.map(I=>$t(I,a,e,o)),f=m.length==Ue;return{data:m,pageInfo:{hasNextPage:f,nextPage:f?u+m.length:null}}},yr=async(s,t,e,r={})=>{let{page:n,resourceId:o,jql:i,fields:a}=t||{},u=n??0,l=[...Lt],p=a==null?void 0:a.Sprint;p&&l.push(p);let c=!o?Rr:Ir,m=(await s.request({url:`${X(s,r,o)}${c}?jql=${i.join(" AND ")}&startAt=${u}&maxResults=${Ue}&fields=${l.join(",")}&expand=transitions`,headers:y(r.token||s.token)})).body.issues.map(I=>$t(I,a,e,o)),f=m.length==Ue;return{data:m,pageInfo:{hasNextPage:f,nextPage:f?u+m.length:null}}},Oe=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,page:u,projectKey:l,resourceId:p,fields:d}=t||{},c=u??0,g=[`project = "${l}"`,"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}"`)),yr(s,{resourceId:p,jql:g,page:c,fields:d},e,r)},ke=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,page:u,projectKeys:l,resourceId:p,fields:d}=t||{},c=u??0,m=["("+l.map(f=>`project = "${f}"`).join(" OR ")+")","statusCategory != Done"];return o&&m.push(`creator in ("${o}")`),n&&n.length!==0&&m.push(`assignee in ("${n.join('", "')}")`),i&&m.push(`comment ~ "${i}"`),a&&a.forEach(f=>m.push(`labels = "${f}"`)),yr(s,{resourceId:p,jql:m,fields:d,page:c},e,r)},xe=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:`${X(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"}})},Ne=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:`${X(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"}})},_e=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:`${X(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"}})},Be=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${X(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 ge="https://api.atlassian.com/ex/jira",Gt=100,ue=class extends N{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await $e(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||ge}/${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||ge}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Gt.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 Zt(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||ge}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Gt.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=>Le(p,a,!1))}}async getComponentsForJiraProject(e,r={}){return await Be(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 Ge(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 Oe(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 ke(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 Te(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await _e(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||ge}/${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 Ne(this.config,e,r)}async setIssueLabels(e,r={}){await xe(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||ge}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Gt.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 le=class extends Q{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 $e(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 Ge(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 Oe(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 ke(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 Te(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await _e(this.config,e,r)}async setIssueLabels(e,r={}){await xe(this.config,e,r)}async setIssueComponents(e,r={}){await Ne(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 Be(this.config,e,r)}};var j="https://api.trello.com",Ws=1e3,Hs=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),Js=(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}))}},pe=class extends N{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||j}/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||j}/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||j}/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||j}/1/members/${n}/?key=${r}&token=${e.token||this.config.token}`});return{data:Hs(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||j}/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||j}/1/search?key=${n}&query=${p}&cards_limit=${Ws}&token=${e.token||this.config.token}&card_members=true`,headers:y(e.token||this.config.token)})).body.cards.map(c=>Js(c,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||j}/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||j}/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||j}/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||j}/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 Qe={};B(Qe,{default:()=>Vs});var Vs={};var je={};B(je,{default:()=>Ks});var Ks={};var Fe={};B(Fe,{restApiPullRequestToCommonPullRequest:()=>Xs});var Xs=s=>ce(s);var tt={};B(tt,{decode:()=>Tt,decodeV0:()=>tn,encode:()=>en,validate:()=>Zs});var T=(e=>(e.Zero="0",e.One="1",e))(T||{}),O=(e=>(e.PullRequest="pr",e.Issue="issue",e))(O||{}),$=(p=>(p.Azure="azure",p.Github="github",p.GithubEnterprise="githubEnterprise",p.Gitlab="gitlab",p.GitlabSelfHosted="gitlabSelfHosted",p.Bitbucket="bitbucket",p.BitbucketServer="bitbucketServer",p.Jira="jira",p.JiraServer="jiraServer",p.Trello="trello",p))($||{});var Me=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("azure"),e.push("issue"),e.push("1"),e.push(t.domain||""),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 ze=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("azure"),e.push("pr"),e.push("1"),e.push(t.domain||""),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 We=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 He=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 Je=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 Ve=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 Ke=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 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 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 Ye=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 Ze=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 et=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":return t==="pr"?new ze:new Me;case"bitbucket":case"bitbucketServer":return t==="pr"?new He:new We;case"github":case"githubEnterprise":return t==="pr"?new Ve:new Je;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new Xe:new Ke;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Ye;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Ze;default:throw new Error("unknown provider")}},Ys=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")},Zs=s=>{if(s.version==="0"){Ys(s);return}et(s.provider,s.entityType).validate(s)},en=s=>et(s.provider,s.entityType).encode(s),Tt=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return et(t[0],t[1]).decode(t)},tn=(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 et(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 rt={};B(rt,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>qr,CHANGES_REQUESTED_BUCKET_ID:()=>Qt,CONFLICTS_ACTION_CATEGORY:()=>vr,CONFLICTS_BUCKET_ID:()=>_t,DRAFT_ACTION_CATEGORY:()=>Dr,DRAFT_BUCKET_ID:()=>Mt,FAILING_CI_ACTION_CATEGORY:()=>Pr,FAILING_CI_BUCKET_ID:()=>Nt,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Er,NEEDS_MY_REVIEW_BUCKET_ID:()=>Bt,OTHER_ACTION_CATEGORY:()=>Ar,OTHER_BUCKET_ID:()=>zt,PINNED_BUCKET_ID:()=>Ot,READY_TO_MERGE_ACTION_CATEGORY:()=>br,READY_TO_MERGE_BUCKET_ID:()=>kt,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>Sr,REVIEWER_COMMENTED_BUCKET_ID:()=>jt,SNOOZED_BUCKET_ID:()=>Wt,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>wr,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>xt,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>Cr,WAITING_FOR_REVIEW_BUCKET_ID:()=>Ft,getActionablePullRequests:()=>Ur,groupPullRequestsByAssignee:()=>nn,groupPullRequestsByAuthor:()=>on,groupPullRequestsByGitKrakenTeam:()=>pn,groupPullRequestsByRepo:()=>sn,groupPullRequestsByReviewer:()=>an,groupPullRequestsByWorkspace:()=>ln,groupPullRequestsIntoBuckets:()=>rn});var x=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Ot="pinned",kt="readyToMerge",xt="unassignedReviewers",Nt="failingCI",_t="conflicts",Bt="needsMyReview",Qt="changesRequested",jt="reviewerCommented",Ft="waitingForReview",Mt="draft",zt="other",Wt="snoozed",br="readyToMerge",wr="unassignedReviewers",Pr="failingCI",vr="conflicts",Er="needsMyReview",qr="changesRequested",Sr="reviewerCommented",Cr="waitingForReview",Dr="draft",Ar="other",Ur=(s,t,e)=>s.map(r=>{var u,l,p,d,c,g,m,f,I,P,h,R,q,G;let o={...r,...{suggestedActionCategory:Ar,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=((f=r.reviews)==null?void 0:f.filter(S=>S.state==="APPROVED").length)??0,o.changeRequestReviewCount=((I=r.reviews)==null?void 0:I.filter(S=>S.state==="CHANGES_REQUESTED").length)??0;let i=(P=e==null?void 0:e.enrichedItemsByUniqueId)==null?void 0:P[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=br),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=Dr),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=Cr,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=Sr),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Pr),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=vr),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=qr),(!t||o.viewer.isAuthor)&&!((q=r.reviews)!=null&&q.length)&&(o.suggestedActionCategory=wr,o.viewer.shouldAssignReviewer=!0),t&&((G=r.reviews)!=null&&G.some(S=>S.reviewer.id===t.id&&S.state==="REVIEW_REQUESTED"))&&(o.suggestedActionCategory=Er,o.viewer.shouldReview=!0),o}),rn=(s,t,e)=>{var i,a,u,l,p,d,c,g,m,f,I,P;let r={pinned:x(Ot,"Pinned","thumbtack",((i=e==null?void 0:e.bucketPriorityOverride)==null?void 0:i.pinned)??-1),readyToMerge:x(kt,"Ready to Merge","code-merge",((a=e==null?void 0:e.bucketPriorityOverride)==null?void 0:a.readyToMerge)??0),unassignedReviewers:x(xt,"Unassigned Reviewers","user-plus",((u=e==null?void 0:e.bucketPriorityOverride)==null?void 0:u.unassignedReviewers)??1),failingCI:x(Nt,"Failing CI","circle-x",((l=e==null?void 0:e.bucketPriorityOverride)==null?void 0:l.failingCI)??2),conflicts:x(_t,"Resolve Conflicts","triangle-exclamation",((p=e==null?void 0:e.bucketPriorityOverride)==null?void 0:p.conflicts)??3),needsMyReview:x(Bt,"Needs My Review","eye",((d=e==null?void 0:e.bucketPriorityOverride)==null?void 0:d.needsMyReview)??4),changesRequested:x(Qt,"Suggested Changes","file-plus",((c=e==null?void 0:e.bucketPriorityOverride)==null?void 0:c.changesRequested)??5),reviewerCommented:x(jt,"Reviewer Commented","comment",((g=e==null?void 0:e.bucketPriorityOverride)==null?void 0:g.reviewerCommented)??6),waitingForReview:x(Ft,"Waiting for Review","circle-pause",((m=e==null?void 0:e.bucketPriorityOverride)==null?void 0:m.waitingForReview)??7),draft:x(Mt,"Draft","compass-drafting",((f=e==null?void 0:e.bucketPriorityOverride)==null?void 0:f.draft)??8),other:x(zt,"Other","ellipsis",((I=e==null?void 0:e.bucketPriorityOverride)==null?void 0:I.other)??9),snoozed:x(Wt,"Snoozed","snooze",((P=e==null?void 0:e.bucketPriorityOverride)==null?void 0:P.snoozed)??10)},o=Ur(s,t,e).reduce((h,R)=>(h[R.uuid]=R,h),{});return s.forEach(h=>{let R=o[h.uuid],q=!0;if(R.viewer.snoozed){r[Wt].pullRequests.push(h);return}R.viewer.pinned&&r[Ot].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[kt].pullRequests.push(h),q=!1),R.viewer.shouldAssignReviewer&&(r[xt].pullRequests.push(h),q=!1),(!t||R.viewer.isAuthor)&&R.failingCI&&(r[Nt].pullRequests.push(h),q=!1),(!t||R.viewer.isAuthor)&&R.hasConflicts&&(r[_t].pullRequests.push(h),q=!1),R.viewer.shouldReview&&(r[Bt].pullRequests.push(h),q=!1),(!t||R.viewer.isAuthor)&&(R.reviewDecision==="CHANGES_REQUESTED"||R.codeSuggestionsCount>0)&&(r[Qt].pullRequests.push(h),q=!1),(!t||R.viewer.isAuthor)&&R.reviewDecision==="COMMENTED"&&(r[jt].pullRequests.push(h),q=!1),(!t||R.viewer.isAuthor)&&R.reviewDecision==="REVIEW_REQUESTED"&&(r[Ft].pullRequests.push(h),q=!1),R.isDraft&&(r[Mt].pullRequests.push(h),q=!1),q&&r[zt].pullRequests.push(h)}),Object.values(r).forEach(h=>{h.pullRequests.sort((R,q)=>o[R.uuid].priority-o[q.uuid].priority)}),r},sn=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}}),Z(t)},nn=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:he(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Z(e)},on=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:he(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),Z(e)},an=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:he(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Z(e)},un=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}`))??[]},ln=(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)=>(un(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Tt(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 Z(r)},pn=(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(f=>{var P,h;let I=(h=(P=t[f.id])==null?void 0:P[e])==null?void 0:h.providerID;return I&&u.has(I)})){a=!0;let f=c.id;o[f]?o[f].pullRequests.push(i):o[f]={name:c.name,priority:0,pullRequests:[i],id:f,teamData:c}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,Z(o)};var st={};B(st,{getPullRequestRank:()=>dn});var dn=(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 nt={};B(nt,{default:()=>cn});var cn={};var ot={};B(ot,{default:()=>gn});var gn={};var it={};B(it,{default:()=>mn});var mn={};var Lr=s=>{let t={request:s==null?void 0:s.request};return{azureDevOps:new te({...t,...s==null?void 0:s.azureDevOps}),bitbucket:new re({...t,...s==null?void 0:s.bitbucket}),bitbucketServer:new se({...t,...s==null?void 0:s.bitbucketServer}),github:new oe({...t,...s==null?void 0:s.github}),gitlab:new ae({...t,...s==null?void 0:s.gitlab}),jira:new ue({...t,...s==null?void 0:s.jira}),jiraServer:new le({...t,...s==null?void 0:s.jiraServer}),trello:new pe({...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 Gr=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(Gr||{});var hn=Lr;var fn={azureDevOps:Qe,bitbucket:je,bitbucketServer:Fe,github:st,gitlab:nt,gitProvider:rt,jira:ot,trello:it,entityIdentifier:tt};
1108
+ `,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(Ut))??[]}}async getTreeForRepo(t,e={}){let r=K(t.repo),n=new URL(t.cursor??`${Ce(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(Os),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var _s="https://api.atlassian.com/ex/jira",Ae=100,Lt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Ir="/rest/api/2/search/jql",Rr="/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:Le(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[Le(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:Fs(s.fields.status),statusTransitions:((a=s.transitions)==null?void 0:a.map(Bs))??[],components:((u=s.fields.components)==null?void 0:u.map(Qs))??[],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(Ms),fixVersions:s.fields.fixVersions.map(zs)}},Bs=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}}},Qs=s=>({description:s.description??null,id:s.id,name:s.name}),js=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,Le=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:js(s,t,e)}),Fs=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}},Ms=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}),zs=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),X=(s,t,e)=>e?`${t.baseUrl||_s}/${e}`:`${(t==null?void 0:t.baseUrl)||s.baseUrl}`,$e=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${X(s,e,r)}/rest/api/2/field`,headers:y(e.token||s.token)})).body},Ge=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${X(s,r,o)}/rest/api/2/issue/${n}?fields=${Lt.join(",")}&expand=transitions`,headers:y(r.token||s.token)});return{data:$t(a.body,i,e,o)}},Te=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1109
+ 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?Rr:Ir,c=new URL(`${X(s,r,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",Ae.toString()),c.searchParams.set("fields",Lt.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)),f=!1,I="";return p?(f=m.length==Ae,I=(parseInt(n??"0",10)+m.length).toString()):(f=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:f,endCursor:I}}},yr=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=[...Lt],l=a==null?void 0:a.Sprint;l&&u.push(l);let p=!o,d=p?Rr:Ir,c=new URL(`${X(s,r,o)}${d}`);c.searchParams.set("jql",i.join(" AND ")),c.searchParams.set("maxResults",Ae.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)),f=!1,I="";return p?(f=m.length==Ae,I=(parseInt(n??"0",10)+m.length).toString()):(f=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:f,endCursor:I}}},Oe=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}"`)),yr(s,{resourceId:p,jql:c,cursor:u,fields:d},e,r)},ke=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}"`)),yr(s,{resourceId:p,jql:g,fields:d,cursor:u},e,r)},xe=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:`${X(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"}})},Ne=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:`${X(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"}})},_e=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:`${X(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"}})},Be=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${X(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 me="https://api.atlassian.com/ex/jira",Gt=100,le=class extends N{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await $e(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||me}/${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||me}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Gt.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 Zt(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||me}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Gt.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=>Le(p,a,!1))}}async getComponentsForJiraProject(e,r={}){return await Be(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 Ge(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 Oe(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 ke(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 Te(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await _e(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||me}/${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 Ne(this.config,e,r)}async setIssueLabels(e,r={}){await xe(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||me}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Gt.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 pe=class extends Q{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 $e(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 Ge(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 Oe(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 ke(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 Te(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await _e(this.config,e,r)}async setIssueLabels(e,r={}){await xe(this.config,e,r)}async setIssueComponents(e,r={}){await Ne(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 Be(this.config,e,r)}};var j="https://api.trello.com",Ws=1e3,Hs=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),Js=(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}))}},de=class extends N{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||j}/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||j}/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||j}/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||j}/1/members/${n}/?key=${r}&token=${e.token||this.config.token}`});return{data:Hs(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||j}/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||j}/1/search?key=${n}&query=${p}&cards_limit=${Ws}&token=${e.token||this.config.token}&card_members=true`,headers:y(e.token||this.config.token)})).body.cards.map(c=>Js(c,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||j}/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||j}/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||j}/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||j}/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 Qe={};B(Qe,{default:()=>Vs});var Vs={};var je={};B(je,{default:()=>Ks});var Ks={};var Fe={};B(Fe,{restApiPullRequestToCommonPullRequest:()=>Xs});var Xs=s=>ge(s);var tt={};B(tt,{decode:()=>Tt,decodeV0:()=>tn,encode:()=>en,validate:()=>Zs});var T=(e=>(e.Zero="0",e.One="1",e))(T||{}),O=(e=>(e.PullRequest="pr",e.Issue="issue",e))(O||{}),$=(p=>(p.Azure="azure",p.Github="github",p.GithubEnterprise="githubEnterprise",p.Gitlab="gitlab",p.GitlabSelfHosted="gitlabSelfHosted",p.Bitbucket="bitbucket",p.BitbucketServer="bitbucketServer",p.Jira="jira",p.JiraServer="jiraServer",p.Trello="trello",p))($||{});var Me=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("azure"),e.push("issue"),e.push("1"),e.push(t.domain||""),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 ze=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("azure"),e.push("pr"),e.push("1"),e.push(t.domain||""),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 We=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 He=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 Je=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 Ve=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 Ke=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 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 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 Ye=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 Ze=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 et=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":return t==="pr"?new ze:new Me;case"bitbucket":case"bitbucketServer":return t==="pr"?new He:new We;case"github":case"githubEnterprise":return t==="pr"?new Ve:new Je;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new Xe:new Ke;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Ye;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Ze;default:throw new Error("unknown provider")}},Ys=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")},Zs=s=>{if(s.version==="0"){Ys(s);return}et(s.provider,s.entityType).validate(s)},en=s=>et(s.provider,s.entityType).encode(s),Tt=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return et(t[0],t[1]).decode(t)},tn=(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 et(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 rt={};B(rt,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>qr,CHANGES_REQUESTED_BUCKET_ID:()=>Qt,CONFLICTS_ACTION_CATEGORY:()=>vr,CONFLICTS_BUCKET_ID:()=>_t,DRAFT_ACTION_CATEGORY:()=>Dr,DRAFT_BUCKET_ID:()=>Mt,FAILING_CI_ACTION_CATEGORY:()=>wr,FAILING_CI_BUCKET_ID:()=>Nt,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Er,NEEDS_MY_REVIEW_BUCKET_ID:()=>Bt,OTHER_ACTION_CATEGORY:()=>Ur,OTHER_BUCKET_ID:()=>zt,PINNED_BUCKET_ID:()=>Ot,READY_TO_MERGE_ACTION_CATEGORY:()=>br,READY_TO_MERGE_BUCKET_ID:()=>kt,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>Sr,REVIEWER_COMMENTED_BUCKET_ID:()=>jt,SNOOZED_BUCKET_ID:()=>Wt,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Pr,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>xt,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>Cr,WAITING_FOR_REVIEW_BUCKET_ID:()=>Ft,getActionablePullRequests:()=>Ar,groupPullRequestsByAssignee:()=>nn,groupPullRequestsByAuthor:()=>on,groupPullRequestsByGitKrakenTeam:()=>pn,groupPullRequestsByRepo:()=>sn,groupPullRequestsByReviewer:()=>an,groupPullRequestsByWorkspace:()=>ln,groupPullRequestsIntoBuckets:()=>rn});var x=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Ot="pinned",kt="readyToMerge",xt="unassignedReviewers",Nt="failingCI",_t="conflicts",Bt="needsMyReview",Qt="changesRequested",jt="reviewerCommented",Ft="waitingForReview",Mt="draft",zt="other",Wt="snoozed",br="readyToMerge",Pr="unassignedReviewers",wr="failingCI",vr="conflicts",Er="needsMyReview",qr="changesRequested",Sr="reviewerCommented",Cr="waitingForReview",Dr="draft",Ur="other",Ar=(s,t,e)=>s.map(r=>{var u,l,p,d,c,g,m,f,I,w,h,R,q,G;let o={...r,...{suggestedActionCategory:Ur,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=((f=r.reviews)==null?void 0:f.filter(S=>S.state==="APPROVED").length)??0,o.changeRequestReviewCount=((I=r.reviews)==null?void 0:I.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=br),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=Dr),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=Cr,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=Sr),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=wr),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=vr),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=qr),(!t||o.viewer.isAuthor)&&!((q=r.reviews)!=null&&q.length)&&(o.suggestedActionCategory=Pr,o.viewer.shouldAssignReviewer=!0),t&&((G=r.reviews)!=null&&G.some(S=>S.reviewer.id===t.id&&S.state==="REVIEW_REQUESTED"))&&(o.suggestedActionCategory=Er,o.viewer.shouldReview=!0),o}),rn=(s,t,e)=>{var i,a,u,l,p,d,c,g,m,f,I,w;let r={pinned:x(Ot,"Pinned","thumbtack",((i=e==null?void 0:e.bucketPriorityOverride)==null?void 0:i.pinned)??-1),readyToMerge:x(kt,"Ready to Merge","code-merge",((a=e==null?void 0:e.bucketPriorityOverride)==null?void 0:a.readyToMerge)??0),unassignedReviewers:x(xt,"Unassigned Reviewers","user-plus",((u=e==null?void 0:e.bucketPriorityOverride)==null?void 0:u.unassignedReviewers)??1),failingCI:x(Nt,"Failing CI","circle-x",((l=e==null?void 0:e.bucketPriorityOverride)==null?void 0:l.failingCI)??2),conflicts:x(_t,"Resolve Conflicts","triangle-exclamation",((p=e==null?void 0:e.bucketPriorityOverride)==null?void 0:p.conflicts)??3),needsMyReview:x(Bt,"Needs My Review","eye",((d=e==null?void 0:e.bucketPriorityOverride)==null?void 0:d.needsMyReview)??4),changesRequested:x(Qt,"Suggested Changes","file-plus",((c=e==null?void 0:e.bucketPriorityOverride)==null?void 0:c.changesRequested)??5),reviewerCommented:x(jt,"Reviewer Commented","comment",((g=e==null?void 0:e.bucketPriorityOverride)==null?void 0:g.reviewerCommented)??6),waitingForReview:x(Ft,"Waiting for Review","circle-pause",((m=e==null?void 0:e.bucketPriorityOverride)==null?void 0:m.waitingForReview)??7),draft:x(Mt,"Draft","compass-drafting",((f=e==null?void 0:e.bucketPriorityOverride)==null?void 0:f.draft)??8),other:x(zt,"Other","ellipsis",((I=e==null?void 0:e.bucketPriorityOverride)==null?void 0:I.other)??9),snoozed:x(Wt,"Snoozed","snooze",((w=e==null?void 0:e.bucketPriorityOverride)==null?void 0:w.snoozed)??10)},o=Ar(s,t,e).reduce((h,R)=>(h[R.uuid]=R,h),{});return s.forEach(h=>{let R=o[h.uuid],q=!0;if(R.viewer.snoozed){r[Wt].pullRequests.push(h);return}R.viewer.pinned&&r[Ot].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[kt].pullRequests.push(h),q=!1),R.viewer.shouldAssignReviewer&&(r[xt].pullRequests.push(h),q=!1),(!t||R.viewer.isAuthor)&&R.failingCI&&(r[Nt].pullRequests.push(h),q=!1),(!t||R.viewer.isAuthor)&&R.hasConflicts&&(r[_t].pullRequests.push(h),q=!1),R.viewer.shouldReview&&(r[Bt].pullRequests.push(h),q=!1),(!t||R.viewer.isAuthor)&&(R.reviewDecision==="CHANGES_REQUESTED"||R.codeSuggestionsCount>0)&&(r[Qt].pullRequests.push(h),q=!1),(!t||R.viewer.isAuthor)&&R.reviewDecision==="COMMENTED"&&(r[jt].pullRequests.push(h),q=!1),(!t||R.viewer.isAuthor)&&R.reviewDecision==="REVIEW_REQUESTED"&&(r[Ft].pullRequests.push(h),q=!1),R.isDraft&&(r[Mt].pullRequests.push(h),q=!1),q&&r[zt].pullRequests.push(h)}),Object.values(r).forEach(h=>{h.pullRequests.sort((R,q)=>o[R.uuid].priority-o[q.uuid].priority)}),r},sn=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}}),Z(t)},nn=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:fe(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Z(e)},on=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:fe(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),Z(e)},an=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:fe(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Z(e)},un=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}`))??[]},ln=(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)=>(un(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Tt(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 Z(r)},pn=(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(f=>{var w,h;let I=(h=(w=t[f.id])==null?void 0:w[e])==null?void 0:h.providerID;return I&&u.has(I)})){a=!0;let f=c.id;o[f]?o[f].pullRequests.push(i):o[f]={name:c.name,priority:0,pullRequests:[i],id:f,teamData:c}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,Z(o)};var st={};B(st,{getPullRequestRank:()=>dn});var dn=(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 nt={};B(nt,{default:()=>cn});var cn={};var ot={};B(ot,{default:()=>gn});var gn={};var it={};B(it,{default:()=>mn});var mn={};var Lr=s=>{let t={request:s==null?void 0:s.request};return{azureDevOps:new te({...t,...s==null?void 0:s.azureDevOps}),bitbucket:new re({...t,...s==null?void 0:s.bitbucket}),bitbucketServer:new se({...t,...s==null?void 0:s.bitbucketServer}),github:new ie({...t,...s==null?void 0:s.github}),gitlab:new ue({...t,...s==null?void 0:s.gitlab}),jira:new le({...t,...s==null?void 0:s.jira}),jiraServer:new pe({...t,...s==null?void 0:s.jiraServer}),trello:new de({...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 Gr=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(Gr||{});var hn=Lr;var fn={azureDevOps:Qe,bitbucket:je,bitbucketServer:Fe,github:st,gitlab:nt,gitProvider:rt,jira:ot,trello:it,entityIdentifier:tt};