@gitkraken/provider-apis 0.29.9 → 0.30.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 ss=Object.create;var be=Object.defineProperty;var ns=Object.getOwnPropertyDescriptor;var is=Object.getOwnPropertyNames;var os=Object.getPrototypeOf,as=Object.prototype.hasOwnProperty;var j=(s,t)=>{for(var e in t)be(s,e,{get:t[e],enumerable:!0})},pr=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of is(t))!as.call(s,n)&&n!==e&&be(s,n,{get:()=>t[n],enumerable:!(r=ns(t,n))||r.enumerable});return s};var us=(s,t,e)=>(e=s!=null?ss(os(s)):{},pr(t||!s||!s.__esModule?be(e,"default",{value:s,enumerable:!0}):e,s)),ls=s=>pr(be({},"__esModule",{value:!0}),s);var Yn={};j(Yn,{AzureDevOps:()=>se,AzureDevopsUtils:()=>Xe,Bitbucket:()=>ne,BitbucketServer:()=>ie,BitbucketServerUtils:()=>qe,BitbucketUtils:()=>Ye,EntityIdentifierProviderType:()=>T,EntityIdentifierUtils:()=>pt,EntityType:()=>k,EntityVersion:()=>O,GitBuildStatusStage:()=>dr,GitBuildStatusState:()=>he,GitDiffLineType:()=>ft,GitHub:()=>ae,GitHubIssueCloseReason:()=>rs,GitHubUtils:()=>ct,GitIssueState:()=>Ce,GitLab:()=>le,GitLabUtils:()=>gt,GitMergeStrategy:()=>re,GitProviderUtils:()=>dt,GitPullRequestMergeableState:()=>W,GitPullRequestReviewState:()=>F,GitPullRequestState:()=>ee,GraphQLErrors:()=>P,Jira:()=>pe,JiraServer:()=>de,JiraUtils:()=>mt,Linear:()=>ce,PullRequestAsyncStatus:()=>ts,Trello:()=>ge,TrelloUtils:()=>ht,Utils:()=>Xn,default:()=>Kn,isFetch:()=>we});module.exports=ls(Yn);var dr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(dr||{}),he=(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))(he||{}),re=(i=>(i.MergeCommit="MERGE_COMMIT",i.Rebase="REBASE",i.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",i.FastForward="FAST_FORWARD",i.Squash="SQUASH",i))(re||{}),ee=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(ee||{}),F=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(F||{}),W=(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))(W||{}),ft=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(ft||{});var cr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},z=s=>!s||s.length===0?null:s.reduce((t,e)=>cr[e.state]>cr[t]?e.state:t,"APPROVED"),Pe=(s,t)=>s.name||s.username||s.email||t,te=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var L=100;var gr=us(require("node-fetch")),mr=globalThis.fetch||gr.default;var ps=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},It=s=>async({url:t,...e})=>{let r=await s(t,e);return ps(r)};var we=(s,t=!1)=>s.name==="fetch"||t;var B=class{constructor(t){let e=(t==null?void 0:t.request)||mr;this.config={...t,request:we(e,t==null?void 0:t.forceIsFetch)?It(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&we(t.request,(t==null?void 0:t.forceIsFetch)??this.config.forceIsFetch)?It(t.request):this.config.request}}},x=class extends B{};var y=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},hr=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,X=(s,t,e)=>!s||t.some(r=>s[r])?e:"",fr=async s=>{var n,i,o;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=((i=a==null?void 0:a.pageInfo)==null?void 0:i.endCursor)||((o=a==null?void 0:a.pageInfo)==null?void 0:o.nextPage)}return t};async function Rt(s){return(await Promise.allSettled(s)).map(e=>ds(e)).filter(e=>e!=null)}function ds(s,t=void 0){return(s==null?void 0:s.status)==="fulfilled"?s.value:t}var cs="https://app.vssps.visualstudio.com/_apis",gs="https://vssps.dev.azure.com/",ms="https://dev.azure.com",S=(s,t={})=>y(t.token||s.token,t.isPAT||s.isPAT),Ir=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/"),yt=(s,t)=>{let e=t.baseUrl||s.baseUrl||cs;return e=e.replace(/\/$/,""),e},C=(s,t)=>{let e=t.baseUrl||s.baseUrl||ms;return e=e.replace(/\/$/,""),e},bt=(s,t)=>{let e=t.baseUrl||s.baseUrl||gs;return e=e.replace(/\/$/,""),e};var hs={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},fs={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},Pt=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Ee=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Is=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"}},ve=(s,t)=>{var n;let e=[],r=[];return t.reviewers.forEach(i=>{let o={reviewer:Pt(i),state:fs[i.vote??0]||"REVIEW_REQUESTED"};i.isRequired&&e.push(o),r.push(o)}),{id:t.pullRequestId.toString(),title:t.title,number:t.codeReviewId,state:hs[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:Pt(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:Ee(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Ee(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:Ir(t),assignees:t.reviewers.map(Pt),reviews:r,reviewDecision:z(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:Is(t.mergeStatus),labels:((n=t.labels)==null?void 0:n.map(i=>({color:null,description:null,id:i.id,name:i.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:Ee(t.defaultBranch)}:null,permissions:null}),Rs=(s,t,e,r)=>{var l,p,d,c,g,m;let n=e.fields,i=n["System.AssignedTo"],o=n["System.State"],a=n["System.WorkItemType"],u;return o&&a&&(u=(l=r[a])==null?void 0:l[o]),{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:i?[{avatarUrl:((g=(c=i._links)==null?void 0:c.avatar)==null?void 0:g.href)??null,email:null,id:i.id,name:i.uniqueName??null,username:i.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:(u==null?void 0:u.title)||o,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,resourceId:null,key:null,id:null},upvoteCount:0,labels:((m=e.fields["System.Tags"])==null?void 0:m.split(";").map(I=>({color:null,description:null,id:null,name:I.trim()})))??[]}},se=class extends x{async getCurrentUser(t={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${yt(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:r,headers:S(this.config,e)});return{data:{id:n.body.id,name:n.body.displayName,username:n.body.displayName,email:n.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(t,e={}){let n=(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/ConnectionData`,headers:S(this.config,e)})).body.authorizedUser;if(n.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:n.id,name:n.providerDisplayName,username:n.providerDisplayName,email:n.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/commits/${t.oid}`,headers:S(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(t,e={}){let r=`${yt(this.config,e)}/accounts?memberId=${t.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:S(this.config,e)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(t,e={}){let r=`${C(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:S(this.config,e)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(t,e={}){let r=new URL(`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/projects`);r.searchParams.set("$top",L.toString()),t.cursor&&r.searchParams.set("$skip",t.cursor);let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),i=n.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:n.body.value.map(o=>({id:o.id,name:o.name,namespace:t.namespace}))}}async getAzureProjectScopeDescriptor(t,e={}){let{namespace:r,projectId:n}=t;return{data:{scope:(await this.config.request({url:`${bt(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:S(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(t,e={}){let{namespace:r,projectScopeDescriptor:n,cursor:i}=t,o=new URL(`${bt(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/users`);n&&o.searchParams.set("scopeDescriptor",n),i&&o.searchParams.set("continuationToken",i);let a=await this.config.request({url:o.toString(),headers:S(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:S(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 i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:n},e);r.push(i.data)}return{data:r}}async getRepo(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`,headers:S(this.config,e)});return{data:Rr(t.namespace,r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async i=>{try{let o=await this.getRepo(i,e);r.push(o.data)}catch(o){n.push({input:i,error:o})}})),{data:r,errors:n}}async getReposForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories`,headers:S(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(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",t),n.searchParams.set("$top",L.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let i=await this.config.request({url:n.toString(),headers:S(this.config,r)}),o=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:i.body.value.map(a=>({name:Ee(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:i,assigneeLogins:o,authorLogin:a}=t||{},u=n||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return o&&o.length&&(l+=`&searchCriteria.reviewerId=${o[0]}`),a&&(l+=`&searchCriteria.creatorId=${a}`),await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${l}&%24top=${r}&%24skip=${(u-1)*r}`,headers:S(this.config,e)})}async getPullRequestsForRepo(t,e={}){let n=t.page||1,i=await this.getPullRequestsForRepoBase(t,e,100);return{pageInfo:{hasNextPage:i.body.value.length===100,nextPage:n+1},data:i.body.value.map(o=>ve(t.repo.namespace,o))}}async getPullRequestsForRepos(t,e={}){if(!t.repos.every(i=>i.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 i=>{try{(await this.getPullRequestsForRepoBase({repo:i,...t},e)).body.value.forEach(a=>{n.push(ve(i.namespace,a))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:n}}async getPullRequestsForProjectBase(t,e={},r=100){let{namespace:n,project:i,page:o,assigneeLogins:a,authorLogin:u,repo:l}=t;if(l!=null&&l.project&&l.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let p=o||1,d=new URL(`${C(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",r.toString()),d.searchParams.set("$skip",((p-1)*r).toString()),l!=null&&l.id&&(l==null?void 0:l.project)===i&&d.searchParams.set("searchCriteria.repositoryId",l.id),a&&a.length&&d.searchParams.set("searchCriteria.reviewerId",a[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers:S(this.config,e)})}async getPullRequestsForProject(t,e={}){let n=t.page||1,i=await this.getPullRequestsForProjectBase(t,e,100);return{pageInfo:{hasNextPage:(i==null?void 0:i.body.value.length)===100,nextPage:n+1},data:(i==null?void 0:i.body.value.map(o=>ve(t.namespace,o)))||[]}}async getPullRequestsForProjects(t,e={}){let{projects:r}=t||{},n=[];return await Promise.all(r.map(async i=>{try{if(!t.repo||t.repo.project&&t.repo.project===i.project){let o=await this.getPullRequestsForProjectBase({...i,...t},e);o==null||o.body.value.forEach(a=>{n.push(ve(i.namespace,a))})}}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{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:i},pullRequestId:o}=t,a=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${i}/pullrequests/${o}?includeCommits=true?api-version=6.0`,headers:{...S(this.config,e)}});if(!a.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:a.body.mergeStatus}}async updatePullRequest(t,e,r){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}?api-version=6.0`,body:e,headers:{...S(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,i;switch(n){case"MERGE_COMMIT":{i="noFastForward";break}case"REBASE":{i="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{i="rebaseMerge";break}case"SQUASH":{i="squash";break}}let o={completionOptions:{mergeStrategy:i},lastMergeSourceCommit:{commitId:(u=r.headRef)==null?void 0:u.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(o),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 i={name:n.name};if(!(await this.config.request({method:"POST",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(t,e={}){let{pullRequest:r,label:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...S(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 i=r.labels;if(!i)throw new Error('Azure DevOps requires "labels" for this function.');for(let o of n)i.find(a=>a.id===o.id)||await this.addPullRequestLabel({pullRequest:r,label:o},e);for(let o of i)n.find(a=>o.id===a.id)||await this.removePullRequestLabel({pullRequest:r,label:o},e)}async setPullRequestAsDraft(t,e={}){let{pullRequest:r,isDraft:n}=t,i={isDraft:n};if(!(await this.updatePullRequest(r,JSON.stringify(i),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n,isRequired:i}=t,o={id:n.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(o),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n}=t;await this.config.request({method:"DELETE",url:`${C(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,headers:{...S(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;for(let i of n)r.assignees.find(o=>o.id===i.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:i,isRequired:!0},e);for(let i of r.assignees)n.find(o=>i.id===o.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:i},e)}async getIssuesForAzureProject(t,e={}){let{page:r,assigneeLogins:n,authorLogin:i,mentionLogin:o,labelNames:a,statusByWorkItemIdByStatusId:u}=t||{},l=r||1,p=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];i&&d.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),n&&n[0]&&d.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),o&&d.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(f=>d.push(`[System.Tags] Contains '${f}'`));let c=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...S(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(f=>f.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let I=await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...S(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:I.body.value.map(f=>Rs(t.namespace,t.project,f,u||{}))}}async getPermissionsForRepos(t,e={}){let{namespace:r,repos:n}=t,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},o=p=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${p.projectId}/${p.id}`;return Object.keys(i).map(g=>({securityNamespaceId:d,token:c,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(o)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,e)}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,I=i[d.permissions];for(let f of I)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][f]=!1);return p},{})}}async decorateReposWithPermissions(t,e={}){let{namespace:r,repos:n}=t,i=await this.getPermissionsForRepos({namespace:r,repos:n},e);return{data:n.map(o=>({...o,permissions:i.data[`${o.projectId}/${o.id}`]}))}}async updateIssue(t,e,r={}){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${encodeURIComponent(t.project.namespace)}/${encodeURIComponent(t.project.name)}/_apis/wit/workitems/${t.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...S(this.config,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(t,e={}){var a;let{issue:r,status:n}=t,i=[{op:"add",path:"/fields/System.State",value:n.name}];if(!((a=(await this.updateIssue(r,i,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,i=[{op:"add",path:"/fields/System.AssignedTo",value:(n==null?void 0:n.name)??""}];if(!((a=(await this.updateIssue(r,i,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,o=[{op:"replace",path:"/fields/System.Tags",value:n.map(l=>l.name).join(";")}];if(!((u=(await this.updateIssue(r,o,e)).body.fields)!=null&&u["System.Tags"]))throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...S(this.config,e)}})).body.value}}async getLabelsForProject(t,e={}){let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${C(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...S(this.config,e)}})).body.value.map(o=>({color:null,description:null,id:o.id,name:o.name,url:o.url}))}}};var U=(s,t={})=>y(t.token||s.token,t.isPAT||s.isPAT);var $="https://api.bitbucket.org/2.0",ys={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},Se=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}),yr=s=>{let t=s.links.clone,e=t==null?void 0:t.find(n=>n.name==="ssh"),r=t==null?void 0:t.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},br=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}},wt=s=>{var r;let t=s.id,e=((r=s.participants)==null?void 0:r.map(n=>{let i="REVIEW_REQUESTED";return n.approved?i="APPROVED":n.state==="changes_requested"?i="CHANGES_REQUESTED":n.participated_on!==null&&(i="COMMENTED"),{reviewer:Se(n.user),state:i}}))??[];return{id:t.toString(),title:s.title,number:t,state:ys[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:Se(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:yr(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:z(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:yr(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},bs=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},ne=class extends B{async refreshToken(t){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${$}/user`,headers:U(this.config,e)});return{data:Se(r.body)}}async getUserForCommit(t,e={}){var o;let n=(await this.config.request({url:`${$}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:U(this.config,e)})).body.author,i=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:i?i[1].trim():null,email:i?i[2]:null,avatarUrl:((o=n.user)==null?void 0:o.links.avatar.href)||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${$}/repositories/${t.namespace}/${t.name}`,headers:U(this.config,e)});return{data:br(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async i=>{try{let o=await this.getRepo(i,e);r.push(o.data)}catch(o){n.push({input:i,error:o})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=new URL(`${$}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",L.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),i=!!n.body.next,o=null;return n.body.next&&(o=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:i,endCursor:o},data:n.body.values.map(br)}}async getBranches(t,e={}){var o;let r=new URL(`${$}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",((o=t.page)==null?void 0:o.toString())||"1"),r.searchParams.set("pagelen",L.toString());let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),i=!!n.body.next;return{pageInfo:{hasNextPage:i,nextPage:i?n.body.page+1:null},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getTags(t,e={}){let r=new URL(`${$}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",L.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),i=!!n.body.next,o=null;return n.body.next&&(o=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:i,endCursor:o},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 o;let r=new URL(`${$}/user/permissions/workspaces`);r.searchParams.set("page",((o=t.page)==null?void 0:o.toString())||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),i=!!n.body.next;return{pageInfo:{hasNextPage:i,nextPage:i?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 o;let r=new URL(`${$}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);if(r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",((o=t.page)==null?void 0:o.toString())||"1"),r.searchParams.set("pagelen","50"),t.repos&&t.repos.length>0){let a=`state = "open" AND (${t.repos.map(u=>`source.repository.full_name = "${u.namespace}/${u.name}"`).join(" OR ")})`;r.searchParams.set("q",a)}let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),i=!!n.body.next;return{pageInfo:{hasNextPage:i,nextPage:i?n.body.page+1:null},data:n.body.values.map(wt)}}async getPullRequestsForRepoBase(t,e={}){var o;let r=new URL(`${$}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests?state=OPEN`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let i='state="OPEN"';return n.length&&(i+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",((o=t.page)==null?void 0:o.toString())||"1"),r.searchParams.set("pagelen","50"),r.searchParams.set("q",i),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(o=>{r.push(wt(o))});let i=!!n.body.next;return{pageInfo:{hasNextPage:i,nextPage:i?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(o=>{r.push(wt(o))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:r}}async getAccountsForWorkspace(t,e={}){var o;let r=new URL(`${$}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",((o=t.page)==null?void 0:o.toString())||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),i=!!n.body.next;return{pageInfo:{hasNextPage:i,nextPage:i?n.body.page+1:null},data:n.body.values.map(a=>Se(a.user))}}async getReposPermissionsForCurrentUser(t,e={}){var o;let r=new URL(`${$}/user/permissions/repositories`);r.searchParams.set("page",((o=t.page)==null?void 0:o.toString())||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),i=!!n.body.next;return{pageInfo:{hasNextPage:i,nextPage:i?n.body.page+1:null},data:n.body.values.reduce((a,u)=>({...a,[u.repository.uuid]:bs(u.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let i=await this.getReposPermissionsForCurrentUser({page:n},e);r={...i.data,...r},n=i.pageInfo.hasNextPage?i.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(i=>({...i,permissions:r[i.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${$}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:U(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,i;switch(n){case"MERGE_COMMIT":{i="merge_commit";break}case"FAST_FORWARD":{i="fast_forward";break}case"SQUASH":{i="squash";break}}let o={merge_strategy:i,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${$}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(o),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,i={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${$}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(i),headers:{...U(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var qe={};j(qe,{normalizePermissions:()=>vt,restApiPullRequestToCommonPullRequest:()=>Ps});var Ps=s=>fe(s),vt=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Ie=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},fe=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:Ie(m.user),state:e[m.status]})),n=((u=s.toRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:u.href)??null,i=((l=s.toRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:l.href)??null;i||(i=((p=s.toRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:p.href)??null);let o=((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:Ie(s.author.user),assignees:null,reviews:r,reviewDecision:z(r),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:i&&n?{cloneUrlHTTPS:i,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&o?{cloneUrlHTTPS:a,cloneUrlSSH:o}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},Pr=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}},ie=class extends x{getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return y(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":i}}=r,o=n?parseInt(n,10):null,a=decodeURIComponent(i),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${i}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>o?o===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Ie(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,i=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!i.body.author)throw new Error("Could not find user for commit");return{data:Ie(i.body.author)}}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:Pr(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async i=>{try{let o=await this.getRepo(i,e);r.push(o.data)}catch(o){n.push({input:i,error:o})}})),{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(Pr)}}async getRepoPermissionsForUsername(t,e={}){var n;let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let i=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:vt(i.body.values)}}catch(i){if(((n=i.response)==null?void 0:n.status)===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw i}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let i=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:i.data}}))}async getPullRequestsForRepoBase(t,e={}){var n;let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests?state=OPEN`);return r.searchParams.set("start",((n=t.page)==null?void 0:n.toString())||"0"),r.searchParams.set("limit","50"),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(o=>{if(t.authorLogin&&o.author.user.name!==t.authorLogin)return null;r.push(fe(o))});let i=n.body.values.length!==0;return{pageInfo:{hasNextPage:i,nextPage:i?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(o=>{if(t.authorLogin&&o.author.user.name!==t.authorLogin)return null;r.push(fe(o))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:r}}async getPullRequestsForCurrentUser(t,e={}){var o;let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state","OPEN"),r.searchParams.set("start",((o=t.page)==null?void 0:o.toString())||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),i=n.body.values.length!==0;return{pageInfo:{hasNextPage:i,nextPage:i?n.body.start+n.body.values.length:null},data:n.body.values.map(fe)}}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 i={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(i),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(t,e={}){var o;let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",((o=t.page)==null?void 0:o.toString())||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),i=n.body.values.length!==0;return{pageInfo:{hasNextPage:i,nextPage:i?n.body.start+n.body.values.length:null},data:n.body.values.map(a=>Ie(a.user))}}};var Dr=require("js-base64");var Ce=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Ce||{});var P=class extends Error{constructor(e,r){let n=r==null?void 0:r.map(o=>`'${o.message}'`).join(", "),i=n?`${e}: ${n}`:e;super(i);this.graphQLErrors=r??[]}};var ws={AS_CODE_OWNER:[3,0,0],CHECK_RUN:[3,0,0],LATEST_REVIEWS:[3,0,0],VIEWER_CAN_MERGE_AS_ADMIN:[3,5,0],ISSUE_FULL_DATABASE_ID:[3,12,0],PR_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_COMMENT_FULL_DATABASE_ID:[3,13,0]},wr=15,vr=100,G=s=>!!s,H=(s,t)=>{let e=ws[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Ae="https://api.github.com",vs=`${Ae}/graphql`,Le=`
1
+ "use strict";var ct=Object.defineProperty;var is=Object.getOwnPropertyDescriptor;var as=Object.getOwnPropertyNames;var us=Object.prototype.hasOwnProperty;var x=(s,t)=>{for(var e in t)ct(s,e,{get:t[e],enumerable:!0})},ls=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of as(t))!us.call(s,n)&&n!==e&&ct(s,n,{get:()=>t[n],enumerable:!(r=is(t,n))||r.enumerable});return s};var ps=s=>ls(ct({},"__esModule",{value:!0}),s);var ro={};x(ro,{AzureDevOps:()=>Z,AzureDevopsUtils:()=>He,Bitbucket:()=>ee,BitbucketServer:()=>te,BitbucketServerUtils:()=>we,BitbucketUtils:()=>Je,EntityIdentifierProviderType:()=>D,EntityIdentifierUtils:()=>it,EntityType:()=>L,EntityVersion:()=>A,GitBuildStatusStage:()=>ur,GitBuildStatusState:()=>ce,GitDiffLineType:()=>gt,GitHub:()=>se,GitHubIssueCloseReason:()=>ns,GitHubUtils:()=>ut,GitIssueState:()=>ve,GitLab:()=>oe,GitLabUtils:()=>lt,GitMergeStrategy:()=>Y,GitProviderUtils:()=>at,GitPullRequestMergeableState:()=>Q,GitPullRequestReviewState:()=>N,GitPullRequestState:()=>K,GraphQLErrors:()=>f,Jira:()=>ie,JiraServer:()=>ae,JiraUtils:()=>pt,Linear:()=>ue,PullRequestAsyncStatus:()=>ss,Trello:()=>le,TrelloUtils:()=>dt,Utils:()=>to,default:()=>eo,isFetch:()=>Re});module.exports=ps(ro);var ur=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(ur||{}),ce=(c=>(c.ActionRequired="ACTION_REQUIRED",c.Cancelled="CANCELLED",c.Error="ERROR",c.Failed="FAILED",c.Pending="PENDING",c.Running="RUNNING",c.Skipped="SKIPPED",c.Success="SUCCESS",c.Warning="WARNING",c.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",c))(ce||{}),Y=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(Y||{}),K=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(K||{}),N=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(N||{}),Q=(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))(Q||{}),gt=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(gt||{});var lr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},_=s=>!s||s.length===0?null:s.reduce((t,e)=>lr[e.state]>lr[t]?e.state:t,"APPROVED"),Ie=(s,t)=>s.name||s.username||s.email||t,X=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 v=100;var pr=globalThis.fetch;var ds=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):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={};s.headers.forEach((o,i)=>{r[i]=o});let n={body:e,headers:r,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},mt=s=>async({url:t,...e})=>{let r=await s(t,e);return ds(r)};var Re=(s,t=!1)=>s.name==="fetch"||t;var O=class{constructor(t){let e=t?.request||pr;this.config={...t,request:Re(e,t?.forceIsFetch)?mt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&Re(t.request,t?.forceIsFetch??this.config.forceIsFetch)?mt(t.request):this.config.request}}},U=class extends O{};var h=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},dr=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,H=(s,t,e)=>!s||t.some(r=>s[r])?e:"",cr=async s=>{let t=[],e=!0,r;for(;e;){let n=await s(r);t=t.concat(n.data),e=!!n?.pageInfo?.hasNextPage,r=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return t};async function ht(s){return(await Promise.allSettled(s)).map(e=>cs(e)).filter(e=>e!=null)}function cs(s,t=void 0){return s?.status==="fulfilled"?s.value:t}var gs="https://app.vssps.visualstudio.com/_apis",ms="https://vssps.dev.azure.com/",hs="https://dev.azure.com",P=(s,t={})=>h(t.token||s.token,t.isPAT||s.isPAT),gr=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/"),ft=(s,t)=>{let e=t.baseUrl||s.baseUrl||gs;return e=e.replace(/\/$/,""),e},w=(s,t)=>{let e=t.baseUrl||s.baseUrl||hs;return e=e.replace(/\/$/,""),e},It=(s,t)=>{let e=t.baseUrl||s.baseUrl||ms;return e=e.replace(/\/$/,""),e};var fs={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Is={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},Rt=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),be=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Rs=s=>{switch(s){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},ye=(s,t)=>{let e=[],r=[];return t.reviewers.forEach(n=>{let o={reviewer:Rt(n),state:Is[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),r.push(o)}),{id:t.pullRequestId.toString(),title:t.title,number:t.codeReviewId,state:fs[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:Rt(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:be(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:be(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:gr(t),assignees:t.reviewers.map(Rt),reviews:r,reviewDecision:_(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:null}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:Rs(t.mergeStatus),labels:t.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},mr=(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:be(t.defaultBranch)}:null,permissions:null}),ys=(s,t,e,r)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=r[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.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:o._links?.avatar?.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?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},Z=class extends U{async getCurrentUser(t={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${ft(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:r,headers:P(this.config,e)});return{data:{id:n.body.id,name:n.body.displayName,username:n.body.displayName,email:n.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(t,e={}){let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/ConnectionData`,headers:P(this.config,e)})).body.authorizedUser;if(n.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:n.id,name:n.providerDisplayName,username:n.providerDisplayName,email:n.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/commits/${t.oid}`,headers:P(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(t,e={}){let r=`${ft(this.config,e)}/accounts?memberId=${t.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:P(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(t,e={}){let r=`${w(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:P(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(t,e={}){let r=new URL(`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/projects`);r.searchParams.set("$top",v.toString()),t.cursor&&r.searchParams.set("$skip",t.cursor);let n=await this.config.request({url:r.toString(),headers:P(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:`${It(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:P(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(t,e={}){let{namespace:r,projectScopeDescriptor:n,cursor:o}=t,i=new URL(`${It(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/users`);n&&i.searchParams.set("scopeDescriptor",n),o&&i.searchParams.set("continuationToken",o);let a=await this.config.request({url:i.toString(),headers:P(this.config,e)}),u=a.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:a.body.value.map(l=>({avatarUrl:l._links?.avatar?.href??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:l._links?.storageKey?.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:P(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:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`,headers:P(this.config,e)});return{data:mr(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:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories`,headers:P(this.config,e)})).body.value.map(n=>mr(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(`${w(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",t),n.searchParams.set("$top",v.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:P(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:be(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:`${w(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${r}&%24skip=${(u-1)*r}`,headers:P(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=>ye(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(ye(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(t,e={},r=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=t;if(l?.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let c=i||1,p=new URL(`${w(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return p.searchParams.set("searchCriteria.status","1"),p.searchParams.set("$top",r.toString()),p.searchParams.set("$skip",((c-1)*r).toString()),l?.id&&l?.project===o&&p.searchParams.set("searchCriteria.repositoryId",l.id),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:P(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=>ye(t.namespace,i))||[]}}async getPullRequestsForProjects(t,e={}){let{projects:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(!t.repo||t.repo.project&&t.repo.project===o.project)&&(await this.getPullRequestsForProjectBase({...o,...t},e))?.body.value.forEach(a=>{n.push(ye(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:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...P(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:`${w(this.config,r)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}?api-version=6.0`,body:e,headers:{...P(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={}){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:r.headRef?.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:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels?api-version=6.0`,body:JSON.stringify(o),headers:{...P(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:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...P(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:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(i),headers:{...P(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:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,headers:{...P(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,c=200,p=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&p.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),n&&n[0]&&p.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),i&&p.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(R=>p.push(`[System.Tags] Contains '${R}'`));let d=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${p.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:d}),method:"POST",headers:{...P(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*c,c*l).map(R=>R.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let y=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...P(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>c*l,nextPage:l+1},data:y.body.value.map(R=>ys(t.namespace,t.project,R,u||{}))}}async getPermissionsForRepos(t,e={}){let{namespace:r,repos:n}=t,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},i=c=>{let p="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",d=`repoV2/${c.projectId}/${c.id}`;return Object.keys(o).map(g=>({securityNamespaceId:p,token:d,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(i)};return{data:(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((c,p)=>{let[,d,g]=p.token.split("/"),m=`${d}/${g}`,y=o[p.permissions];for(let R of y)c[m]===void 0&&(c[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),p.value===!1&&(c[m][R]=!1);return c},{})}}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:`${w(this.config,r)}/${encodeURIComponent(t.project.namespace)}/${encodeURIComponent(t.project.name)}/_apis/wit/workitems/${t.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...P(this.config,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(t,e={}){let{issue:r,status:n}=t,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!(await this.updateIssue(r,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(t,e={}){let{issue:r,assignee:n}=t,o=[{op:"add",path:"/fields/System.AssignedTo",value:n?.name??""}];if(!(await this.updateIssue(r,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(t,e={}){let{issue:r,labels:n}=t,i=[{op:"replace",path:"/fields/System.Tags",value:n.map(u=>u.name).join(";")}];if(!(await this.updateIssue(r,i,e)).body.fields?.["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:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...P(this.config,e)}})).body.value}}async getLabelsForProject(t,e={}){let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...P(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}};var S=(s,t={})=>h(t.token||s.token,t.isPAT||s.isPAT);var q="https://api.bitbucket.org/2.0",bs={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},Pe=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}),hr=s=>{let t=s.links.clone,e=t?.find(n=>n.name==="ssh"),r=t?.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},fr=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(t=>t.name==="https")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),yt=s=>{let t=s.id,e=s.participants?.map(r=>{let n="REVIEW_REQUESTED";return r.approved?n="APPROVED":r.state==="changes_requested"?n="CHANGES_REQUESTED":r.participated_on!==null&&(n="COMMENTED"),{reviewer:Pe(r.user),state:n}})??[];return{id:t.toString(),title:s.title,number:t,state:bs[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:Pe(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:hr(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:_(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:hr(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Ps=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}}},ee=class extends O{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:`${q}/user`,headers:S(this.config,e)});return{data:Pe(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${q}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:S(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${q}/repositories/${t.namespace}/${t.name}`,headers:S(this.config,e)});return{data:fr(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(`${q}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",v.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:S(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(fr)}}async getBranches(t,e={}){let r=new URL(`${q}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",v.toString());let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(t,e={}){let r=new URL(`${q}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",v.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:S(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={}){let r=new URL(`${q}/user/permissions/workspaces`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){let r=new URL(`${q}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);if(r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t.repos&&t.repos.length>0){let i=`state = "open" AND (${t.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;r.searchParams.set("q",i)}let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(yt)}}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${q}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests?state=OPEN`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50"),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:S(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{r.push(yt(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{r.push(yt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${q}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>Pe(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${q}/user/permissions/repositories`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:S(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:Ps(a.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:`${q}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:S(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:`${q}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...S(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:`${q}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var we={};x(we,{normalizePermissions:()=>bt,restApiPullRequestToCommonPullRequest:()=>ws});var ws=s=>ge(s),bt=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var me=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},ge=s=>{let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(u=>({reviewer:me(u.user),state:e[u.status]})),n=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.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:me(s.author.user),assignees:null,reviews:r,reviewDecision:_(r),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},Ir=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(t=>t.name==="https"||t.name==="http")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),te=class extends U{getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return h(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:c,id:p,name:d,slug:g})=>i?i===p:a===d||a===c||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:me(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:me(o.body.author)}}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:Ir(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(Ir)}}async getRepoPermissionsForUsername(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:bt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){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",t.page?.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={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state","OPEN"),r.searchParams.set("start",t.page?.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")}async getAccountsForProject(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",t.page?.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(i=>me(i.user))}}};var Er=require("js-base64");var ve=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ve||{});var f=class extends Error{constructor(e,r){let n=r?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var vs={AS_CODE_OWNER:[3,0,0],CHECK_RUN:[3,0,0],LATEST_REVIEWS:[3,0,0],VIEWER_CAN_MERGE_AS_ADMIN:[3,5,0],ISSUE_FULL_DATABASE_ID:[3,12,0],PR_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_COMMENT_FULL_DATABASE_ID:[3,13,0]},Rr=15,yr=100,C=s=>!!s,j=(s,t)=>{let e=vs[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Se="https://api.github.com",Es=`${Se}/graphql`,qe=`
2
2
  description
3
3
  dueOn
4
4
  id
@@ -6,7 +6,7 @@ number
6
6
  state
7
7
  title
8
8
  url
9
- `,Es=`
9
+ `,Ss=`
10
10
  ... on CheckRun {
11
11
  completedAt
12
12
  conclusion
@@ -15,62 +15,62 @@ url
15
15
  permalink
16
16
  startedAt
17
17
  }
18
- `,De=/\/api\/v\d+$/,Ue=`
18
+ `,Ee=/\/api\/v\d+$/,Ce=`
19
19
  color
20
20
  description
21
21
  id
22
22
  name
23
- `,Er=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.")},Ss=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Er(e),De.test(e)&&(e=e.replace(De,"")),`${e}/api/graphql`):vs},oe=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Er(e),De.test(e)&&(e=e.replace(De,"")),`${e}/api/v3`):Ae},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:Ss(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},qs={user:!0,"user:email":!0,"read:user":!0},J=s=>s.some(t=>qs[t]),N=(s=!1,t=!1,e)=>`
23
+ `,br=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},qs=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),br(e),Ee.test(e)&&(e=e.replace(Ee,"")),`${e}/api/graphql`):Es},re=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),br(e),Ee.test(e)&&(e=e.replace(Ee,"")),`${e}/api/v3`):Se},I=(s,t,e)=>{let r=h(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:qs(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},Cs={user:!0,"user:email":!0,"read:user":!0},F=s=>s.some(t=>Cs[t]),$=(s=!1,t=!1,e)=>`
24
24
  __typename
25
- ${X(e,["graphQLId"],"id")}
26
- ${X(e,["id"],"databaseId")}
27
- ${X(e,["name"],"name")}
28
- ${X(e,["name","username"],"login")}
29
- ${t?X(e,["email"],"email"):""}
30
- ${X(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
31
- ${X(e,["url"],"url")}
32
- `,Cs=(s=!1)=>`
25
+ ${H(e,["graphQLId"],"id")}
26
+ ${H(e,["id"],"databaseId")}
27
+ ${H(e,["name"],"name")}
28
+ ${H(e,["name","username"],"login")}
29
+ ${t?H(e,["email"],"email"):""}
30
+ ${H(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
31
+ ${H(e,["url"],"url")}
32
+ `,Ds=(s=!1)=>`
33
33
  latestReviews(first: 100) {
34
34
  nodes {
35
35
  author {
36
36
  ... on User {
37
- ${N(!1,s)}
37
+ ${$(!1,s)}
38
38
  }
39
39
  ... on EnterpriseUserAccount {
40
- ${Et(!1)}
40
+ ${Pt(!1)}
41
41
  }
42
42
  }
43
43
  state
44
44
  }
45
45
  }
46
- `,Sr=(s=!1)=>`
46
+ `,Pr=(s=!1)=>`
47
47
  __typename
48
48
  id
49
49
  databaseId
50
50
  login
51
51
  avatarUrl${s?"(size: $avatarSize)":""}
52
52
  url
53
- `,Et=(s=!1)=>`
53
+ `,Pt=(s=!1)=>`
54
54
  __typename
55
55
  id
56
56
  login
57
57
  avatarUrl${s?"(size: $avatarSize)":""}
58
58
  url
59
- `,$e=(s,t=!1,e)=>`
59
+ `,De=(s,t=!1,e)=>`
60
60
  id
61
- ${!e||H(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
61
+ ${!e||j(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
62
62
  number
63
63
  title
64
64
  state
65
65
  author {
66
66
  ... on User {
67
- ${N(!1,t)}
67
+ ${$(!1,t)}
68
68
  }
69
69
  ... on Bot {
70
- ${Sr(!1)}
70
+ ${Pr(!1)}
71
71
  }
72
72
  ... on EnterpriseUserAccount {
73
- ${Et(!1)}
73
+ ${Pt(!1)}
74
74
  }
75
75
  }
76
76
  commits(last: 1) {
@@ -83,7 +83,7 @@ commits(last: 1) {
83
83
  contexts(first: 100) {
84
84
  totalCount
85
85
  nodes {
86
- ${!e||H(e,"CHECK_RUN")?Es:""}
86
+ ${!e||j(e,"CHECK_RUN")?Ss:""}
87
87
  ... on StatusContext {
88
88
  context
89
89
  createdAt
@@ -145,47 +145,47 @@ closedAt
145
145
  mergedAt
146
146
  assignees(first: 100) {
147
147
  nodes {
148
- ${N(!1,t)}
148
+ ${$(!1,t)}
149
149
  }
150
150
  }
151
151
  reviewRequests(first: 100) {
152
152
  nodes {
153
- ${!e||H(e,"AS_CODE_OWNER")?"asCodeOwner":""}
153
+ ${!e||j(e,"AS_CODE_OWNER")?"asCodeOwner":""}
154
154
  requestedReviewer {
155
155
  ... on User {
156
- ${N(!1,t)}
156
+ ${$(!1,t)}
157
157
  }
158
158
  }
159
159
  }
160
160
  }
161
- ${!e||H(e,"LATEST_REVIEWS")?Cs(t):""}
161
+ ${!e||j(e,"LATEST_REVIEWS")?Ds(t):""}
162
162
  additions
163
163
  deletions
164
164
  changedFiles
165
165
  mergeable
166
166
  mergeStateStatus
167
167
  milestone {
168
- ${Le}
168
+ ${qe}
169
169
  }
170
170
  labels(first: 100) {
171
171
  nodes {
172
- ${Ue}
172
+ ${Ce}
173
173
  }
174
174
  }
175
- ${!e||H(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
176
- `,Ds=(s=!1,t)=>`
175
+ ${!e||j(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
176
+ `,As=(s=!1,t)=>`
177
177
  id
178
- ${!t||H(t,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
178
+ ${!t||j(t,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
179
179
  title
180
180
  author {
181
181
  ... on User {
182
- ${N(!1,s)}
182
+ ${$(!1,s)}
183
183
  }
184
184
  ... on Bot {
185
- ${Sr(!1)}
185
+ ${Pr(!1)}
186
186
  }
187
187
  ... on EnterpriseUserAccount {
188
- ${Et(!1)}
188
+ ${Pt(!1)}
189
189
  }
190
190
  }
191
191
  closedAt
@@ -209,19 +209,19 @@ comments {
209
209
  }
210
210
  assignees(first: 100) {
211
211
  nodes {
212
- ${N(!1,s)}
212
+ ${$(!1,s)}
213
213
  }
214
214
  }
215
215
  state
216
216
  milestone {
217
- ${Le}
217
+ ${qe}
218
218
  }
219
219
  labels(first: 100) {
220
220
  nodes {
221
- ${Ue}
221
+ ${Ce}
222
222
  }
223
223
  }
224
- `,As={"-linked":"-linked",archived:"archived",assignee:"assignee",author:"author",base:"base",closed:"closed",commenter:"commenter",comments:"comments",created:"created",draft:"draft",head:"head",label:"label",language:"language",linked:"linked",in:"in",interactions:"interactions",involves:"involves",is:"is",mentions:"mentions",merged:"merged",milestone:"milestone",no:"no",org:"org",project:"project",reactions:"reactions",repo:"repo",review:"review","reviewed-by":"reviewed-by","review-requested":"review-requested",state:"state",status:"status",team:"team","team-review-requested":"team-review-requested",type:"type",updated:"updated",user:"user","user-review-requested":"user-review-requested"},Ls=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),St=s=>{let t=[];return(s.match(Ls)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];As[n]&&t.push(r)}}),t},qt=(s,t,e,r)=>{let n=s==="issue";return{query:`
224
+ `,Ls={"-linked":"-linked",archived:"archived",assignee:"assignee",author:"author",base:"base",closed:"closed",commenter:"commenter",comments:"comments",created:"created",draft:"draft",head:"head",label:"label",language:"language",linked:"linked",in:"in",interactions:"interactions",involves:"involves",is:"is",mentions:"mentions",merged:"merged",milestone:"milestone",no:"no",org:"org",project:"project",reactions:"reactions",repo:"repo",review:"review","reviewed-by":"reviewed-by","review-requested":"review-requested",state:"state",status:"status",team:"team","team-review-requested":"team-review-requested",type:"type",updated:"updated",user:"user","user-review-requested":"user-review-requested"},Us=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),wt=s=>{let t=[];return(s.match(Us)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];Ls[n]&&t.push(r)}}),t},vt=(s,t,e,r)=>{let n=s==="issue";return{query:`
225
225
  query SearchIssuesOrPullRequests($query: String! $after: String) {
226
226
  search(type:ISSUE query:$query first: ${r.maxPageSize} after:$after) {
227
227
  pageInfo {
@@ -230,18 +230,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
230
230
  }
231
231
  nodes {
232
232
  ... on ${n?"Issue":"PullRequest"} {
233
- ${n?Ds(r.supportsEmail,r.enterpriseVersion??null):$e(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
233
+ ${n?As(r.supportsEmail,r.enterpriseVersion??null):De(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
234
234
  }
235
235
  }
236
236
  }
237
- }`,variables:{query:`is:${s} is:open ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},Us="Field 'isDraft' doesn't exist on type 'PullRequest'",Ge=(s=[])=>s.some(t=>(t==null?void 0:t.message)===Us),$s=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Gs=`
237
+ }`,variables:{query:`is:${s} is:open ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},$s="Field 'isDraft' doesn't exist on type 'PullRequest'",Ae=(s=[])=>s.some(t=>t?.message===$s),Gs=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Ts=`
238
238
  \
239
- +`,qr=(s,t,e,r)=>{let n=$s.exec(s);if(!n||!n[0]||!n[1])return[];let i=parseInt(n[1],10),o=parseInt(n[2],10),a=s.replace(Gs,`
239
+ +`,wr=(s,t,e,r)=>{let n=Gs.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(Ts,`
240
240
  +`).split(`
241
- `).slice(1),u=i-1,l=o-1,p=a.map(g=>{let m,I;switch(g[0]){case"-":{m="DELETED",u+=1,I=`${g.slice(1)}
242
- `;break}case"+":{m="ADDED",l+=1,I=`${g.slice(1)}
243
- `;break}default:m="UNMODIFIED",l+=1,u+=1,I=`${g}
244
- `}return{line:I,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=t;if(d!==null&&c!==null&&r!==null&&d<c){let g=0,m=p.length,I=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let f=0;f<p.length;f++){let h=p[f][I];h===d?g=f:h===c&&(m=f)}p=p.slice(g,m+1)}return p};var Ct=`
241
+ `).slice(1),u=o-1,l=i-1,c=a.map(g=>{let m,y;switch(g[0]){case"-":{m="DELETED",u+=1,y=`${g.slice(1)}
242
+ `;break}case"+":{m="ADDED",l+=1,y=`${g.slice(1)}
243
+ `;break}default:m="UNMODIFIED",l+=1,u+=1,y=`${g}
244
+ `}return{line:y,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),p=e,d=t;if(p!==null&&d!==null&&r!==null&&p<d){let g=0,m=c.length,y=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let R=0;R<c.length;R++){let pe=c[R][y];pe===p?g=R:pe===d&&(m=R)}c=c.slice(g,m+1)}return c};var Et=`
245
245
  id
246
246
  databaseId
247
247
  owner {
@@ -254,18 +254,18 @@ defaultBranchRef {
254
254
  name
255
255
  }
256
256
  viewerPermission
257
- `,Lt={__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"},Ts={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Os={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},ks={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},xs={OPEN:"OPEN",CLOSED:"CLOSED"},Ns=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Ut=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),_s=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Dt=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:_s(s.viewerPermission)}),Bs=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),Cr=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:Bs(s.permissions)}),Qs=s=>({path:s.path,isDirectory:s.type==="tree"}),js={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Fs={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},Q=(s,t=Fs)=>{let e={};return t.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),t.graphQLId&&(e.graphQLId=s.id),t.name&&(e.name=s.name??s.login),t.username&&(e.username=s.login),t.email&&(e.email=s.email??null),t.avatarUrl&&(e.avatarUrl=s.avatarUrl),t.url&&(e.url=s.url),e},zs=(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]},Ms=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],At=s=>{var o,a,u,l,p,d,c,g,m,I,f,b;let t=null;s.author?t=s.author:t=Lt;let e=(((o=s.reviewRequests)==null?void 0:o.nodes)||[]).filter(G).filter(h=>!h.asCodeOwner),r=(a=s.headRepository)==null?void 0:a.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=(u=s.repository)==null?void 0:u.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let i=e.filter(h=>h.requestedReviewer&&"__typename"in h.requestedReviewer).map(h=>({reviewer:Q(h.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((((l=s.latestReviews)==null?void 0:l.nodes)||[]).filter(G).map(h=>{let R=Lt;return h.author&&h.author.__typename&&(R=h.author),{reviewer:Q(R),state:Ts[h.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,number:s.number,state:js[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?Q(t):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:s.repository.sshUrl}},headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:((g=(c=(d=(p=s.commits.nodes)==null?void 0:p.filter(G)[0])==null?void 0:d.commit.statusCheckRollup)==null?void 0:c.contexts.nodes)==null?void 0:g.filter(G).map(h=>"context"in h?{completedAt:null,description:h.description,name:h.context,state:Ms(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:zs(h.status,h.conclusion),startedAt:h.startedAt?new Date(h.startedAt):null,stage:null,url:h.permalink}))??[]},headRef:s.headRef?{name:s.headRef.name,oid:((m=s.headRef.target)==null?void 0:m.oid)??null}:null,baseRef:s.baseRef?{name:s.baseRef.name,oid:((I=s.baseRef.target)==null?void 0:I.oid)??null}:null,url:s.url,updatedDate:new Date(s.updatedAt),closedDate:s.closedAt?new Date(s.closedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees.nodes?s.assignees.nodes.filter(G).map(h=>Q(h)):null,reviews:i,reviewDecision:z(i),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:ks[s.mergeStateStatus]??Os[s.mergeable],milestone:s.milestone?$t(s.milestone):null,labels:((b=(f=s.labels)==null?void 0:f.nodes)==null?void 0:b.filter(G).map(Ut))??[],permissions:{canMerge:Ns.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Ws=s=>{var f,b;let{comments:t,isOutdated:e,isResolved:r,originalLine:n,originalStartLine:i,startDiffSide:o}=s,a=(f=t.nodes)==null?void 0:f[0];if(!a)return null;let{author:u,body:l,databaseId:p,fullDatabaseId:d,id:c,path:g,publishedAt:m,url:I}=a;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:m?new Date(m):null,diffLines:qr(a.diffHunk,n,i,o),id:d??p.toString(),isOutdated:e,isResolved:r,graphQLId:c,filename:g,replies:((b=t.nodes)==null?void 0:b.filter(G).slice(1).map(Hs))??[],url:I}},Hs=s=>({author:s.author?{avatarUrl:s.author.avatarUrl,email:null,name:s.author.login}:null,body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId.toString(),url:s.url}),Js=s=>{var e,r,n;let t=null;return s.author?t=s.author:t=Lt,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?Q(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:xs[s.state],color:null},type:null,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login}},url:s.url,updatedDate:new Date(s.updatedAt),assignees:((e=s.assignees.nodes)==null?void 0:e.filter(G).map(i=>Q(i)))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?$t(s.milestone):null,labels:((n=(r=s.labels)==null?void 0:r.nodes)==null?void 0:n.filter(G).map(Ut))??[]}},$t=s=>({id:s.number.toString(),graphQLId:s.id.toString(),number:s.number,title:s.title,description:s.description,isOpen:s.state=="OPEN",url:s.url,startDate:null,dueDate:s.dueOn?new Date(s.dueOn):null}),ae=class extends x{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let r=e.token||this.config.token;if(!r)return[];let n=this._scopesCache[r];if(!n){let o=(await w(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=o?o.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 i=await this.config.request({url:`${oe(this.config,e)}/meta`,headers:y(e.token||this.config.token)});if(!i.body.installed_version)return null;n=i.body.installed_version.split(".").slice(0,3).map(o=>parseInt(o,10)),this._enterpriseVersionsCache[r]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,r,n){let i=n.baseUrl||this.config.baseUrl;return!i||i.startsWith(Ae)?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=hr(e.fields),i=await this.getScopes(r),o=await w(this.config,{query:`
257
+ `,Ct={__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"},Os={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},ks={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},xs={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Ns={OPEN:"OPEN",CLOSED:"CLOSED"},_s=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Dt=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Bs=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),St=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:Bs(s.viewerPermission)}),Qs=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),vr=s=>({id:s.id.toString(),graphQLId:s.node_id,namespace:s.owner.login,name:s.name,webUrl:s.html_url,httpsUrl:s.clone_url,sshUrl:s.ssh_url,defaultBranch:{name:s.default_branch},permissions:Qs(s.permissions)}),js=s=>({path:s.path,isDirectory:s.type==="tree"}),Fs={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},zs={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},k=(s,t=zs)=>{let e={};return t.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),t.graphQLId&&(e.graphQLId=s.id),t.name&&(e.name=s.name??s.login),t.username&&(e.username=s.login),t.email&&(e.email=s.email??null),t.avatarUrl&&(e.avatarUrl=s.avatarUrl),t.url&&(e.url=s.url),e},Ms=(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]},Ws=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],qt=s=>{let t=null;s.author?t=s.author:t=Ct;let e=(s.reviewRequests?.nodes||[]).filter(C).filter(i=>!i.asCodeOwner),r=s.headRepository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=s.repository?.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:k(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(C).map(i=>{let a=Ct;return i.author&&i.author.__typename&&(a=i.author),{reviewer:k(a),state:Os[i.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,number:s.number,state:Fs[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?k(t):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:s.repository.sshUrl}},headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(C)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(C).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Ws(i.state),startedAt:new Date(i.createdAt),stage:null,url:i.targetUrl}:{completedAt:i.completedAt?new Date(i.completedAt):null,description:null,name:i.name,state:Ms(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:s.headRef?{name:s.headRef.name,oid:s.headRef.target?.oid??null}:null,baseRef:s.baseRef?{name:s.baseRef.name,oid:s.baseRef.target?.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(C).map(i=>k(i)):null,reviews:o,reviewDecision:_(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:xs[s.mergeStateStatus]??ks[s.mergeable],milestone:s.milestone?At(s.milestone):null,labels:s.labels?.nodes?.filter(C).map(Dt)??[],permissions:{canMerge:_s.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Hs=s=>{let{comments:t,isOutdated:e,isResolved:r,originalLine:n,originalStartLine:o,startDiffSide:i}=s,a=t.nodes?.[0];if(!a)return null;let{author:u,body:l,databaseId:c,fullDatabaseId:p,id:d,path:g,publishedAt:m,url:y}=a;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:m?new Date(m):null,diffLines:wr(a.diffHunk,n,o,i),id:p??c.toString(),isOutdated:e,isResolved:r,graphQLId:d,filename:g,replies:t.nodes?.filter(C).slice(1).map(Js)??[],url:y}},Js=s=>({author:s.author?{avatarUrl:s.author.avatarUrl,email:null,name:s.author.login}:null,body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId.toString(),url:s.url}),Vs=s=>{let t=null;return s.author?t=s.author:t=Ct,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?k(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:Ns[s.state],color:null},type:null,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login}},url:s.url,updatedDate:new Date(s.updatedAt),assignees:s.assignees.nodes?.filter(C).map(e=>k(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?At(s.milestone):null,labels:s.labels?.nodes?.filter(C).map(Dt)??[]}},At=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}),se=class extends U{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 I(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:`${re(this.config,e)}/meta`,headers:h(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[r]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,r,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(Se)?e:r?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(r)}`:""}async getCurrentUser(e={},r={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=dr(e.fields),o=await this.getScopes(r),i=await I(this.config,{query:`
258
258
  query getCurrentUser {
259
259
  viewer {
260
- ${N(!1,J(i),n)}
260
+ ${$(!1,F(o),n)}
261
261
  }
262
262
  }
263
- `},r),a=(u=o.body.data)==null?void 0:u.viewer;if(!a)throw new P("Current user not found.",o.body.errors);return{data:Q(a,n)}}async getAccountsForRepo(e,r={}){var l,p,d,c,g;let n=await this.getScopes(r),{repo:{namespace:i,name:o},cursor:a}=e,u=await w(this.config,{query:`
263
+ `},r),a=i.body.data?.viewer;if(!a)throw new f("Current user not found.",i.body.errors);return{data:k(a,n)}}async getAccountsForRepo(e,r={}){let n=await this.getScopes(r),{repo:{namespace:o,name:i},cursor:a}=e,u=await I(this.config,{query:`
264
264
  query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
265
265
  repository(owner: $owner, name: $name) {
266
266
  assignableUsers(first: $first, after: $cursor) {
267
267
  nodes {
268
- ${N(!1,J(n))}
268
+ ${$(!1,F(n))}
269
269
  }
270
270
  pageInfo {
271
271
  endCursor
@@ -274,7 +274,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
274
274
  }
275
275
  }
276
276
  }
277
- `,variables:{owner:i,name:o,cursor:a,first:L}},r);if(!u.body.data)throw new P("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=>Q(m)))??[]}}async getUserForCommit(e,r={}){var a,u;let n=await w(this.config,{query:`
277
+ `,variables:{owner:o,name:i,cursor:a,first:v}},r);if(!u.body.data)throw new f("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(l=>k(l))??[]}}async getUserForCommit(e,r={}){let n=await I(this.config,{query:`
278
278
  query getUserForCommit(
279
279
  $owner: String!
280
280
  $name: String!
@@ -293,7 +293,7 @@ query getUserForCommit(
293
293
  }
294
294
  }
295
295
  }
296
- `,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},r),i=(a=n.body.data)==null?void 0:a.repository;if(!i)throw new P("Repository not found.",n.body.errors);let o=(u=i.object)==null?void 0:u.author;if(!o)throw new P("Commit not found.",n.body.errors);return{data:{name:o.name,email:o.email,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(o.avatarUrl,o.email,r)}}}async createCommit(e,r={}){let{commitMessage:n,deletedFiles:i,newOrModifiedFiles:o,repo:a,target:u}=e,l=await w(this.config,{query:`
296
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,oid:e.oid,avatarSize:e.avatarSize}},r),o=n.body.data?.repository;if(!o)throw new f("Repository not found.",n.body.errors);let i=o.object?.author;if(!i)throw new f("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 I(this.config,{query:`
297
297
  mutation createCommitOnBranch(
298
298
  $branchName: String!,
299
299
  $expectedHeadOid: GitObjectID!,
@@ -320,23 +320,23 @@ mutation createCommitOnBranch(
320
320
  }
321
321
  }
322
322
  }
323
- `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(o).map(([p,d])=>({contents:Dr.Base64.encode(d),path:p})),deletions:i.map(p=>({path:p}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},r);if(!l.body.data)throw new P("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),i=await w(this.config,{query:`
323
+ `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([c,p])=>({contents:Er.Base64.encode(p),path:c})),deletions:o.map(c=>({path:c}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},r);if(!l.body.data)throw new f("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={}){let n=await this.getScopes(r),o=await I(this.config,{query:`
324
324
  query getAccountForEmail($query: String! $avatarSize: Int) {
325
325
  search(query: $query, type: USER, first: 1) {
326
326
  nodes {
327
327
  ... on User {
328
- ${N(!0,J(n))}
328
+ ${$(!0,F(n))}
329
329
  }
330
330
  }
331
331
  }
332
332
  }
333
- `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},r),o=(l=(u=(a=i.body.data)==null?void 0:a.search)==null?void 0:u.nodes)==null?void 0:l[0];if(!o)throw new P("Could not find user via email",i.body.errors);return{data:Q({...o,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(o.avatarUrl,o.email,r)})}}async getAccountForUsername(e,r={}){var a;let n=await this.getScopes(r),i=await w(this.config,{query:`
333
+ `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},r),i=o.body.data?.search?.nodes?.[0];if(!i)throw new f("Could not find user via email",o.body.errors);return{data:k({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getAccountForUsername(e,r={}){let n=await this.getScopes(r),o=await I(this.config,{query:`
334
334
  query getUserForUsername($login: String! $avatarSize: Int) {
335
335
  user(login: $login) {
336
- ${N(!0,J(n))}
336
+ ${$(!0,F(n))}
337
337
  }
338
338
  }
339
- `,variables:{login:e.username,avatarSize:e.avatarSize}},r),o=(a=i.body.data)==null?void 0:a.user;if(!o)throw new P("Could not find user via username",i.body.errors);return{data:Q({...o,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(o.avatarUrl,o.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await w(this.config,{query:`
339
+ `,variables:{login:e.username,avatarSize:e.avatarSize}},r),i=o.body.data?.user;if(!i)throw new f("Could not find user via username",o.body.errors);return{data:k({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await I(this.config,{query:`
340
340
  query getOrgsForCurrentUser($cursor: String, $first: Int!) {
341
341
  viewer {
342
342
  organizations(first: $first after: $cursor) {
@@ -355,7 +355,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
355
355
  }
356
356
  }
357
357
  }
358
- `,variables:{cursor:e.cursor,first:L}},r);if(!n.body.data)throw new P("Could not fetch orgs for current user",n.body.errors);let i=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.body.data.viewer.organizations.pageInfo,data:i.map(o=>({id:o.databaseId.toString(),graphQLId:o.id,username:o.login,name:o.name||null,email:o.email||null,avatarUrl:o.avatarUrl}))}}async getOrgMembers(e,r={}){var o,a,u,l,p,d,c,g,m;let n=await w(this.config,{query:`
358
+ `,variables:{cursor:e.cursor,first:v}},r);if(!n.body.data)throw new f("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={}){let n=await I(this.config,{query:`
359
359
  query getOrgMember($cursor: String, $first: Int!, $login: String!) {
360
360
  viewer {
361
361
  organization(login: $login) {
@@ -365,28 +365,28 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
365
365
  hasNextPage
366
366
  }
367
367
  nodes {
368
- ${N(!1,!0)}
368
+ ${$(!1,!0)}
369
369
  }
370
370
  }
371
371
  }
372
372
  }
373
373
  }
374
- `,variables:{cursor:e.cursor,first:L,login:e.org}},r);if(!((a=(o=n.body.data)==null?void 0:o.viewer.organization)!=null&&a.membersWithRole)&&((u=n.body.errors)!=null&&u.length))throw new P("Could not read the members of the organization",n.body.errors);let i=((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:i.map(I=>Q({...I,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(I.avatarUrl,I.email,r)}))}}async getRepo(e,r={}){var i;let n=await w(this.config,{query:`
374
+ `,variables:{cursor:e.cursor,first:v,login:e.org}},r);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new f("Could not read the members of the organization",n.body.errors);let o=n.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:n.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:n.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>k({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}))}}async getRepo(e,r={}){let n=await I(this.config,{query:`
375
375
  query getRepo($owner: String!, $name: String!) {
376
376
  repository(owner: $owner, name: $name) {
377
- ${Ct}
377
+ ${Et}
378
378
  }
379
379
  }
380
- `,variables:{owner:e.namespace,name:e.name}},r);if(!((i=n.body.data)!=null&&i.repository))throw new P(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:Dt(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},p)=>`
381
- getRepo_${p}: repository(owner: "${u}", name: "${l}") {
382
- ${Ct}
380
+ `,variables:{owner:e.namespace,name:e.name}},r);if(!n.body.data?.repository)throw new f(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:St(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},c)=>`
381
+ getRepo_${c}: repository(owner: "${u}", name: "${l}") {
382
+ ${Et}
383
383
  }
384
384
  `).join(`
385
- `),i=await w(this.config,{query:`
385
+ `),o=await I(this.config,{query:`
386
386
  query batchGetRepos {
387
387
  ${n}
388
388
  }
389
- `},r);if(!i.body.data)throw new P("Could not fetch repos",i.body.errors);let o=[],a=[];return e.forEach((u,l)=>{let p=i.body.data[`getRepo_${l}`];p?o.push(Dt(p)):a.push({input:u})}),{data:o,errors:a}}async fetchMultipleRESTPages(e,r,n,i){let o=[];for(let d=0;d<r;d++)o.push(n(e+d));let a=await Promise.all(o),u=[];for(let d of a){if(!d.body)throw new Error(d.statusText||"Unknown error");u=u.concat(d.body.map(c=>i(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 i=o=>this.config.request({url:`${oe(this.config,r)}/user/repos?${n.toString()}&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,i,Cr)}async getReposForOrg(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=i=>this.config.request({url:`${oe(this.config,r)}/orgs/${e.orgName}/repos?per_page=100&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,n,Cr)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await w(this.config,{query:`
389
+ `},r);if(!o.body.data)throw new f("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let c=o.body.data[`getRepo_${l}`];c?i.push(St(c)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,r,n,o){let i=[];for(let p=0;p<r;p++)i.push(n(e+p));let a=await Promise.all(i),u=[];for(let p of a){if(!p.body)throw new Error(p.statusText||"Unknown error");u=u.concat(p.body.map(d=>o(d)))}let l=a.every(p=>p.body.length===100),c=e+r;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?c: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:`${re(this.config,r)}/user/repos?${n.toString()}&page=${i}`,headers:{...h(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,vr)}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:`${re(this.config,r)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...h(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,vr)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await I(this.config,{query:`
390
390
  query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
391
391
  search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
392
392
  pageInfo {
@@ -395,12 +395,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
395
395
  }
396
396
  nodes {
397
397
  ... on Repository {
398
- ${Ct}
398
+ ${Et}
399
399
  }
400
400
  }
401
401
  }
402
402
  }
403
- `,variables:{query:`fork:true ${e.usernames.map(o=>`user:${o}`).join(" ")}`,cursor:e.cursor,first:L}},r);if(!n.body.data)throw new P("Could not fetch repos for usernames",n.body.errors);let i=n.body.data.search.nodes||[];return{pageInfo:n.body.data.search.pageInfo,data:i.map(Dt)}}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 i=await w(this.config,{query:`
403
+ `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:v}},r);if(!n.body.data)throw new f("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(St)}}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={}){let o=await I(this.config,{query:`
404
404
  query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
405
405
  repository(owner: $owner, name: $name) {
406
406
  refs(refPrefix: $refPrefix first: $first after: $cursor) {
@@ -421,7 +421,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
421
421
  }
422
422
  }
423
423
  }
424
- `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:L}},n),o=(u=i.body.data)==null?void 0:u.repository;if(!o)throw new P("Ref repository not found.",i.body.errors);let a=o.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:`
424
+ `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:v}},n),i=o.body.data?.repository;if(!i)throw new f("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.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={}){let n=await I(this.config,{query:`
425
425
  query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
426
426
  repository(owner: $owner, name: $name) {
427
427
  object(expression: $ref) {
@@ -460,7 +460,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
460
460
  }
461
461
  }
462
462
  }
463
- `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},r),i=(a=n.body.data)==null?void 0:a.repository;if(!i)throw new P("Blame repository not found.",n.body.errors);let o=i.object;if(!o||!("blame"in o))throw new P("Ref not found.",n.body.errors);if(o.blame.ranges.length===0)throw new P("File not found.",n.body.errors);return{data:{ranges:o.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),i=await this.getScopes(r),o=J(i),a=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return qt("pr",c,e.cursor,{maxPageSize:e.maxPageSize??wr,supportsEmail:o,supportsDrafts:d,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await w(this.config,a(!0),r);u.body.errors&&Ge(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 P("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:((p=l.search.nodes)==null?void 0:p.filter(G).map(At))||[]}}async searchIssues(e,r={}){var l;let n=await this.getEnterpriseVersion(r),i=await this.getScopes(r),o=J(i),a=await w(this.config,qt("issue",e.query,e.cursor,{supportsEmail:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??vr,enterpriseVersion:n}),r),{data:u}=a.body;if(!u)throw new P("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:((l=u.search.nodes)==null?void 0:l.filter(G).map(Js))||[]}}async getPullRequestsAssociatedWithUser(e,r={}){var i;let n=[`involves:${e.username}`];return(i=e.repos)!=null&&i.length&&e.repos.forEach(o=>{n.push(`repo:${o.namespace}/${o.name}`)}),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:i,authorLogin:o,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=St(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),i&&g.push(`updated:<${i}`),o&&g.push(`author:${o}`),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),i=await this.getScopes(r),o=J(i),a=c=>({query:`query getPullRequest(
463
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},r),o=n.body.data?.repository;if(!o)throw new f("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new f("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new f("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,r={}){let n=await this.config.request({url:`${re(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...h(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={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=c=>{let p=c&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return vt("pr",p,e.cursor,{maxPageSize:e.maxPageSize??Rr,supportsEmail:i,supportsDrafts:c,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await I(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(C).map(qt)||[]}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=await I(this.config,vt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??yr,enterpriseVersion:n}),r),{data:u}=a.body;if(!u)throw new f("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(C).map(Vs)||[]}}async getPullRequestsAssociatedWithUser(e,r={}){let n=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{n.push(`repo:${o.namespace}/${o.name}`)}),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:c,labelNames:p,maxPageSize:d}=e,g=wt(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}`),c&&g.push(`mentions:${c}`),p&&p.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:d},r)}async getPullRequestForRepo(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=p=>({query:`query getPullRequest(
464
464
  $owner: String!
465
465
  $name: String!
466
466
  $number: Int!
@@ -470,24 +470,24 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
470
470
  name: $name
471
471
  ) {
472
472
  pullRequest(number: $number) {
473
- ${$e(c,o,n)}
473
+ ${De(p,i,n)}
474
474
  }
475
475
  }
476
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await w(this.config,a(!0),r);u.body.errors&&Ge(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 P("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?At(p):null}}async getPullRequestByGraphQLId(e,r={}){var d;let n=await this.getEnterpriseVersion(r),i=await this.getScopes(r),o=J(i),a=c=>({query:`query getPullRequest(
476
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await I(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not fetch pull request by number",u.body.errors);let c=u.body.data?.repository.pullRequest;return{data:c?qt(c):null}}async getPullRequestByGraphQLId(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=p=>({query:`query getPullRequest(
477
477
  $graphQLId: ID!
478
478
  ) {
479
479
  node(id: $graphQLId) {
480
480
  ... on PullRequest {
481
- ${$e(c,o,n)}
481
+ ${De(p,i,n)}
482
482
  }
483
483
  }
484
- }`,variables:{graphQLId:e.graphQLId}}),u=await w(this.config,a(!0),r);u.body.errors&&Ge(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 P("Could not fetch pull request by id",u.body.errors);let p=(d=u.body.data)==null?void 0:d.node;return{data:p?At(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 i=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
484
+ }`,variables:{graphQLId:e.graphQLId}}),u=await I(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not fetch pull request by id",u.body.errors);let c=u.body.data?.node;return{data:c?qt(c):null}}async closePullRequest(e,r={}){let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
485
485
  closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
486
486
  pullRequest {
487
487
  id
488
488
  }
489
489
  }
490
- }`,o=await w(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:n}},r);if(!((l=(u=(a=o.body.data)==null?void 0:a.closePullRequest)==null?void 0:u.pullRequest)!=null&&l.id))throw new P("Could not close pull request",o.body.errors)}async mergePullRequest(e,r={}){var l,p,d,c;let{pullRequest:n,mergeStrategy:i}=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 o;switch(i){case"MERGE_COMMIT":{o="MERGE";break}case"REBASE":{o="REBASE";break}case"SQUASH":{o="SQUASH";break}}let a=`mutation MergePullRequest(
490
+ }`,i=await I(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:n}},r);if(!i.body.data?.closePullRequest?.pullRequest?.id)throw new f("Could not close pull request",i.body.errors)}async mergePullRequest(e,r={}){let{pullRequest:n,mergeStrategy:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!n.headRef?.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(
491
491
  $pullRequestGraphQLId: ID!,
492
492
  $expectedSourceSha: GitObjectID!,
493
493
  $mergeStrategy: PullRequestMergeMethod,
@@ -501,43 +501,43 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
501
501
  id
502
502
  }
503
503
  }
504
- }`,u=await w(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:n.graphQLId,expectedSourceSha:n.headRef.oid,mergeStrategy:o}},r);if(!((c=(d=(p=u.body.data)==null?void 0:p.mergePullRequest)==null?void 0:d.pullRequest)!=null&&c.id))throw new P("Could not merge pull request",u.body.errors)}async setPullRequestMilestone(e,r={}){var u,l,p;let{pullRequest:n,milestone:i}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
504
+ }`,u=await I(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:n.graphQLId,expectedSourceSha:n.headRef.oid,mergeStrategy:i}},r);if(!u.body.data?.mergePullRequest?.pullRequest?.id)throw new f("Could not merge pull request",u.body.errors)}async setPullRequestMilestone(e,r={}){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) {
505
505
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
506
506
  pullRequest {
507
507
  id
508
508
  }
509
509
  }
510
- }`,a=await w(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:n.graphQLId,milestoneGraphQLId:(i==null?void 0:i.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 P("Could not set milestone of pull request",a.body.errors)}async markPullRequestReadyForReview(e,r){var o,a,u;let n=`mutation MarkReadyToReview($pullRequestGraphQLId: ID!) {
510
+ }`,a=await I(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},r);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set milestone of pull request",a.body.errors)}async markPullRequestReadyForReview(e,r){let n=`mutation MarkReadyToReview($pullRequestGraphQLId: ID!) {
511
511
  markPullRequestReadyForReview(input: { pullRequestId: $pullRequestGraphQLId }) {
512
512
  pullRequest {
513
513
  id
514
514
  }
515
515
  }
516
- }`,i=await w(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!((u=(a=(o=i.body.data)==null?void 0:o.markPullRequestReadyForReview)==null?void 0:a.pullRequest)!=null&&u.id))throw new P("Could not mark pull request ready to review",i.body.errors)}async convertPullRequestToDraft(e,r){var o,a,u;let n=`mutation ConvertToDraft($pullRequestGraphQLId: ID!) {
516
+ }`,o=await I(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!o.body.data?.markPullRequestReadyForReview?.pullRequest?.id)throw new f("Could not mark pull request ready to review",o.body.errors)}async convertPullRequestToDraft(e,r){let n=`mutation ConvertToDraft($pullRequestGraphQLId: ID!) {
517
517
  convertPullRequestToDraft(input: { pullRequestId: $pullRequestGraphQLId }) {
518
518
  pullRequest {
519
519
  id
520
520
  }
521
521
  }
522
- }`,i=await w(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!((u=(a=(o=i.body.data)==null?void 0:o.convertPullRequestToDraft)==null?void 0:a.pullRequest)!=null&&u.id))throw new P("Could not convert pull request to draft",i.body.errors)}async setPullRequestAsDraft(e,r={}){let{pullRequest:{graphQLId:n},isDraft:i}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');if(i){await this.convertPullRequestToDraft(n,r);return}await this.markPullRequestReadyForReview(n,r)}async setPullRequestReviewers(e,r={}){var d,c,g;let{pullRequest:{reviews:n,graphQLId:i},reviewers:o}=e;if(!n)throw new Error('GitHub requires "reviews" for this function');if(!i)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=o.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!]!) {
522
+ }`,o=await I(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!o.body.data?.convertPullRequestToDraft?.pullRequest?.id)throw new f("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={}){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(p=>p.state!=="REVIEW_REQUESTED").map(p=>{if(!p.reviewer.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return p.reviewer.graphQLId}),u=i.map(p=>{if(!p.graphQLId)throw new Error('GitHub requires reviewer "graphQLId" for this function.');return p.graphQLId}).filter(p=>a.indexOf(p)===-1),l=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
523
523
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds }) {
524
524
  pullRequest {
525
525
  id
526
526
  }
527
527
  }
528
- }`,p=await w(this.config,{query:l,variables:{pullRequestGraphQLId:i,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 P("Could not set pull request reviewers",p.body.errors)}async reRequestPullRequestReviews(e,r={}){var p,d,c;let{pullRequest:{reviews:n,graphQLId:i},reviewers:o}=e;if(!i)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 o){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!]!) {
528
+ }`,c=await I(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},r);if(!c.body.data?.requestReviews?.pullRequest?.id)throw new f("Could not set pull request reviewers",c.body.errors)}async reRequestPullRequestReviews(e,r={}){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 c of i){if(!c.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!n.find(p=>p.reviewer.graphQLId===c.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(c.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
529
529
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
530
530
  pullRequest {
531
531
  id
532
532
  }
533
533
  }
534
- }`,l=await w(this.config,{query:u,variables:{pullRequestGraphQLId:i,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 P("Could not re-request pull request reviews",l.body.errors)}async setPullRequestAssignees(e,r={}){var l,p,d;let{pullRequest:n,assignees:i}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=i.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!]!) {
534
+ }`,l=await I(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:a}},r);if(!l.body.data?.requestReviews?.pullRequest?.id)throw new f("Could not re-request pull request reviews",l.body.errors)}async setPullRequestAssignees(e,r={}){let{pullRequest:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),a=`mutation SetPullRequestAssignees($pullRequestGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
535
535
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
536
536
  pullRequest {
537
537
  id
538
538
  }
539
539
  }
540
- }`,u=await w(this.config,{query:a,variables:{pullRequestGraphQLId:n.graphQLId,assigneeGraphQLIds:o}},r);if(!((d=(p=(l=u.body.data)==null?void 0:l.updatePullRequest)==null?void 0:p.pullRequest)!=null&&d.id))throw new P("Could not set pull request assignees",u.body.errors)}async getReviewsForPullRequest(e,r={}){var c,g,m,I;let n=await this.getEnterpriseVersion(r),{repo:{namespace:i,name:o},pullRequestId:a}=e,u=`query getPullRequests(
540
+ }`,u=await I(this.config,{query:a,variables:{pullRequestGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},r);if(!u.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set pull request assignees",u.body.errors)}async getReviewsForPullRequest(e,r={}){let n=await this.getEnterpriseVersion(r),{repo:{namespace:o,name:i},pullRequestId:a}=e,u=`query getPullRequests(
541
541
  $namespace: String!
542
542
  $name: String!
543
543
  $pullRequestId: Int!
@@ -561,7 +561,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
561
561
  login
562
562
  }
563
563
  body
564
- ${!n||H(n,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
564
+ ${!n||j(n,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
565
565
  diffHunk
566
566
  id
567
567
  path
@@ -581,7 +581,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
581
581
  login
582
582
  }
583
583
  body
584
- ${!n||H(n,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
584
+ ${!n||j(n,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
585
585
  id
586
586
  publishedAt
587
587
  url
@@ -589,54 +589,54 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
589
589
  }
590
590
  }
591
591
  }
592
- }`,l=await w(this.config,{query:u,variables:{namespace:i,name:o,pullRequestId:a}},r),p=((g=(c=l.body.data)==null?void 0:c.repository.pullRequest.reviewThreads.nodes)==null?void 0:g.filter(G).reduce((f,b)=>{var E,D;if(!((D=(E=b.comments.nodes)==null?void 0:E[0])!=null&&D.pullRequestReview))return f;let h=b.comments.nodes[0].pullRequestReview,R=Ws(b);return R&&(f[h.id]||(f[h.id]=[]),f[h.id].push(R)),f},{}))??{};return{data:((I=(m=l.body.data)==null?void 0:m.repository.pullRequest.reviews.nodes)==null?void 0:I.filter(G).filter(f=>p[f.id]).map(f=>({author:f.author?{avatarUrl:f.author.avatarUrl,email:null,name:f.author.login}:null,body:f.body,createdAt:f.publishedAt?new Date(f.publishedAt):null,id:f.fullDatabaseId??f.databaseId.toString(),graphQLId:f.id,reviewComments:p[f.id],url:f.url})))??[]}}async getIssuesAssociatedWithUser(e,r={}){var c;let[n,i]=((c=e.cursor)==null?void 0:c.split(";"))||[void 0,void 0],o=[];e.labelNames&&e.labelNames.forEach(g=>{o.push(`label:"${g}"`)});let[a,u]=await Promise.all([n==="null"?null:this.searchIssues({query:`author:${e.username} ${o.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r),i==="null"?null:this.searchIssues({query:`assignee:${e.username} ${o.join(" ")}`,cursor:i,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:i}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
592
+ }`,l=await I(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),c=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(C).reduce((d,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return d;let m=g.comments.nodes[0].pullRequestReview,y=Hs(g);return y&&(d[m.id]||(d[m.id]=[]),d[m.id].push(y)),d},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(C).filter(d=>c[d.id]).map(d=>({author:d.author?{avatarUrl:d.author.avatarUrl,email:null,name:d.author.login}:null,body:d.body,createdAt:d.publishedAt?new Date(d.publishedAt):null,id:d.fullDatabaseId??d.databaseId.toString(),graphQLId:d.id,reviewComments:c[d.id],url:d.url}))??[]}}async getIssuesAssociatedWithUser(e,r={}){let[n,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(d=>{i.push(`label:"${d}"`)});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={},c=[],p=d=>{l[d.id]||(l[d.id]=!0,c.push(d))};return a?.data.forEach(p),u?.data.forEach(p),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:c}}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
593
593
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
594
594
  pullRequest {
595
595
  id
596
596
  }
597
597
  }
598
- }`,a=await w(this.config,{query:o,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:i.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 P("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=St(e.startQuery||""),{cursor:i,assigneeLogins:o,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(d=>{n.push(`repo:${d.namespace}/${d.name}`)}),o&&o.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:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async closeIssueWithReason(e,r={}){var u,l,p;let{issue:n,reason:i}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
598
+ }`,a=await I(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},r);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=wt(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:c}=e;return e.repos.forEach(p=>{n.push(`repo:${p.namespace}/${p.name}`)}),i&&i.forEach(p=>{n.push(`assignee:${p}`)}),a&&n.push(`updated:<${a}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),c&&c.forEach(p=>{n.push(`label:"${p}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async closeIssueWithReason(e,r={}){let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
599
599
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
600
600
  issue {
601
601
  id
602
602
  }
603
603
  }
604
- }`,a=await w(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId,reason:i}},r);if(!((p=(l=(u=a.body.data)==null?void 0:u.closeIssue)==null?void 0:l.issue)!=null&&p.id))throw new P("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 i=`mutation SetIssueState($issueGraphQLId: ID!) {
604
+ }`,a=await I(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId,reason:o}},r);if(!a.body.data?.closeIssue?.issue?.id)throw new f("Could not close issue with reason",a.body.errors)}async closeIssue(e,r={}){let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetIssueState($issueGraphQLId: ID!) {
605
605
  updateIssue(input: { id: $issueGraphQLId, state: CLOSED }) {
606
606
  issue {
607
607
  id
608
608
  }
609
609
  }
610
- }`,o=await w(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId}},r);if(!((l=(u=(a=o.body.data)==null?void 0:a.updateIssue)==null?void 0:u.issue)!=null&&l.id))throw new P("Could not close issue",o.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 i=`mutation ReOpenIssue($issueGraphQLId: ID!) {
610
+ }`,i=await I(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!i.body.data?.updateIssue?.issue?.id)throw new f("Could not close issue",i.body.errors)}async reOpenIssue(e,r={}){let{issue:n}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ReOpenIssue($issueGraphQLId: ID!) {
611
611
  reopenIssue(input: { issueId: $issueGraphQLId }) {
612
612
  issue {
613
613
  id
614
614
  }
615
615
  }
616
- }`,o=await w(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId}},r);if(!((l=(u=(a=o.body.data)==null?void 0:a.reopenIssue)==null?void 0:u.issue)!=null&&l.id))throw new P("Could not reopen issue",o.body.errors)}async setIssueLabels(e,r={}){var l,p,d;let{issue:n,labels:i}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=i.map(c=>c.graphQLId),a=`mutation SetIssueLabels($issueGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
616
+ }`,i=await I(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!i.body.data?.reopenIssue?.issue?.id)throw new f("Could not reopen issue",i.body.errors)}async setIssueLabels(e,r={}){let{issue:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>l.graphQLId),a=`mutation SetIssueLabels($issueGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
617
617
  updateIssue(input: { id: $issueGraphQLId, labelIds: $labelGraphQLIds }) {
618
618
  issue {
619
619
  id
620
620
  }
621
621
  }
622
- }`,u=await w(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,labelGraphQLIds:o}},r);if(!((d=(p=(l=u.body.data)==null?void 0:l.updateIssue)==null?void 0:p.issue)!=null&&d.id))throw new P("Could not set issue labels",u.body.errors)}async setIssueMilestone(e,r={}){var u,l,p;let{issue:n,milestone:i}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(i&&!i.graphQLId)throw new Error('GitHub requires milestone "graphQLId" for this function.');let o=`mutation SetIssueMilestone($issueGraphQLId: ID!, $milestoneGraphQLId: ID) {
622
+ }`,u=await I(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,labelGraphQLIds:i}},r);if(!u.body.data?.updateIssue?.issue?.id)throw new f("Could not set issue labels",u.body.errors)}async setIssueMilestone(e,r={}){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) {
623
623
  updateIssue(input: { id: $issueGraphQLId, milestoneId: $milestoneGraphQLId }) {
624
624
  issue {
625
625
  id
626
626
  }
627
627
  }
628
- }`,a=await w(this.config,{query:`${o}`,variables:{issueGraphQLId:n.graphQLId,milestoneGraphQLId:(i==null?void 0:i.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 P("Could not set milestone of issue",a.body.errors)}async setIssueAssignees(e,r={}){var l,p,d;let{issue:n,assignees:i}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=i.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!]!) {
628
+ }`,a=await I(this.config,{query:`${i}`,variables:{issueGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},r);if(!a.body.data?.updateIssue?.issue?.id)throw new f("Could not set milestone of issue",a.body.errors)}async setIssueAssignees(e,r={}){let{issue:n,assignees:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=o.map(l=>{if(!l.graphQLId)throw new Error('GitHub requires assignee "graphQLId" for this function.');return l.graphQLId}),a=`mutation SetIssueAssignees($issueGraphQLId: ID!, $assigneeGraphQLIds: [ID!]!) {
629
629
  updateIssue(input: { id: $issueGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
630
630
  issue {
631
631
  id
632
632
  }
633
633
  }
634
- }`,u=await w(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,assigneeGraphQLIds:o}},r);if(!((d=(p=(l=u.body.data)==null?void 0:l.updateIssue)==null?void 0:p.issue)!=null&&d.id))throw new P("Could not set issue assignees",u.body.errors)}async getMilestonesForRepo(e,r={}){var u,l,p;let{repo:{namespace:n,name:i},cursor:o}=e,a=await w(this.config,{query:`
634
+ }`,u=await I(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},r);if(!u.body.data?.updateIssue?.issue?.id)throw new f("Could not set issue assignees",u.body.errors)}async getMilestonesForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await I(this.config,{query:`
635
635
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
636
636
  repository(owner: $owner, name: $name) {
637
637
  milestones(first: $first, after: $cursor) {
638
638
  nodes {
639
- ${Le}
639
+ ${qe}
640
640
  }
641
641
  pageInfo {
642
642
  endCursor
@@ -645,12 +645,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
645
645
  }
646
646
  }
647
647
  }
648
- `,variables:{owner:n,name:i,cursor:o,first:L}},r);if(!a.body.data)throw new P("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($t))??[]}}async getLabelsForRepo(e,r={}){var u,l,p;let{repo:{namespace:n,name:i},cursor:o}=e,a=await w(this.config,{query:`
648
+ `,variables:{owner:n,name:o,cursor:i,first:v}},r);if(!a.body.data)throw new f("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(At)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await I(this.config,{query:`
649
649
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
650
650
  repository(owner: $owner, name: $name) {
651
651
  labels(first: $first, after: $cursor) {
652
652
  nodes {
653
- ${Ue}
653
+ ${Ce}
654
654
  }
655
655
  pageInfo {
656
656
  endCursor
@@ -659,7 +659,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
659
659
  }
660
660
  }
661
661
  }
662
- `,variables:{owner:n,name:i,cursor:o,first:L}},r);if(!a.body.data)throw new P("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(Ut))??[]}}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(Qs)}}};var Vs="https://gitlab.com/api/v4",Ks="https://gitlab.com/api/graphql",Gt=/\/api\/v\d+$/,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.")},Te=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ar(e),Gt.test(e)||(e=e+"/api/v4"),e):Vs},Xs=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ar(e),Gt.test(e)&&(e=e.replace(Gt,"")),`${e}/api/graphql`):Ks},v=(s,t,e)=>{let r=y(e.token||s.token);return s.request({url:Xs(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},Oe=s=>s==null?void 0:s.map(t=>`"${t.message}"`).join(", ");var Nt=s=>s.split("/").slice(0,-1).join("/"),_t=s=>s.split("/").at(-1)??"",ke=s=>({id:s.id.replace(ue,""),graphQLId:s.id,namespace:Nt(s.fullPath),name:_t(s.fullPath),webUrl:s.webUrl}),Lr=s=>({id:s.id.replace(ue,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:Nt(s.fullPath),name:_t(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Ys={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Zs={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var en="gid://gitlab/User/",ue="gid://gitlab/Project/",tn="gid://gitlab/MergeRequest/",rn="gid://gitlab/Issue/",sn="gid://gitlab/ProjectLabel/",nn="gid://gitlab/Milestone/",on="gid://gitlab/Ci::Build/",Bt=`
662
+ `,variables:{owner:n,name:o,cursor:i,first:v}},r);if(!a.body.data)throw new f("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(Dt)??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${re(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...h(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(js)}}};var Ks="https://gitlab.com/api/v4",Xs="https://gitlab.com/api/graphql",Lt=/\/api\/v\d+$/,Sr=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},Le=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Sr(e),Lt.test(e)||(e=e+"/api/v4"),e):Ks},Ys=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Sr(e),Lt.test(e)&&(e=e.replace(Lt,"")),`${e}/api/graphql`):Xs},b=(s,t,e)=>{let r=h(e.token||s.token);return s.request({url:Ys(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},Ue=s=>s?.map(t=>`"${t.message}"`).join(", ");var Ot=s=>s.split("/").slice(0,-1).join("/"),kt=s=>s.split("/").at(-1)??"",$e=s=>({id:s.id.replace(ne,""),graphQLId:s.id,namespace:Ot(s.fullPath),name:kt(s.fullPath),webUrl:s.webUrl}),qr=s=>({id:s.id.replace(ne,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:Ot(s.fullPath),name:kt(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Zs={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},en={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var tn="gid://gitlab/User/",ne="gid://gitlab/Project/",rn="gid://gitlab/MergeRequest/",sn="gid://gitlab/Issue/",nn="gid://gitlab/ProjectLabel/",on="gid://gitlab/Milestone/",an="gid://gitlab/Ci::Build/",xt=`
663
663
  description
664
664
  dueDate
665
665
  id
@@ -668,7 +668,7 @@ startDate
668
668
  state
669
669
  title
670
670
  webPath
671
- `,Tt=`
671
+ `,Ut=`
672
672
  id
673
673
  fullPath
674
674
  webUrl
@@ -682,25 +682,25 @@ userPermissions {
682
682
  downloadCode
683
683
  pushCode
684
684
  }
685
- `,V=`
685
+ `,z=`
686
686
  id
687
687
  name
688
688
  username
689
689
  publicEmail
690
690
  avatarUrl
691
691
  webUrl
692
- `,Qt=`
692
+ `,Nt=`
693
693
  color
694
694
  description
695
695
  id
696
696
  title
697
- `,Ot=`
697
+ `,$t=`
698
698
  author {
699
- ${V}
699
+ ${z}
700
700
  }
701
701
  assignees {
702
702
  nodes {
703
- ${V}
703
+ ${z}
704
704
  }
705
705
  }
706
706
  closedAt
@@ -711,7 +711,7 @@ id
711
711
  iid
712
712
  labels {
713
713
  nodes {
714
- ${Qt}
714
+ ${Nt}
715
715
  }
716
716
  }
717
717
  state
@@ -722,9 +722,9 @@ upvotes
722
722
  userNotesCount
723
723
  webUrl
724
724
  milestone {
725
- ${Bt}
725
+ ${xt}
726
726
  }
727
- `,an=`
727
+ `,un=`
728
728
  stages {
729
729
  nodes {
730
730
  jobs {
@@ -740,11 +740,11 @@ stages {
740
740
  name
741
741
  }
742
742
  }
743
- `,Ur=(s,t,e)=>`
743
+ `,Cr=(s,t,e)=>`
744
744
  id
745
745
  state
746
746
  author {
747
- ${V}
747
+ ${z}
748
748
  }
749
749
  diffRefs {
750
750
  baseSha
@@ -769,12 +769,12 @@ targetBranch
769
769
  sourceBranch
770
770
  assignees {
771
771
  nodes {
772
- ${V}
772
+ ${z}
773
773
  }
774
774
  }
775
775
  reviewers {
776
776
  nodes {
777
- ${V}
777
+ ${z}
778
778
  mergeRequestInteraction {
779
779
  approved
780
780
  reviewState
@@ -784,19 +784,19 @@ reviewers {
784
784
  mergeStatusEnum
785
785
  labels {
786
786
  nodes {
787
- ${Qt}
787
+ ${Nt}
788
788
  }
789
789
  }
790
790
  ${s?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
791
- ${t?`milestone { ${Bt} }`:""}
792
- ${e?`headPipeline { ${an} }`:""}
793
- `,Y=s=>`${s.namespace}/${s.name}`,un=s=>`${s.namespace}/${s.name}`,ln=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),kt=s=>{var t;return{id:s.id.replace(ue,""),graphQLId:s.id,namespace:Nt(s.fullPath),name:_t(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:(t=s.repository)!=null&&t.rootRef?{name:s.repository.rootRef}:null,permissions:ln(s.userPermissions)}},pn=s=>({path:s.path,isDirectory:s.type==="tree"}),dn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Gr=(s,t,e)=>!t&&(s!=null&&s.startsWith("/"))?`https://gitlab.com${s}`:t&&(s!=null&&s.startsWith("/"))&&e?`${e.replace(/\/+?$/,"")}${s}`:s,K=(s,t,e)=>{let r=Gr(s.avatarUrl,t,e);return{id:s.id.replace(en,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},jt=s=>({color:s.color,description:s.description,id:s.id.replace(sn,""),graphQLId:s.id,name:s.title}),cn=(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,gn=(s,t,e)=>{var n;let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:K(s,t,e),state:(n=s.mergeRequestInteraction)!=null&&n.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},$r=(s,t,e,r,n)=>{var o,a,u,l,p,d,c,g,m,I,f,b;let i=(o=s.reviewers)!=null&&o.nodes?s.reviewers.nodes.map(h=>gn(h,r,n)):null;return{id:s.id.replace(tn,""),graphQLId:s.id,title:s.title,number:parseInt(s.iid,10),state:dn[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?K(s.author,r,n):null,createdDate:new Date(s.createdAt),isDraft:s.draft,repository:{id:t.id,graphQLId:t.graphQLId,name:t.name,owner:{login:t.namespace},remoteInfo:t.httpsUrl&&t.sshUrl?{cloneUrlHTTPS:t.httpsUrl,cloneUrlSSH:t.sshUrl}:null},headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:((l=(u=(a=s.headPipeline)==null?void 0:a.stages)==null?void 0:u.nodes)==null?void 0:l.flatMap(h=>{var R,E;return((E=(R=h.jobs)==null?void 0:R.nodes)==null?void 0:E.map(D=>({completedAt:D.finishedAt?new Date(D.finishedAt):null,description:null,name:D.name??null,state:cn(D.status,D.allowFailure),stage:h.name??null,startedAt:new Date(D.createdAt),url:`${t.webUrl}/-/jobs/${D.id.replace(on,"")}`})))??[]}))??[]},baseRef:{name:s.targetBranch,oid:((p=s.diffRefs)==null?void 0:p.baseSha)??null},headRef:{name:s.sourceBranch,oid:((d=s.diffRefs)==null?void 0:d.headSha)??null},url:s.webUrl,updatedDate:new Date(s.updatedAt),closedDate:s.mergedAt?new Date(s.mergedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:(c=s.assignees)!=null&&c.nodes?s.assignees.nodes.map(h=>K(h,r,n)):null,reviews:i,reviewDecision:z(i),additions:((g=s.diffStatsSummary)==null?void 0:g.additions)||0,deletions:((m=s.diffStatsSummary)==null?void 0:m.deletions)||0,fileCount:((I=s.diffStatsSummary)==null?void 0:I.fileCount)||0,commitCount:s.commitCount||0,mergeableState:Zs[s.mergeStatusEnum],milestone:s.milestone?Ft(s.milestone,t.webUrl):null,labels:((b=(f=s.labels)==null?void 0:f.nodes)==null?void 0:b.map(jt))??[],permissions:null}},xt=(s,t,e,r)=>{var n,i;return{author:K(s.author,e,r),assignees:s.assignees.nodes.map(o=>K(o,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(rn,""),labels:((i=(n=s.labels)==null?void 0:n.nodes)==null?void 0:i.map(jt))??[],number:s.iid,repository:{id:t.id.replace(ue,""),graphQLId:t.id,name:t.name,owner:{login:t.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?Ft(s.milestone,t.webUrl):null}},Ft=(s,t)=>({id:s.id.replace(nn,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${t}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),le=class extends x{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){var i;let n=(i=(await v(this.config,{query:`
791
+ ${t?`milestone { ${xt} }`:""}
792
+ ${e?`headPipeline { ${un} }`:""}
793
+ `,J=s=>`${s.namespace}/${s.name}`,ln=s=>`${s.namespace}/${s.name}`,pn=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),Gt=s=>({id:s.id.replace(ne,""),graphQLId:s.id,namespace:Ot(s.fullPath),name:kt(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:pn(s.userPermissions)}),dn=s=>({path:s.path,isDirectory:s.type==="tree"}),cn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Ar=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,M=(s,t,e)=>{let r=Ar(s.avatarUrl,t,e);return{id:s.id.replace(tn,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},_t=s=>({color:s.color,description:s.description,id:s.id.replace(nn,""),graphQLId:s.id,name:s.title}),gn=(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,mn=(s,t,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:M(s,t,e),state:s.mergeRequestInteraction?.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},Dr=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>mn(i,r,n)):null;return{id:s.id.replace(rn,""),graphQLId:s.id,title:s.title,number:parseInt(s.iid,10),state:cn[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?M(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:s.headPipeline?.stages?.nodes?.flatMap(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:gn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(an,"")}`}))??[])??[]},baseRef:{name:s.targetBranch,oid:s.diffRefs?.baseSha??null},headRef:{name:s.sourceBranch,oid:s.diffRefs?.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:s.assignees?.nodes?s.assignees.nodes.map(i=>M(i,r,n)):null,reviews:o,reviewDecision:_(o),additions:s.diffStatsSummary?.additions||0,deletions:s.diffStatsSummary?.deletions||0,fileCount:s.diffStatsSummary?.fileCount||0,commitCount:s.commitCount||0,mergeableState:en[s.mergeStatusEnum],milestone:s.milestone?Bt(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(_t)??[],permissions:null}},Tt=(s,t,e,r)=>({author:M(s.author,e,r),assignees:s.assignees.nodes.map(n=>M(n,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(sn,""),labels:s.labels?.nodes?.map(_t)??[],number:s.iid,repository:{id:t.id.replace(ne,""),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?Bt(s.milestone,t.webUrl):null}),Bt=(s,t)=>({id:s.id.replace(on,""),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}),oe=class extends U{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){let n=(await b(this.config,{query:`
794
794
  query getCurrentUser {
795
795
  currentUser {
796
- ${V}
796
+ ${z}
797
797
  }
798
798
  }
799
- `},e)).body.data)==null?void 0:i.currentUser;if(!n)throw new Error("Current user not found.");return{data:K(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(t,e={}){var a,u,l,p;let r=Y(t.repo),i=(p=(l=(u=(a=(await v(this.config,{query:`
799
+ `},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:M(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(t,e={}){let r=J(t.repo),o=(await b(this.config,{query:`
800
800
  query getUserForCommit($fullPath: ID!, $oid: String!) {
801
801
  project(fullPath: $fullPath) {
802
802
  repository {
@@ -812,21 +812,21 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
812
812
  }
813
813
  }
814
814
  }
815
- `,variables:{fullPath:r,oid:t.oid}},e)).body.data)==null?void 0:a.project)==null?void 0:u.repository)==null?void 0:l.tree)==null?void 0:p.lastCommit;if(!i)throw new Error("Commit not found.");let o=Gr(i.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:i.authorName,email:i.authorEmail,avatarUrl:o}}}async getAccountForEmail(t,e={}){var i,o,a;let n=(a=(o=(i=(await v(this.config,{query:`
815
+ `,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Ar(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(t,e={}){let n=(await b(this.config,{query:`
816
816
  query getAccountForEmail($email: String!) {
817
817
  users(search: $email) {
818
818
  nodes {
819
- ${V}
819
+ ${z}
820
820
  }
821
821
  }
822
822
  }
823
- `,variables:{email:t.email}},e)).body.data)==null?void 0:i.users)==null?void 0:o.nodes)==null?void 0:a[0];if(!n)throw new Error("User not found.");return{data:K(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(t,e={}){var i;let n=(i=(await v(this.config,{query:`
823
+ `,variables:{email:t.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:M(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(t,e={}){let n=(await b(this.config,{query:`
824
824
  query getAccountForUsername($username: String!) {
825
825
  user(username: $username) {
826
- ${V}
826
+ ${z}
827
827
  }
828
828
  }
829
- `,variables:{username:t.username}},e)).body.data)==null?void 0:i.user;if(!n)throw new Error("User not found.");return{data:K(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(t,e={}){var u,l,p,d,c,g,m;let{repo:{namespace:r,name:n},cursor:i}=t,o=await v(this.config,{query:`
829
+ `,variables:{username:t.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:M(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await b(this.config,{query:`
830
830
  query getAccountsForRepo(
831
831
  $fullPath: ID!
832
832
  $after: String
@@ -837,7 +837,7 @@ query getAccountsForRepo(
837
837
  projectMembers(after: $after) {
838
838
  nodes {
839
839
  user {
840
- ${V}
840
+ ${z}
841
841
  }
842
842
  }
843
843
  pageInfo {
@@ -847,22 +847,22 @@ query getAccountsForRepo(
847
847
  }
848
848
  }
849
849
  }
850
- `,variables:{fullPath:`${r}/${n}`,after:i}},e),a=(d=(p=(l=(u=o.body.data)==null?void 0:u.project)==null?void 0:l.projectMembers)==null?void 0:p.nodes)==null?void 0:d.map(I=>I.user).filter(I=>I!==null);return{pageInfo:((m=(g=(c=o.body.data)==null?void 0:c.project)==null?void 0:g.projectMembers)==null?void 0:m.pageInfo)??{endCursor:null,hasNextPage:!1},data:(a==null?void 0:a.map(I=>K(I,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))??[]}}async getRepo(t,e={}){var i;let r=Y(t),n=await v(this.config,{query:`
850
+ `,variables:{fullPath:`${r}/${n}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>M(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(t,e={}){let r=J(t),n=await b(this.config,{query:`
851
851
  query getRepo($fullPath: ID!) {
852
852
  project(fullPath: $fullPath) {
853
- ${Tt}
853
+ ${Ut}
854
854
  }
855
855
  }
856
- `,variables:{fullPath:r}},e);if(!((i=n.body.data)!=null&&i.project))throw new Error(`Repository ${r} not found`);return{data:kt(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(Y).map((u,l)=>`
856
+ `,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:Gt(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(J).map((u,l)=>`
857
857
  getRepo_${l}: project(fullPath: "${u}") {
858
- ${Tt}
858
+ ${Ut}
859
859
  }
860
860
  `).join(`
861
- `),i=await v(this.config,{query:`
861
+ `),o=await b(this.config,{query:`
862
862
  query batchGetRepos {
863
863
  ${n}
864
864
  }
865
- `},e);if(!i.body.data)throw new Error(Oe(i.body.errors)||i.statusText||"Unknown error");let o=[],a=[];return t.forEach((u,l)=>{let p=i.body.data[`getRepo_${l}`];p?o.push(kt(p)):a.push({input:u})}),{data:o,errors:a}}async getRepos(t,e={}){let r=[];for(let o=0;o<t.length;o+=15)r.push(t.slice(o,o+15));return(await Promise.all(r.map(o=>this.getReposBase(o,e)))).reduce((o,a)=>({data:[...o.data,...a.data],errors:[...o.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(t,e={}){var i,o,a,u,l;let r=await v(this.config,{query:`
865
+ `},e);if(!o.body.data)throw new Error(Ue(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let c=o.body.data[`getRepo_${l}`];c?i.push(Gt(c)):a.push({input:u})}),{data:i,errors:a}}async getRepos(t,e={}){let r=[];for(let i=0;i<t.length;i+=15)r.push(t.slice(i,i+15));return(await Promise.all(r.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(t,e={}){let r=await b(this.config,{query:`
866
866
  query getReposForCurrentUser($after: String) {
867
867
  projects(membership: true first: 100 after: $after) {
868
868
  pageInfo {
@@ -870,11 +870,11 @@ query getReposForCurrentUser($after: String) {
870
870
  hasNextPage
871
871
  }
872
872
  nodes {
873
- ${Tt}
873
+ ${Ut}
874
874
  }
875
875
  }
876
876
  }
877
- `,variables:{after:t.cursor}},e);if(!((i=r.body.data)!=null&&i.projects))throw new Error(Oe(r.body.errors)||r.statusText||"Unknown error");let n=((a=(o=r.body.data)==null?void 0:o.projects)==null?void 0:a.nodes)||[];return{pageInfo:(l=(u=r.body.data)==null?void 0:u.projects)==null?void 0:l.pageInfo,data:n.map(kt)}}async getRefs(t,e,r={}){var u;let n=Y(e.repo),i=new URL(`${Te(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);i.searchParams.set("page",((u=e.page)==null?void 0:u.toString())||"1"),i.searchParams.set("per_page",L.toString());let o=await this.config.request({url:i.toString(),headers:y(r.token||this.config.token)}),a=o.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:o.body.map(l=>({name:l.name,commit:{oid:l.commit.id,authoredDate:new Date(l.commit.authored_date),committedDate:new Date(l.commit.committed_date)}}))}}async getBranches(t,e={}){return this.getRefs("branches",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getBlame(t,e={}){let r=Y(t.repo),n=new URL(`${Te(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/blame`);n.searchParams.set("ref",t.ref);let i=await this.config.request({url:n.toString(),headers:y(e.token||this.config.token)}),o=0;return{data:{ranges:i.body.map(a=>{let u=o+1;return o+=a.lines.length,{startingLine:u,endingLine:o,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(t,e={}){var a,u,l,p;let r="";(a=t.repo)!=null&&a.id?r=`projectId:"${t.repo.id}"`:(u=t.repo)!=null&&u.namespace&&((l=t.repo)!=null&&l.name)&&(r=`projectPath:"${t.repo.namespace}/${t.repo.name}"`);let n=Ys[t.association],i=await v(this.config,{query:`
877
+ `,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(Ue(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(Gt)}}async getRefs(t,e,r={}){let n=J(e.repo),o=new URL(`${Le(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",v.toString());let i=await this.config.request({url:o.toString(),headers:h(r.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(u=>({name:u.name,commit:{oid:u.commit.id,authoredDate:new Date(u.commit.authored_date),committedDate:new Date(u.commit.committed_date)}}))}}async getBranches(t,e={}){return this.getRefs("branches",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getBlame(t,e={}){let r=J(t.repo),n=new URL(`${Le(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/blame`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:h(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(t,e={}){let r="";t.repo?.id?r=`projectId:"${t.repo.id}"`:t.repo?.namespace&&t.repo?.name&&(r=`projectPath:"${t.repo.namespace}/${t.repo.name}"`);let n=Zs[t.association],o=await b(this.config,{query:`
878
878
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
879
879
  user(username: $username) {
880
880
  ${n}(state:opened first:100 after:$cursor labels: $labelNames${r?` ${r}`:""}) {
@@ -883,12 +883,12 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
883
883
  hasNextPage
884
884
  }
885
885
  nodes {
886
- ${Ur(!0,!0,!0)}
886
+ ${Cr(!0,!0,!0)}
887
887
  }
888
888
  }
889
889
  }
890
890
  }
891
- `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!i.body.data)throw new Error(Oe(i.body.errors)||i.statusText||"Unknown error");if(!i.body.data.user)throw new Error("User not found");let o=i.body.data.user[n];if(!o)throw new Error("Unexpected response");return{pageInfo:o.pageInfo,data:((p=o.nodes)==null?void 0:p.filter(d=>t.includeFromArchivedRepos||!d.project.archived).map(d=>$r(d,Lr(d.project),Lr(d.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))||[]}}async getPullRequestsAssociatedWithUser(t,e={}){var D,q;let[r,n,i]=((D=t.cursor)==null?void 0:D.split(";"))||[void 0,void 0,void 0],o=(r==null?void 0:r.split("-"))||[],a=(n==null?void 0:n.split("-"))||[],u=(i==null?void 0:i.split("-"))||[],l=[],p=[],d=[],c=0;do{let A=t.repos&&t.repos[c];o[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:o[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...A&&{repo:A}},e)),a[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...A&&{repo:A}},e)),u[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...A&&{repo:A}},e)),c++}while(c<(((q=t.repos)==null?void 0:q.length)||0));let g=[l,p,d].flat(),m=await Promise.all(g),I={},f=[],b=A=>{I[A.id]||(I[A.id]=!0,f.push(A))},h=!1,E=m.map((A,ur)=>{var lr;let me="";return A&&A.data.forEach(b),A!=null&&A.pageInfo.hasNextPage?(h=!0,me+=`${A.pageInfo.endCursor||"null"}`):me+="null",(lr=t.repos)!=null&&lr.length&&(ur+1)%t.repos.length!==0?me+="-":ur+1<m.length&&(me+=";"),me}).join("");return{pageInfo:{hasNextPage:h,endCursor:E},data:f}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:i,labelNames:o,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"),i&&d("assigneeUsername",i[0],"String"),o&&d("labelName",o,"[String]"),r!=null&&d("draft",r,"Boolean"),a&&d("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(t,e={},r){var f,b,h;let{cursor:n,repo:i}=t||{},o=Y(i),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),p={fullPath:o,...a},d=await v(this.config,{query:`
891
+ `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!o.body.data)throw new Error(Ue(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[n];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:i.nodes?.filter(a=>t.includeFromArchivedRepos||!a.project.archived).map(a=>Dr(a,qr(a.project),qr(a.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[]}}async getPullRequestsAssociatedWithUser(t,e={}){let[r,n,o]=t.cursor?.split(";")||[void 0,void 0,void 0],i=r?.split("-")||[],a=n?.split("-")||[],u=o?.split("-")||[],l=[],c=[],p=[],d=0;do{let E=t.repos&&t.repos[d];i[d]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:i[d],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...E&&{repo:E}},e)),a[d]==="null"?c.push(null):c.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[d],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...E&&{repo:E}},e)),u[d]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:u[d],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...E&&{repo:E}},e)),d++}while(d<(t.repos?.length||0));let g=[l,c,p].flat(),m=await Promise.all(g),y={},R=[],T=E=>{y[E.id]||(y[E.id]=!0,R.push(E))},pe=!1,os=m.map((E,ar)=>{let de="";return E&&E.data.forEach(T),E?.pageInfo.hasNextPage?(pe=!0,de+=`${E.pageInfo.endCursor||"null"}`):de+="null",t.repos?.length&&(ar+1)%t.repos.length!==0?de+="-":ar+1<m.length&&(de+=";"),de}).join("");return{pageInfo:{hasNextPage:pe,endCursor:os},data:R}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=t||{},u={},l=[],c=[],p=(d,g,m)=>{l.push(`$${d}: ${m}`),c.push(`${d}: $${d}`),u[d]=g};return e&&p("updatedBefore",e,"Time"),n&&p("authorUsername",n,"String"),o&&p("assigneeUsername",o[0],"String"),i&&p("labelName",i,"[String]"),r!=null&&p("draft",r,"Boolean"),a&&p("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:c}}async getPullRequestsForRepoBase(t,e={},r){let{cursor:n,repo:o}=t||{},i=J(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),c={fullPath:i,...a},p=await b(this.config,{query:`
892
892
  query getPullRequestsForRepo(
893
893
  $fullPath: ID!
894
894
  $after: String
@@ -913,19 +913,19 @@ query getPullRequestsForRepo(
913
913
  hasNextPage
914
914
  }
915
915
  nodes {
916
- ${Ur(!1,!0,!0)}
916
+ ${Cr(!1,!0,!0)}
917
917
  }
918
918
  }
919
919
  }
920
920
  }
921
- `,variables:{...p,after:n}},e),c=[],g=(f=d.body.data)==null?void 0:f.project;if(!r&&(g!=null&&g.archived))return{pageInfo:null,data:[]};let m=ke(g||{id:"",fullPath:"",webUrl:""});return(((b=g==null?void 0:g.mergeRequests)==null?void 0:b.nodes)||[]).forEach(R=>{c.push($r(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:i,authorLogin:o,labelNames:a,isDraft:u,reviewRequestedLogin:l}=t;return{data:(await Promise.all(r.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:n,updatedBefore:i,authorLogin:o,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,t.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(t,e={}){var a,u,l;let{pullRequest:r}=t,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
921
+ `,variables:{...c,after:n}},e),d=[],g=p.body.data?.project;if(!r&&g?.archived)return{pageInfo:null,data:[]};let m=$e(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(R=>{d.push(Dr(R,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.pageInfo,data:d}}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(p=>this.getPullRequestsForRepoBase({repo:p,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,t.includeFromArchivedRepos??!1)))).flatMap(p=>p.data)}}async closePullRequest(t,e={}){let{pullRequest:r}=t,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
922
922
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
923
923
  errors,
924
924
  mergeRequest {
925
925
  id
926
926
  }
927
927
  }
928
- }`,o=(a=(await v(this.config,{query:n,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString()}},e)).body.data)==null?void 0:a.mergeRequestUpdate;if(!((u=o==null?void 0:o.mergeRequest)!=null&&u.id)||((l=o==null?void 0:o.errors)==null?void 0:l.length)!==0)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){var u,l,p,d;let{pullRequest:r,mergeStrategy:n}=t;if(!((u=r.headRef)!=null&&u.oid))throw new Error('GitLab requires "headRef.oid" for this function.');let i=`mutation MergePullRequest(
928
+ }`,i=(await b(this.config,{query:n,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t;if(!r.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
929
929
  $fullPath: ID!,
930
930
  $pullRequestId: String!,
931
931
  $expectedSourceSha: String!,
@@ -942,59 +942,59 @@ query getPullRequestsForRepo(
942
942
  id
943
943
  }
944
944
  }
945
- }`,a=(l=(await v(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),expectedSourceSha:r.headRef.oid,squash:n==="SQUASH"}},e)).body.data)==null?void 0:l.mergeRequestAccept;if(!((p=a==null?void 0:a.mergeRequest)!=null&&p.id)||((d=a==null?void 0:a.errors)==null?void 0:d.length)!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(t,e={}){var u,l,p;let{pullRequest:r,milestone:n}=t;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
945
+ }`,a=(await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),expectedSourceSha:r.headRef.oid,squash:n==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(t,e={}){let{pullRequest:r,milestone:n}=t;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
946
946
  mergeRequestSetMilestone(input: { projectPath: $fullPath, iid: $pullRequestId, milestoneId: $milestoneGraphQLId }) {
947
947
  errors,
948
948
  mergeRequest {
949
949
  id
950
950
  }
951
951
  }
952
- }`,o=await v(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),milestoneGraphQLId:n==null?void 0:n.graphQLId}},e),a=(u=o.body.data)==null?void 0:u.mergeRequestSetMilestone;if(!((l=a==null?void 0:a.mergeRequest)!=null&&l.id)||o.body.errors||((p=a==null?void 0:a.errors)==null?void 0:p.length)!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(t,e={}){var u,l,p;let{pullRequest:r,isDraft:n}=t,i=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
952
+ }`,i=await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),milestoneGraphQLId:n?.graphQLId}},e),a=i.body.data?.mergeRequestSetMilestone;if(!a?.mergeRequest?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(t,e={}){let{pullRequest:r,isDraft:n}=t,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
953
953
  mergeRequestSetDraft(input: { projectPath: $fullPath, iid: $pullRequestId, draft: $isDraft }) {
954
954
  errors,
955
955
  mergeRequest {
956
956
  id
957
957
  }
958
958
  }
959
- }`,a=(u=(await v(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),isDraft:n}},e)).body.data)==null?void 0:u.mergeRequestSetDraft;if(!((l=a==null?void 0:a.mergeRequest)!=null&&l.id)||((p=a==null?void 0:a.errors)==null?void 0:p.length)!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(t,e={}){var l,p,d;let{pullRequest:r,reviewers:n}=t,i=n.map(c=>{if(!c.username)throw new Error('GitLab requires reviewer "username" for this function.');return c.username}),o=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
959
+ }`,a=(await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),isDraft:n}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires reviewer "username" for this function.');return l.username}),i=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
960
960
  mergeRequestSetReviewers(input: { projectPath: $fullPath, iid: $pullRequestId, reviewerUsernames: $reviewerUsernames }) {
961
961
  errors,
962
962
  mergeRequest {
963
963
  id
964
964
  }
965
965
  }
966
- }`,u=(l=(await v(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),reviewerUsernames:i}},e)).body.data)==null?void 0:l.mergeRequestSetReviewers;if(!((p=u==null?void 0:u.mergeRequest)!=null&&p.id)||((d=u==null?void 0:u.errors)==null?void 0:d.length)!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(t,e={}){var u,l,p;let{pullRequest:r,reviewer:n}=t;if(!n.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let i=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
966
+ }`,u=(await b(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),reviewerUsernames:o}},e)).body.data?.mergeRequestSetReviewers;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(t,e={}){let{pullRequest:r,reviewer:n}=t;if(!n.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
967
967
  mergeRequestReviewerRereview(input: { projectPath: $fullPath, iid: $pullRequestId, userId: $reviewerUserId }) {
968
968
  errors,
969
969
  mergeRequest {
970
970
  id
971
971
  }
972
972
  }
973
- }`,a=(u=(await v(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),reviewerUserId:n.graphQLId}},e)).body.data)==null?void 0:u.mergeRequestReviewerRereview;if(!((l=a==null?void 0:a.mergeRequest)!=null&&l.id)||((p=a==null?void 0:a.errors)==null?void 0:p.length)!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(t,e={}){let{pullRequest:r,reviewers:n}=t,i=r.reviews;if(!i)throw new Error('GitLab requires "reviews" for this function.');let o=n.filter(a=>i.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(o.map(a=>this.reRequestPullRequestReview({pullRequest:r,reviewer:a},e)))}async setPullRequestAssignees(t,e={}){var l,p,d;let{pullRequest:r,assignees:n}=t,i=n.map(c=>{if(!c.username)throw new Error('GitLab requires assignee "username" for this function.');return c.username}),o=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
973
+ }`,a=(await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),reviewerUserId:n.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(t,e={}){let{pullRequest:r,reviewers:n}=t,o=r.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=n.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:r,reviewer:a},e)))}async setPullRequestAssignees(t,e={}){let{pullRequest:r,assignees:n}=t,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires assignee "username" for this function.');return l.username}),i=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
974
974
  mergeRequestSetAssignees(input: { projectPath: $fullPath, iid: $pullRequestId, assigneeUsernames: $assigneeUsernames }) {
975
975
  errors,
976
976
  mergeRequest {
977
977
  id
978
978
  }
979
979
  }
980
- }`,u=(l=(await v(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),assigneeUsernames:i}},e)).body.data)==null?void 0:l.mergeRequestSetAssignees;if(!((p=u==null?void 0:u.mergeRequest)!=null&&p.id)||((d=u==null?void 0:u.errors)==null?void 0:d.length)!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(t,e={}){var u,l,p;let{pullRequest:r,labels:n}=t,i=n.map(d=>{if(!d.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return d.graphQLId}),o=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
980
+ }`,u=(await b(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),assigneeUsernames:o}},e)).body.data?.mergeRequestSetAssignees;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(t,e={}){let{pullRequest:r,labels:n}=t,o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return u.graphQLId}),i=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
981
981
  mergeRequestSetLabels(input: { projectPath: $fullPath, iid: $pullRequestId, labelIds: $labelGraphQLIds }) {
982
982
  mergeRequest {
983
983
  id
984
984
  }
985
985
  }
986
- }`;if(!((p=(l=(u=(await v(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:i}},e)).body.data)==null?void 0:u.mergeRequestSetLabels)==null?void 0:l.mergeRequest)!=null&&p.id))throw new Error("Could not set pull request labels")}async getIssue(t,e={}){var i,o,a;let r=un(t),n=await v(this.config,{query:`
986
+ }`;if(!(await b(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(t,e={}){let r=ln(t),n=await b(this.config,{query:`
987
987
  query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
988
988
  project(fullPath: $projectId) {
989
989
  id
990
990
  fullPath
991
991
  webUrl
992
992
  issue(iid: $issueNumber) {
993
- ${Ot}
993
+ ${$t}
994
994
  }
995
995
  }
996
996
  }
997
- `,variables:{issueNumber:t.number,projectId:r}},e);if(!((i=n.body.data)!=null&&i.project))throw new Error(`Repository ${r} not found`);if(!((a=(o=n.body.data)==null?void 0:o.project)!=null&&a.issue))throw new Error(`Issue ${t.number} not found`);return{data:xt(n.body.data.project.issue,ke(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(t){let{updatedBefore:e,authorLogin:r,assigneeLogins:n,labelNames:i}=t||{},o={},a=[],u=[],l=(p,d,c)=>{a.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),o[p]=d};return e&&l("updatedBefore",e,"Time"),r&&l("authorUsername",r,"String"),n&&l("assigneeUsername",n[0],"String"),i&&l("labelName",i,"[String]"),{variables:o,variableTypes:a,issueArguments:u}}async getIssuesForRepo(t,e={}){var f,b,h;let{cursor:r,repo:n}=t||{},i=Y(n),{variables:o,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:i,...o},p=`
997
+ `,variables:{issueNumber:t.number,projectId:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${t.number} not found`);return{data:Tt(n.body.data.project.issue,$e(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(t){let{updatedBefore:e,authorLogin:r,assigneeLogins:n,labelNames:o}=t||{},i={},a=[],u=[],l=(c,p,d)=>{a.push(`$${c}: ${d}`),u.push(`${c}: $${c}`),i[c]=p};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={}){let{cursor:r,repo:n}=t||{},o=J(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:o,...i},c=`
998
998
  query GetIssuesFromProject(
999
999
  $fullPath: ID!
1000
1000
  $after: String
@@ -1014,7 +1014,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1014
1014
  ${u.length?u.join(" "):""}
1015
1015
  ) {
1016
1016
  nodes {
1017
- ${Ot}
1017
+ ${$t}
1018
1018
  }
1019
1019
  pageInfo {
1020
1020
  endCursor
@@ -1022,11 +1022,11 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1022
1022
  }
1023
1023
  }
1024
1024
  }
1025
- }`,d=await v(this.config,{query:p,variables:{...l,after:r}},e),c=[],g=(f=d.body.data)==null?void 0:f.project,m=ke(g||{id:"",fullPath:"",webUrl:""});return(((b=g==null?void 0:g.issues)==null?void 0:b.nodes)||[]).forEach(R=>{c.push(xt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:((h=g==null?void 0:g.issues)==null?void 0:h.pageInfo)??{endCursor:null,hasNextPage:!1},data:c.sort((R,E)=>(R.updatedDate||R.createdDate).getTime()-(E.updatedDate||E.createdDate).getTime())}}async getIssuesForRepos(t,e={}){var g,m,I,f,b;let{cursor:r}=t||{},n=t.repoIds.map(h=>h.toString().startsWith(ue)?h:`${ue}${h}`),{variables:i,variableTypes:o,mergeRequestArguments:a}=this.getVariablesForPullRequests(t),u={projectIds:n,...i},l=`
1025
+ }`,p=await b(this.config,{query:c,variables:{...l,after:r}},e),d=[],g=p.body.data?.project,m=$e(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(R=>{d.push(Tt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:d.sort((R,T)=>(R.updatedDate||R.createdDate).getTime()-(T.updatedDate||T.createdDate).getTime())}}async getIssuesForRepos(t,e={}){let{cursor:r}=t||{},n=t.repoIds.map(g=>g.toString().startsWith(ne)?g:`${ne}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(t),u={projectIds:n,...o},l=`
1026
1026
  query GetIssuesFromProject(
1027
1027
  $projectIds: [ID!]
1028
1028
  $after: String
1029
- ${o.length?o.join(" "):""}
1029
+ ${i.length?i.join(" "):""}
1030
1030
  ) {
1031
1031
  projects(
1032
1032
  ids: $projectIds
@@ -1048,24 +1048,24 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1048
1048
  ${a.length?a.join(" "):""}
1049
1049
  ) {
1050
1050
  nodes {
1051
- ${Ot}
1051
+ ${$t}
1052
1052
  }
1053
1053
  }
1054
1054
  }
1055
1055
  }
1056
- }`,p=await v(this.config,{query:l,variables:{...u,after:r}},e),d=[];return(((m=(g=p.body.data)==null?void 0:g.projects)==null?void 0:m.nodes)||[]).forEach(h=>{var D;if(!t.includeFromArchivedRepos&&h.archived)return;let R=ke(h);(((D=h.issues)==null?void 0:D.nodes)||[]).forEach(q=>d.push(xt(q,R,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:((b=(f=(I=p.body)==null?void 0:I.data)==null?void 0:f.projects)==null?void 0:b.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 i=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1056
+ }`,c=await b(this.config,{query:l,variables:{...u,after:r}},e),p=[];return(c.body.data?.projects?.nodes||[]).forEach(g=>{if(!t.includeFromArchivedRepos&&g.archived)return;let m=$e(g);(g.issues?.nodes||[]).forEach(R=>p.push(Tt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:c.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:p.sort((g,m)=>(g.updatedDate||g.createdDate).getTime()-(m.updatedDate||m.createdDate).getTime())}}async setIssueState(t,e={}){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!) {
1057
1057
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1058
1058
  issue {
1059
1059
  id
1060
1060
  }
1061
1061
  }
1062
- }`;if(!((l=(u=(a=(await v(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,status:n==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data)==null?void 0:a.updateIssue)==null?void 0:u.issue)!=null&&l.id))throw new Error("Could not set issue status")}async closeIssue(t,e={}){await this.setIssueState({...t,state:"CLOSED"},e)}async reOpenIssue(t,e={}){await this.setIssueState({...t,state:"OPEN"},e)}async setIssueLabels(t,e={}){var u,l,p;let{issue:r,labels:n}=t;if(!r.repository)throw new Error('GitLab requires a "repository" for this function.');let i=n.map(d=>{if(!d.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return d.graphQLId}),o=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
1062
+ }`;if(!(await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,status:n==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue status")}async closeIssue(t,e={}){await this.setIssueState({...t,state:"CLOSED"},e)}async reOpenIssue(t,e={}){await this.setIssueState({...t,state:"OPEN"},e)}async setIssueLabels(t,e={}){let{issue:r,labels:n}=t;if(!r.repository)throw new Error('GitLab requires a "repository" for this function.');let o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return u.graphQLId}),i=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
1063
1063
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, labelIds: $labelGraphQLIds }) {
1064
1064
  issue {
1065
1065
  id
1066
1066
  }
1067
1067
  }
1068
- }`;if(!((p=(l=(u=(await v(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,labelGraphQLIds:i}},e)).body.data)==null?void 0:u.updateIssue)==null?void 0:l.issue)!=null&&p.id))throw new Error("Could not set issue labels")}async setIssueMilestone(t,e={}){var u,l,p;let{issue:r,milestone:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let i=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1068
+ }`;if(!(await b(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(t,e={}){let{issue:r,milestone:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1069
1069
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, milestoneId: $milestoneId }) {
1070
1070
  errors
1071
1071
  issue {
@@ -1075,14 +1075,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1075
1075
  }
1076
1076
  }
1077
1077
  }
1078
- }`,o=await v(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,milestoneId:(n==null?void 0:n.id)??null}},e),a=(u=o.body.data)==null?void 0:u.updateIssue;if(!((l=a==null?void 0:a.issue)!=null&&l.id)||o.body.errors||((p=a==null?void 0:a.errors)==null?void 0:p.length)!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(t,e={}){var l,p,d;let{issue:r,assignees:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let i=n.map(c=>c.username),o=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1078
+ }`,i=await b(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,milestoneId:n?.id??null}},e),a=i.body.data?.updateIssue;if(!a?.issue?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(t,e={}){let{issue:r,assignees:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=n.map(l=>l.username),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1079
1079
  issueSetAssignees(input: { projectPath: $fullPath, iid: $issueId, assigneeUsernames: $assigneeUsernames }) {
1080
1080
  errors,
1081
1081
  issue {
1082
1082
  id
1083
1083
  }
1084
1084
  }
1085
- }`,u=(l=(await v(this.config,{query:o,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,assigneeUsernames:i}},e)).body.data)==null?void 0:l.issueSetAssignees;if(!((p=u==null?void 0:u.issue)!=null&&p.id)||((d=u==null?void 0:u.errors)==null?void 0:d.length)!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(t,e={}){var a,u,l,p,d,c,g;let{repo:{namespace:r,name:n},cursor:i}=t,o=await v(this.config,{query:`
1085
+ }`,u=(await b(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,issueId:r.number,assigneeUsernames:o}},e)).body.data?.issueSetAssignees;if(!u?.issue?.id||u?.errors?.length!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await b(this.config,{query:`
1086
1086
  query getLabelsForRepo(
1087
1087
  $fullPath: ID!
1088
1088
  $after: String
@@ -1093,7 +1093,7 @@ query getLabelsForRepo(
1093
1093
  webUrl
1094
1094
  milestones(after: $after) {
1095
1095
  nodes {
1096
- ${Bt}
1096
+ ${xt}
1097
1097
  }
1098
1098
  pageInfo {
1099
1099
  endCursor
@@ -1102,7 +1102,7 @@ query getLabelsForRepo(
1102
1102
  }
1103
1103
  }
1104
1104
  }
1105
- `,variables:{fullPath:`${r}/${n}`,after:i}},e);return{pageInfo:((l=(u=(a=o.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=o.body.data)==null?void 0:p.project)==null?void 0:d.milestones)==null?void 0:c.nodes)==null?void 0:g.map(m=>{var I,f;return Ft(m,((f=(I=o.body.data)==null?void 0:I.project)==null?void 0:f.webUrl)||"")}))??[]}}async getLabelsForRepo(t,e={}){var a,u,l,p,d,c,g;let{repo:{namespace:r,name:n},cursor:i}=t,o=await v(this.config,{query:`
1105
+ `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>Bt(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await b(this.config,{query:`
1106
1106
  query getLabelsForRepo(
1107
1107
  $fullPath: ID!
1108
1108
  $after: String
@@ -1112,7 +1112,7 @@ query getLabelsForRepo(
1112
1112
  ) {
1113
1113
  labels(after: $after) {
1114
1114
  nodes {
1115
- ${Qt}
1115
+ ${Nt}
1116
1116
  }
1117
1117
  pageInfo {
1118
1118
  endCursor
@@ -1121,37 +1121,94 @@ query getLabelsForRepo(
1121
1121
  }
1122
1122
  }
1123
1123
  }
1124
- `,variables:{fullPath:`${r}/${n}`,after:i}},e);return{pageInfo:((l=(u=(a=o.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=o.body.data)==null?void 0:p.project)==null?void 0:d.labels)==null?void 0:c.nodes)==null?void 0:g.map(jt))??[]}}async getTreeForRepo(t,e={}){let r=Y(t.repo),n=new URL(t.cursor??`${Te(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 i=await this.config.request({url:n.toString(),headers:y(e.token||this.config.token)}),o=i.headers.link;return{data:i.body.map(pn),pageInfo:{endCursor:o?o.substring(1,o.indexOf(">")):null,hasNextPage:!!o}}}};var mn="https://api.atlassian.com/ex/jira",xe=100,zt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Tr="/rest/api/2/search/jql",Or="/rest/api/2/search",Mt=(s,t,e,r)=>{var a,u,l,p;let n=s.fields.assignee,i=!r,o=(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:Ne(s.fields.creator,e,i),updatedDate:new Date(s.fields.updated),assignees:n?[Ne(n,e,i)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:r??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:Rn(s.fields.status),statusTransitions:((a=s.transitions)==null?void 0:a.map(hn))??[],components:((u=s.fields.components)==null?void 0:u.map(fn))??[],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:o.map(yn),fixVersions:s.fields.fixVersions.map(bn)}},hn=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}}},fn=s=>({description:s.description??null,id:s.id,name:s.name}),In=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,Ne=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:In(s,t,e)}),Rn=s=>{let t;switch(s.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:t}},yn=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}),bn=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),Z=(s,t,e)=>e?`${t.baseUrl||mn}/${e}`:`${(t==null?void 0:t.baseUrl)||s.baseUrl}`,_e=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${Z(s,e,r)}/rest/api/2/field`,headers:y(e.token||s.token)})).body},Be=async(s,t,e,r={})=>{let{number:n,resourceId:i,fields:o}=t||{},a=await s.request({url:`${Z(s,r,i)}/rest/api/2/issue/${n}?fields=${zt.join(",")}&expand=transitions`,headers:y(r.token||s.token)});return{data:Mt(a.body,o,e,i)}},Qe=async(s,t,e,r={})=>{let{cursor:n,resourceId:i,labelNames:o,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1125
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];o&&o.forEach(b=>u.push(`labels = "${b}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!i,d=p?Or:Tr,c=new URL(`${Z(s,r,i)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",xe.toString()),c.searchParams.set("fields",zt.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(b=>Mt(b,a,e,i)),I=!1,f="";return p?(I=m.length==xe,f=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,f=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:f}}},kr=async(s,t,e,r={})=>{let{cursor:n,resourceId:i,jql:o,fields:a}=t||{},u=[...zt],l=a==null?void 0:a.Sprint;l&&u.push(l);let p=!i,d=p?Or:Tr,c=new URL(`${Z(s,r,i)}${d}`);c.searchParams.set("jql",o.join(" AND ")),c.searchParams.set("maxResults",xe.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(b=>Mt(b,a,e,i)),I=!1,f="";return p?(I=m.length==xe,f=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,f=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:f}}},je=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:i,mentionLogin:o,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=t||{},c=[`project = "${l}"`,"statusCategory != Done"];return i&&c.push(`creator in ("${i}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),o&&c.push(`comment ~ "${o}"`),a&&a.forEach(g=>c.push(`labels = "${g}"`)),kr(s,{resourceId:p,jql:c,cursor:u,fields:d},e,r)},Fe=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:i,mentionLogin:o,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=t||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return i&&g.push(`creator in ("${i}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),o&&g.push(`comment ~ "${o}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),kr(s,{resourceId:p,jql:g,fields:d,cursor:u},e,r)},ze=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let i={fields:{labels:n.map(o=>o.name)}};await s.request({method:"PUT",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(i),headers:{...y(e.token||s.token),"Content-Type":"application/json"}})},Me=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let i={fields:{components:n.map(o=>({id:o.id}))}};await s.request({method:"PUT",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(i),headers:{...y(e.token||s.token),"Content-Type":"application/json"}})},We=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 i={transition:{id:n.id}};await s.request({method:"POST",url:`${Z(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(i),headers:{...y(e.token||s.token),"Content-Type":"application/json"}})},He=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,i=new URL(`${Z(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:i.toString(),headers:y(e.token||s.token)})).body}};var Re="https://api.atlassian.com/ex/jira",Wt=100,pe=class extends B{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((i,o)=>({...i,[o.name]:o.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){var o;let n=r.token||this.config.token;if(!n)return null;let i=this._resourceUrlCache[n];return i?i[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),((o=this._resourceUrlCache[n])==null?void 0:o[e.resourceId])??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),i=await this.config.request({url:`${r.baseUrl||Re}/${e.resourceId}/rest/api/2/myself`,headers:y(r.token||this.config.token)});return{data:{name:i.body.displayName,email:i.body.emailAddress,avatarUrl:i.body.avatarUrls["48x48"],id:i.body.accountId,username:i.body.displayName,url:n?`${n}/jira/people/${i.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,i=n?this._resourceUrlCache[n]||{}:void 0,o=r.body.map(a=>(i&&(i[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=i),{data:o}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||Re}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Wt.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let i=await this.config.request({url:n.toString(),headers:y(r.token||this.config.token)});return{pageInfo:{hasNextPage:i.body.values.length!==0,endCursor:(i.body.startAt+i.body.values.length).toString()},data:i.body.values.map(o=>({id:o.id,key:o.key,name:o.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,r={}){let n=[];return await Promise.all(e.resourceIds.map(async i=>{try{return await fr(o=>this.getJiraProjectsForResource({resourceId:i,cursor:o},r))}catch{return[]}})).then((...i)=>{i.forEach(o=>{n=n.concat(...o)})}),{data:n}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:i,cursor:o}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||Re}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Wt.toString()),o&&u.searchParams.set("startAt",o),u.searchParams.set("project",i);let l=await this.config.request({url:u.toString(),headers:y(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((o?parseInt(o):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Ne(p,a,!1))}}async getComponentsForJiraProject(e,r={}){return await He(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),i=await this.getResourceUrl({resourceId:e.resourceId},r);return await Be(this.config,{...e,fields:n},i,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),i=await this.getResourceUrl({resourceId:e.resourceId},r);return await je(this.config,{...e,fields:n},i,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),i=await this.getResourceUrl({resourceId:e.resourceId},r);return await Fe(this.config,{...e,fields:n},i,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),i=await this.getResourceUrl({resourceId:e.resourceId},r);return await Qe(this.config,{...e,fields:n},i,r)}async setIssueStatus(e,r={}){await We(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:i}=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 o={accountId:i==null?void 0:i.id};await this.config.request({method:"PUT",url:`${r.baseUrl||Re}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(o),headers:{...y(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await Me(this.config,e,r)}async setIssueLabels(e,r={}){await ze(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:i}=e,o=new URL(`${r.baseUrl||Re}/${n}/rest/api/2/label`);o.searchParams.set("maxResults",Wt.toString()),i&&o.searchParams.set("startAt",i);let a=await this.config.request({url:o.toString(),headers:y(r.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var de=class extends x{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=(e==null?void 0:e.baseUrl)||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await _e(this.config,{},e);this._issueFieldsCache[r]=n.reduce((i,o)=>({...i,[o.name]:o.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 i=await this.getIssueFieldsForResource(r);return await Be(this.config,{...e,fields:i},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 i=await this.getIssueFieldsForResource(r);return await je(this.config,{...e,fields:i},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 i=await this.getIssueFieldsForResource(r);return await Fe(this.config,{...e,fields:i},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 i=await this.getIssueFieldsForResource(r);return await Qe(this.config,{...e,fields:i},n,r)}async setIssueStatus(e,r={}){await We(this.config,e,r)}async setIssueLabels(e,r={}){await ze(this.config,e,r)}async setIssueComponents(e,r={}){await Me(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 He(this.config,e,r)}};var Je=class{constructor(){this.set=new Set;this.arr=[]}push(...t){let e=t.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}};var ye=(o=>(o[o.None=0]="None",o[o.Assignee=1]="Assignee",o[o.Creator=2]="Creator",o[o.Mention=3]="Mention",o[o.MentionInDescription=4]="MentionInDescription",o[o.MentionInComments=5]="MentionInComments",o))(ye||{});function xr(s,t){return s?`${ye[s]}:${t||""}`:t??null}function Nr(s){if(!s)return{category:0};let[t,e]=s.split(":");return t in ye?{category:ye[t],cursor:e||void 0}:{category:0,cursor:s}}var _r=100;function Ke(s){return s?s instanceof Date?s:new Date(s):null}var jr=`
1124
+ `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(_t)??[]}}async getTreeForRepo(t,e={}){let r=J(t.repo),n=new URL(t.cursor??`${Le(this.config,e)}/projects/${encodeURIComponent(r)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",t.branch);let o=await this.config.request({url:n.toString(),headers:h(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(dn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var hn="https://api.atlassian.com/ex/jira",Ge=100,Qt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Lr="/rest/api/2/search/jql",Ur="/rest/api/2/search",jt=(s,t,e,r)=>{let n=s.fields.assignee,o=!r,i=(s.fields[t?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:s.id,commentCount:s.fields.comment.comments.length,number:s.key,title:s.fields.summary,url:e?`${e}/browse/${s.key}`:null,closedDate:null,createdDate:new Date(s.fields.created),author:Te(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[Te(n,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:r??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:yn(s.fields.status),statusTransitions:s.transitions?.map(fn)??[],components:s.fields.components?.map(In)??[],type:s.fields.issuetype.name,upvoteCount:s.fields.votes?.votes||0,labels:s.fields.labels?.map(a=>({color:null,description:null,id:null,name:a}))??[],sprints:i.map(bn),fixVersions:s.fields.fixVersions.map(Pn)}},fn=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}}},In=s=>({description:s.description??null,id:s.id,name:s.name}),Rn=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,Te=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:Rn(s,t,e)}),yn=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}},bn=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}),Pn=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),V=(s,t,e)=>e?`${t.baseUrl||hn}/${e}`:`${t?.baseUrl||s.baseUrl}`,Oe=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${V(s,e,r)}/rest/api/2/field`,headers:h(e.token||s.token)})).body},ke=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${V(s,r,o)}/rest/api/2/issue/${n}?fields=${Qt.join(",")}&expand=transitions`,headers:h(r.token||s.token)});return{data:jt(a.body,i,e,o)}},xe=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1125
+ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(T=>u.push(`labels = "${T}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,c=!o,p=c?Ur:Lr,d=new URL(`${V(s,r,o)}${p}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",Ge.toString()),d.searchParams.set("fields",Qt.join(",")),d.searchParams.set("expand","transitions"),n&&(c?d.searchParams.set("startAt",n):d.searchParams.set("nextPageToken",n));let g=await s.request({url:d.toString(),headers:h(r.token||s.token)}),m=g.body.issues.map(T=>jt(T,a,e,o)),y=!1,R="";return c?(y=m.length==Ge,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},$r=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=[...Qt],l=a?.Sprint;l&&u.push(l);let c=!o,p=c?Ur:Lr,d=new URL(`${V(s,r,o)}${p}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",Ge.toString()),d.searchParams.set("fields",u.join(",")),d.searchParams.set("expand","transitions"),n&&(c?d.searchParams.set("startAt",n):d.searchParams.set("nextPageToken",n));let g=await s.request({url:d.toString(),headers:h(r.token||s.token)}),m=g.body.issues.map(T=>jt(T,a,e,o)),y=!1,R="";return c?(y=m.length==Ge,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},Ne=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:c,fields:p}=t||{},d=[`project = "${l}"`,"statusCategory != Done"];return o&&d.push(`creator in ("${o}")`),n&&n.length!==0&&d.push(`assignee in ("${n.join('", "')}")`),i&&d.push(`comment ~ "${i}"`),a&&a.forEach(g=>d.push(`labels = "${g}"`)),$r(s,{resourceId:c,jql:d,cursor:u,fields:p},e,r)},_e=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:c,fields:p}=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}"`)),$r(s,{resourceId:c,jql:g,fields:p,cursor:u},e,r)},Be=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${V(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...h(e.token||s.token),"Content-Type":"application/json"}})},Qe=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${V(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...h(e.token||s.token),"Content-Type":"application/json"}})},je=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${V(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...h(e.token||s.token),"Content-Type":"application/json"}})},Fe=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${V(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:h(e.token||s.token)})).body}};var he="https://api.atlassian.com/ex/jira",Ft=100,ie=class extends O{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Oe(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){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),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||he}/${e.resourceId}/rest/api/2/myself`,headers:h(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:h(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||he}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Ft.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:h(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 cr(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||he}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Ft.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:h(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(c=>c.accountType!=="app"&&c.active).map(c=>Te(c,a,!1))}}async getComponentsForJiraProject(e,r={}){return await Fe(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await ke(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Ne(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await _e(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await xe(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await je(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${r.baseUrl||he}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...h(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await Qe(this.config,e,r)}async setIssueLabels(e,r={}){await Be(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||he}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Ft.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:h(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 ae=class extends U{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await Oe(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:h(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?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:h(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await ke(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Ne(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await _e(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await xe(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await je(this.config,e,r)}async setIssueLabels(e,r={}){await Be(this.config,e,r)}async setIssueComponents(e,r={}){await Qe(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:h(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await Fe(this.config,e,r)}};var Mt=100,ze=class{constructor(){this.set=new Set;this.arr=[]}push(...t){let e=t.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}},W=async(s,t,e,r)=>{let n=t.token||s.token;if(!n)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},zt=s=>s?s instanceof Date?s:new Date(s):null,wn=`
1126
+ id
1127
+ name
1128
+ description
1129
+ state
1130
+ startDate
1131
+ targetDate
1132
+ url
1133
+ `,Gr=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:zt(s.startDate),targetDate:zt(s.targetDate),url:s.url}),Tr=async(s,t,e)=>{let r=`
1134
+ query GetProjects($first: Int!, $after: String) {
1135
+ projects(first: $first, after: $after) {
1136
+ nodes {
1137
+ ${wn}
1138
+ }
1139
+ pageInfo {
1140
+ hasNextPage
1141
+ endCursor
1142
+ }
1143
+ }
1144
+ }
1145
+ `;return(await W(s,t,r,{first:Mt,after:e})).projects},vn=`
1146
+ id
1147
+ name
1148
+ number
1149
+ description
1150
+ startsAt
1151
+ endsAt
1152
+ completedAt
1153
+ `,Or=s=>({id:s.id,name:s.name??`Cycle ${s.number}`,number:s.number,description:s.description??null,startsAt:new Date(s.startsAt),endsAt:new Date(s.endsAt),completedAt:zt(s.completedAt),url:""}),kr=async(s,t,e)=>{let r=`
1154
+ query GetCycles($first: Int!, $after: String) {
1155
+ cycles(first: $first, after: $after) {
1156
+ nodes {
1157
+ ${vn}
1158
+ }
1159
+ pageInfo {
1160
+ hasNextPage
1161
+ endCursor
1162
+ }
1163
+ }
1164
+ }
1165
+ `;return(await W(s,t,r,{first:Mt,after:e})).cycles},En=`
1166
+ id
1167
+ name
1168
+ color
1169
+ description
1170
+ `,xr=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),Nr=async(s,t,e)=>{let r=`
1171
+ query GetLabels($first: Int!, $after: String) {
1172
+ projectLabels(first: $first, after: $after) {
1173
+ nodes {
1174
+ ${En}
1175
+ }
1176
+ pageInfo {
1177
+ hasNextPage
1178
+ endCursor
1179
+ }
1180
+ }
1181
+ }
1182
+ `;return(await W(s,t,r,{first:Mt,after:e})).projectLabels};var fe=(i=>(i[i.None=0]="None",i[i.Assignee=1]="Assignee",i[i.Creator=2]="Creator",i[i.Mention=3]="Mention",i[i.MentionInDescription=4]="MentionInDescription",i[i.MentionInComments=5]="MentionInComments",i))(fe||{});function _r(s,t){return s?`${fe[s]}:${t||""}`:t??null}function Br(s){if(!s)return{category:0};let[t,e]=s.split(":");return t in fe?{category:fe[t],cursor:e||void 0}:{category:0,cursor:s}}var Qr=100;function We(s){return s?s instanceof Date?s:new Date(s):null}var zr=`
1126
1183
  id
1127
1184
  name
1128
1185
  key
1129
1186
  icon
1130
- `;function Pn(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var Br=`
1187
+ `;function Sn(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var jr=`
1131
1188
  id
1132
1189
  name
1133
1190
  avatarUrl
1134
- `;function Qr(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var wn=`
1191
+ `;function Fr(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var qn=`
1135
1192
  id
1136
1193
  name
1137
- `;function vn(s,t){if(s)return{id:s.id,name:s.name,key:(t==null?void 0:t.key)||null,namespace:null,resourceId:(t==null?void 0:t.id)||null}}var En=`
1194
+ `;function Cn(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var Dn=`
1138
1195
  id
1139
1196
  sortOrder
1140
1197
  name
1141
1198
  description
1142
1199
  status
1143
1200
  targetDate
1144
- `;function Sn(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:Ke(s.targetDate)}:null}function qn(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Cn=`
1201
+ `;function An(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:We(s.targetDate)}:null}function Ln(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Un=`
1145
1202
  id
1146
1203
  name
1147
1204
  color
1148
1205
  type
1149
- `;function Dn(s){return s?{id:s.id,name:s.name,color:s.color,category:qn(s.type)}:null}var Jt=`
1206
+ `;function $n(s){return s?{id:s.id,name:s.name,color:s.color,category:Ln(s.type)}:null}var Ht=`
1150
1207
  creator {
1151
- ${Br}
1208
+ ${jr}
1152
1209
  }
1153
1210
  assignee {
1154
- ${Br}
1211
+ ${jr}
1155
1212
  }
1156
1213
  archivedAt
1157
1214
  createdAt
@@ -1159,35 +1216,35 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1159
1216
  id
1160
1217
  identifier
1161
1218
  project {
1162
- ${wn}
1219
+ ${qn}
1163
1220
  }
1164
1221
  team {
1165
- ${jr}
1222
+ ${zr}
1166
1223
  }
1167
1224
  state {
1168
- ${Cn}
1225
+ ${Un}
1169
1226
  }
1170
1227
  title
1171
1228
  updatedAt
1172
1229
  url
1173
1230
  projectMilestone {
1174
- ${En}
1231
+ ${Dn}
1175
1232
  }
1176
- `;async function Ht(s){return{author:Qr(await s.creator),assignees:[Qr(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:Ke(s.archivedAt),createdDate:Ke(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:vn(await s.project,await s.team),state:Dn(await s.state),title:s.title,type:null,updatedDate:Ke(s.updatedAt),upvoteCount:null,url:s.url,milestone:Sn(await s.projectMilestone)}}var Ve=`
1233
+ `;async function Wt(s){return{author:Fr(await s.creator),assignees:[Fr(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:We(s.archivedAt),createdDate:We(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:Cn(await s.project,await s.team),state:$n(await s.state),title:s.title,type:null,updatedDate:We(s.updatedAt),upvoteCount:null,url:s.url,milestone:An(await s.projectMilestone)}}var Me=`
1177
1234
  nodes {
1178
- ${Jt}
1235
+ ${Ht}
1179
1236
  }
1180
1237
  pageInfo {
1181
1238
  hasNextPage
1182
1239
  endCursor
1183
1240
  }
1184
- `,ce=class extends B{async makeGraphQLRequest(t,e,r){let n=t.token||this.config.token;if(!n)throw new Error("Linear API key is required");let i=await this.config.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});if(i.status>=400)throw new Error(`Linear API request failed: ${i.status} ${i.statusText}`);let o=i.body;if(o.errors)throw new Error(`Linear GraphQL errors: ${o.errors.map(a=>a.message).join(", ")}`);return o.data}async fetchIssue(t,e){let r=`
1241
+ `,ue=class extends O{async fetchIssue(t,e){let r=`
1185
1242
  query GetIssue($identifier: String!) {
1186
1243
  issue(id: $identifier) {
1187
- ${Jt}
1244
+ ${Ht}
1188
1245
  }
1189
1246
  }
1190
- `;return(await this.makeGraphQLRequest(e,r,{identifier:t})).issue}async fetchOrganization(t){let e=`
1247
+ `;return(await W(this.config,e,r,{identifier:t})).issue}async fetchOrganization(t){let e=`
1191
1248
  query GetOrganization {
1192
1249
  organization {
1193
1250
  id
@@ -1195,15 +1252,15 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1195
1252
  urlKey
1196
1253
  }
1197
1254
  }
1198
- `;return(await this.makeGraphQLRequest(t,e)).organization}async fetchTeams(t){let e=`
1255
+ `;return(await W(this.config,t,e)).organization}async fetchTeams(t){let e=`
1199
1256
  query GetTeams {
1200
1257
  teams {
1201
1258
  nodes {
1202
- ${jr}
1259
+ ${zr}
1203
1260
  }
1204
1261
  }
1205
1262
  }
1206
- `;return(await this.makeGraphQLRequest(t,e)).teams}async rawRequest(t,e,r){return{data:await this.makeGraphQLRequest(t,e,r)}}async fetchViewer(t){let e=`
1263
+ `;return(await W(this.config,t,e)).teams}async rawRequest(t,e,r){return{data:await W(this.config,t,e,r)}}async fetchViewer(t){let e=`
1207
1264
  query GetViewer {
1208
1265
  viewer {
1209
1266
  id
@@ -1212,23 +1269,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1212
1269
  displayName
1213
1270
  }
1214
1271
  }
1215
- `;return(await this.makeGraphQLRequest(t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await Ht(r)}}async getLinearOrganization(t={}){let e=await this.fetchOrganization(t);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(t={}){return{data:(await this.fetchTeams(t)).nodes.map(Pn)}}async getCurrentUser(t={}){return{data:await this.fetchViewer(t)}}async getIssuesForCurrentUser(t,e={}){let{cursor:r}=t,{category:n,cursor:i}=Nr(r),o=await this.fetchViewer(e),a,u,l=new Je,p=async(d,c)=>{if(u||n>d)return;let g=await c(Math.max(_r-l.length,1),n===d?i:void 0);if(!g)return;let m=await Rt(g.nodes.map(Ht));l.push(...m),g.pageInfo.hasNextPage&&(a=d,u=g.pageInfo.endCursor)};return await p(1,async(d,c)=>{var m,I;return(I=(m=(await this.rawRequest(e,`
1272
+ `;return(await W(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await Wt(r)}}async getLinearOrganization(t={}){let e=await this.fetchOrganization(t);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(t={}){return{data:(await this.fetchTeams(t)).nodes.map(Sn)}}async getProjects(t={},e={}){let r=await Tr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Gr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await kr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Or),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await Nr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(xr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCurrentUser(t={}){return{data:await this.fetchViewer(t)}}async getIssuesForCurrentUser(t,e={}){let{cursor:r}=t,{category:n,cursor:o}=Br(r),i=await this.fetchViewer(e),a,u,l=new ze,c=async(p,d)=>{if(u||n>p)return;let g=await d(Math.max(Qr-l.length,1),n===p?o:void 0);if(!g)return;let m=await ht(g.nodes.map(Wt));l.push(...m),g.pageInfo.hasNextPage&&(a=p,u=g.pageInfo.endCursor)};return await c(1,async(p,d)=>(await this.rawRequest(e,`
1216
1273
  query GetAssignedIssues($first: Int!, $after: String) {
1217
1274
  viewer {
1218
1275
  issues: assignedIssues(first: $first, after: $after) {
1219
- ${Ve}
1276
+ ${Me}
1220
1277
  }
1221
1278
  }
1222
1279
  }
1223
- `,{first:d,after:c})).data)==null?void 0:m.viewer)==null?void 0:I.issues}),await p(2,async(d,c)=>{var m,I;return(I=(m=(await this.rawRequest(e,`
1280
+ `,{first:p,after:d})).data?.viewer?.issues),await c(2,async(p,d)=>(await this.rawRequest(e,`
1224
1281
  query GetCreatedIssues($first: Int!, $after: String) {
1225
1282
  viewer {
1226
1283
  issues: createdIssues(first: $first, after: $after) {
1227
- ${Ve}
1284
+ ${Me}
1228
1285
  }
1229
1286
  }
1230
1287
  }
1231
- `,{first:d,after:c})).data)==null?void 0:m.viewer)==null?void 0:I.issues}),await p(4,async(d,c)=>{var m;return(m=(await this.rawRequest(e,`
1288
+ `,{first:p,after:d})).data?.viewer?.issues),await c(4,async(p,d)=>(await this.rawRequest(e,`
1232
1289
  query GetMentionedIssues($first: Int!, $after: String) {
1233
1290
  issues(
1234
1291
  first: $first
@@ -1236,23 +1293,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1236
1293
  filter: {
1237
1294
  or: [{
1238
1295
  searchableContent: {
1239
- contains: "${o.displayName}"
1296
+ contains: "${i.displayName}"
1240
1297
  }
1241
1298
  },{
1242
1299
  searchableContent: {
1243
- contains: "${o.email}"
1300
+ contains: "${i.email}"
1244
1301
  }
1245
1302
  },{
1246
1303
  searchableContent: {
1247
- contains: "${o.name}"
1304
+ contains: "${i.name}"
1248
1305
  }
1249
1306
  }]
1250
1307
  }
1251
1308
  ){
1252
- ${Ve}
1309
+ ${Me}
1253
1310
  }
1254
1311
  }
1255
- `,{first:d,after:c})).data)==null?void 0:m.issues}),await p(5,async(d,c)=>{var f;let m=(f=(await this.rawRequest(e,`
1312
+ `,{first:p,after:d})).data?.issues),await c(5,async(p,d)=>{let m=(await this.rawRequest(e,`
1256
1313
  query GetCommentedIssues($first: Int!, $after: String) {
1257
1314
  comments(
1258
1315
  first: $first
@@ -1260,22 +1317,22 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1260
1317
  filter: {
1261
1318
  or: [{
1262
1319
  body: {
1263
- contains: "${o.displayName}"
1320
+ contains: "${i.displayName}"
1264
1321
  }
1265
1322
  },{
1266
1323
  body: {
1267
- contains: "${o.email}"
1324
+ contains: "${i.email}"
1268
1325
  }
1269
1326
  },{
1270
1327
  body: {
1271
- contains: "${o.name}"
1328
+ contains: "${i.name}"
1272
1329
  }
1273
1330
  }]
1274
1331
  }
1275
1332
  ){
1276
1333
  nodes {
1277
1334
  issue {
1278
- ${Jt}
1335
+ ${Ht}
1279
1336
  }
1280
1337
  }
1281
1338
  pageInfo {
@@ -1284,10 +1341,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1284
1341
  }
1285
1342
  }
1286
1343
  }
1287
- `,{first:d,after:c})).data)==null?void 0:f.comments;return m?{nodes:m.nodes.map(b=>b.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:xr(a,u)}}}async getIssues(t,e={}){var g;let{teams:r,projects:n,labels:i,cursor:o}=t,a=[];if(r&&r.length>0){let m=r.map(I=>`"${I}"`).join(", ");a.push(`team: { id: { in: [${m}] } }`)}if(n&&n.length>0){let m=n.map(I=>`"${I}"`).join(", ");a.push(`project: { id: { in: [${m}] } }`)}if(i&&i.length>0){let m=i.map(I=>`"${I}"`).join(", ");a.push(`labels: { name: { in: [${m}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",l=`
1344
+ `,{first:p,after:d})).data?.comments;return m?{nodes:m.nodes.map(R=>R.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:_r(a,u)}}}async getIssues(t,e={}){let{teams:r,projects:n,labels:o,cursor:i}=t,a=[];if(r&&r.length>0){let g=r.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(n&&n.length>0){let g=n.map(m=>`"${m}"`).join(", ");a.push(`project: { id: { in: [${g}] } }`)}if(o&&o.length>0){let g=o.map(m=>`"${m}"`).join(", ");a.push(`labels: { name: { in: [${g}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",l=`
1288
1345
  query GetIssues($first: Int!, $after: String) {
1289
1346
  issues(first: $first, after: $after${u?", ":""}${u}) {
1290
- ${Ve}
1347
+ ${Me}
1291
1348
  }
1292
1349
  }
1293
- `,d=(g=(await this.rawRequest(e,l,{first:_r,after:o})).data)==null?void 0:g.issues;return d?{data:await Rt(d.nodes.map(Ht)),pageInfo:{hasNextPage:d.pageInfo.hasNextPage,endCursor:d.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var M="https://api.trello.com",An=1e3,Ln=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),Un=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},ge=class extends B{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||M}/1/members/me?key=${t.appKey}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||M}/1/members/me/boards?fields=name&key=${t.appKey}&token=${e.token||this.config.token}&filter=open`,headers:y(e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${n}/lists?key=${r}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,i=await this.config.request({url:`${e.baseUrl||M}/1/members/${n}/?key=${r}&token=${e.token||this.config.token}`});return{data:Ln(i.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${n}/members?key=${r}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)})).body.map(o=>({id:o.id,name:o.fullName,username:o.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:i,filterText:o,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(c=>r.push(`label:"${c}"`));let p=`${o?`${o}`:""}${r.join(" ")} board:${i}`;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/search?key=${n}&query=${p}&cards_limit=${An}&token=${e.token||this.config.token}&card_members=true`,headers:y(e.token||this.config.token)})).body.cards.map(c=>Un(c,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||M}/1/cards/${e.id}?key=${t}&token=${n.token||this.config.token}&${r}`,headers:y(n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:i}=t;if(!i.id)throw new Error('Trello requires a status "id" for this function.');let o=`idList=${i.id}`;if(!(await this.updateIssue(r,n,o,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:i}=t,o=i.map(l=>l.id),a=`idMembers=${encodeURIComponent(o.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:i}=t,o=i.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(o)}`,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:i}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&closed=${i}`,headers:y(e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${n}/labels?key=${r}&token=${e.token||this.config.token}`,headers:y(e.token||this.config.token)})).body.map(o=>({color:o.color,description:null,id:o.id,name:o.name}))}}};var Xe={};j(Xe,{default:()=>$n});var $n={};var Ye={};j(Ye,{default:()=>Gn});var Gn={};var pt={};j(pt,{decode:()=>Vt,decodeV0:()=>xn,encode:()=>kn,validate:()=>On});var O=(e=>(e.Zero="0",e.One="1",e))(O||{}),k=(e=>(e.PullRequest="pr",e.Issue="issue",e))(k||{}),T=(c=>(c.Azure="azure",c.AzureDevOpsServer="azureDevOpsServer",c.Github="github",c.GithubEnterprise="githubEnterprise",c.Gitlab="gitlab",c.GitlabSelfHosted="gitlabSelfHosted",c.Bitbucket="bitbucket",c.BitbucketServer="bitbucketServer",c.Jira="jira",c.JiraServer="jiraServer",c.Linear="linear",c.Trello="trello",c))(T||{});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.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var et=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var tt=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 rt=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 st=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 nt=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 it=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 ot=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 at=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 ut=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 lt=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new et:new Ze;case"bitbucket":case"bitbucketServer":return t==="pr"?new rt:new tt;case"github":case"githubEnterprise":return t==="pr"?new nt:new st;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new ot:new it;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new at;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new ut;default:throw new Error("unknown provider")}},Tn=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")},On=s=>{if(s.version==="0"){Tn(s);return}lt(s.provider,s.entityType).validate(s)},kn=s=>lt(s.provider,s.entityType).encode(s),Vt=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return lt(t[0],t[1]).decode(t)},xn=(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 lt(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 dt={};j(dt,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>Jr,CHANGES_REQUESTED_BUCKET_ID:()=>rr,CONFLICTS_ACTION_CATEGORY:()=>Wr,CONFLICTS_BUCKET_ID:()=>er,DRAFT_ACTION_CATEGORY:()=>Xr,DRAFT_BUCKET_ID:()=>ir,FAILING_CI_ACTION_CATEGORY:()=>Mr,FAILING_CI_BUCKET_ID:()=>Zt,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Hr,NEEDS_MY_REVIEW_BUCKET_ID:()=>tr,OTHER_ACTION_CATEGORY:()=>Yr,OTHER_BUCKET_ID:()=>or,PINNED_BUCKET_ID:()=>Kt,READY_TO_MERGE_ACTION_CATEGORY:()=>Fr,READY_TO_MERGE_BUCKET_ID:()=>Xt,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>Vr,REVIEWER_COMMENTED_BUCKET_ID:()=>sr,SNOOZED_BUCKET_ID:()=>ar,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>zr,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Yt,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>Kr,WAITING_FOR_REVIEW_BUCKET_ID:()=>nr,getActionablePullRequests:()=>Zr,groupPullRequestsByAssignee:()=>Bn,groupPullRequestsByAuthor:()=>Qn,groupPullRequestsByGitKrakenTeam:()=>Mn,groupPullRequestsByRepo:()=>_n,groupPullRequestsByReviewer:()=>jn,groupPullRequestsByWorkspace:()=>zn,groupPullRequestsIntoBuckets:()=>Nn});var _=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Kt="pinned",Xt="readyToMerge",Yt="unassignedReviewers",Zt="failingCI",er="conflicts",tr="needsMyReview",rr="changesRequested",sr="reviewerCommented",nr="waitingForReview",ir="draft",or="other",ar="snoozed",Fr="readyToMerge",zr="unassignedReviewers",Mr="failingCI",Wr="conflicts",Hr="needsMyReview",Jr="changesRequested",Vr="reviewerCommented",Kr="waitingForReview",Xr="draft",Yr="other",Zr=(s,t,e)=>s.map(r=>{var u,l,p,d,c,g,m,I,f,b,h,R,E,D;let i={...r,...{suggestedActionCategory:Yr,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&&(i.viewer.isAuthor=((u=r.author)==null?void 0:u.id)===t.id,i.viewer.isAssignee=((l=r.assignees)==null?void 0:l.some(q=>q.id===t.id))??!1,i.viewer.isReviewer=((p=r.reviews)==null?void 0:p.some(q=>q.reviewer.id===t.id))??!1),i.viewer.canMerge=((d=r.permissions)==null?void 0:d.canMerge)??!0,i.hasConflicts=r.mergeableState==="CONFLICTS",i.failingCI=((g=(c=r.headCommit)==null?void 0:c.buildStatuses)==null?void 0:g.some(q=>q.state==="ERROR"||q.state==="FAILED"))||r.mergeableState==="FAILING_CHECKS",i.commentReviewCount=((m=r.reviews)==null?void 0:m.filter(q=>q.state==="COMMENTED").length)??0,i.approvalReviewCount=((I=r.reviews)==null?void 0:I.filter(q=>q.state==="APPROVED").length)??0,i.changeRequestReviewCount=((f=r.reviews)==null?void 0:f.filter(q=>q.state==="CHANGES_REQUESTED").length)??0;let o=(b=e==null?void 0:e.enrichedItemsByUniqueId)==null?void 0:b[r.uuid];o!=null&&(i.viewer.enrichedItems=o,o.some(q=>q.type==="pin")&&(i.viewer.pinned=!0,i.priority-=800),o.some(q=>q.type==="snooze")&&(i.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&&(i.codeSuggestionsCount=a),(!t||i.viewer.isAuthor||i.viewer.isAssignee&&!i.viewer.isReviewer)&&i.viewer.canMerge&&!i.isDraft&&!i.failingCI&&r.mergeableState==="MERGEABLE"&&(!r.reviewDecision||r.reviewDecision==="APPROVED")&&(i.viewer.shouldMerge=!0,i.suggestedActionCategory=Fr),(!t||i.viewer.isAuthor)&&r.isDraft&&(i.suggestedActionCategory=Xr),(!t||i.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(i.suggestedActionCategory=Kr,i.viewer.waitingOnReviews=!0),(!t||i.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(i.suggestedActionCategory=Vr),(!t||i.viewer.isAuthor)&&i.failingCI&&(i.suggestedActionCategory=Mr),(!t||i.viewer.isAuthor)&&i.hasConflicts&&(i.suggestedActionCategory=Wr),(!t||i.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||i.codeSuggestionsCount>0)&&(i.suggestedActionCategory=Jr),(!t||i.viewer.isAuthor)&&!((E=r.reviews)!=null&&E.length)&&(i.suggestedActionCategory=zr,i.viewer.shouldAssignReviewer=!0),t&&((D=r.reviews)!=null&&D.some(q=>q.reviewer.id===t.id&&q.state==="REVIEW_REQUESTED"))&&(i.suggestedActionCategory=Hr,i.viewer.shouldReview=!0),i}),Nn=(s,t,e)=>{var o,a,u,l,p,d,c,g,m,I,f,b;let r={pinned:_(Kt,"Pinned","thumbtack",((o=e==null?void 0:e.bucketPriorityOverride)==null?void 0:o.pinned)??-1),readyToMerge:_(Xt,"Ready to Merge","code-merge",((a=e==null?void 0:e.bucketPriorityOverride)==null?void 0:a.readyToMerge)??0),unassignedReviewers:_(Yt,"Unassigned Reviewers","user-plus",((u=e==null?void 0:e.bucketPriorityOverride)==null?void 0:u.unassignedReviewers)??1),failingCI:_(Zt,"Failing CI","circle-x",((l=e==null?void 0:e.bucketPriorityOverride)==null?void 0:l.failingCI)??2),conflicts:_(er,"Resolve Conflicts","triangle-exclamation",((p=e==null?void 0:e.bucketPriorityOverride)==null?void 0:p.conflicts)??3),needsMyReview:_(tr,"Needs My Review","eye",((d=e==null?void 0:e.bucketPriorityOverride)==null?void 0:d.needsMyReview)??4),changesRequested:_(rr,"Suggested Changes","file-plus",((c=e==null?void 0:e.bucketPriorityOverride)==null?void 0:c.changesRequested)??5),reviewerCommented:_(sr,"Reviewer Commented","comment",((g=e==null?void 0:e.bucketPriorityOverride)==null?void 0:g.reviewerCommented)??6),waitingForReview:_(nr,"Waiting for Review","circle-pause",((m=e==null?void 0:e.bucketPriorityOverride)==null?void 0:m.waitingForReview)??7),draft:_(ir,"Draft","compass-drafting",((I=e==null?void 0:e.bucketPriorityOverride)==null?void 0:I.draft)??8),other:_(or,"Other","ellipsis",((f=e==null?void 0:e.bucketPriorityOverride)==null?void 0:f.other)??9),snoozed:_(ar,"Snoozed","snooze",((b=e==null?void 0:e.bucketPriorityOverride)==null?void 0:b.snoozed)??10)},i=Zr(s,t,e).reduce((h,R)=>(h[R.uuid]=R,h),{});return s.forEach(h=>{let R=i[h.uuid],E=!0;if(R.viewer.snoozed){r[ar].pullRequests.push(h);return}R.viewer.pinned&&r[Kt].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[Xt].pullRequests.push(h),E=!1),R.viewer.shouldAssignReviewer&&(r[Yt].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.failingCI&&(r[Zt].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.hasConflicts&&(r[er].pullRequests.push(h),E=!1),R.viewer.shouldReview&&(r[tr].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&(R.reviewDecision==="CHANGES_REQUESTED"||R.codeSuggestionsCount>0)&&(r[rr].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.reviewDecision==="COMMENTED"&&(r[sr].pullRequests.push(h),E=!1),(!t||R.viewer.isAuthor)&&R.reviewDecision==="REVIEW_REQUESTED"&&(r[nr].pullRequests.push(h),E=!1),R.isDraft&&(r[ir].pullRequests.push(h),E=!1),E&&r[or].pullRequests.push(h)}),Object.values(r).forEach(h=>{h.pullRequests.sort((R,E)=>i[R.uuid].priority-i[E.uuid].priority)}),r},_n=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),te(t)},Bn=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 i=n.id;e[i]?e[i].pullRequests.push(r):e[i]={accountData:n,name:Pe(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:i}}):e[t].pullRequests.push(r)}),te(e)},Qn=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:Pe(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),te(e)},jn=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 i=n.reviewer.id;e[i]?e[i].pullRequests.push(r):e[i]={accountData:n.reviewer,name:Pe(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:i}}):e[t].pullRequests.push(r)}),te(e)},Fn=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}`))??[]},zn=(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((i,o)=>(Fn(o).forEach(u=>{i[u]?i[u].push(o):i[u]=[o]}),i),{});s.forEach(i=>{let{provider:o}=Vt(i.uuid),a=o==="github"?i.repository.graphQLId:i.repository.id,u=o==="azure"?[`${o}-${a}`,`${i.repository.project}-${i.repository.owner.login}`]:[`${o}-${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(i):r[c]={name:d.name,priority:0,pullRequests:[i],id:c,faIconName:"folder"}}),l||r[e].pullRequests.push(i)})}else r[e].pullRequests=s;return te(r)},Mn=(s,t,e,r)=>{let n="internal-no-team",i={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(o=>{var l,p,d;let a=!1,u=new Set;u.add((l=o.author)==null?void 0:l.id),(p=o.assignees)==null||p.forEach(c=>u.add(c.id)),(d=o.reviews)==null||d.forEach(c=>u.add(c.reviewer.id)),r.forEach(c=>{var m;if((m=c.members)==null?void 0:m.some(I=>{var b,h;let f=(h=(b=t[I.id])==null?void 0:b[e])==null?void 0:h.providerID;return f&&u.has(f)})){a=!0;let I=c.id;i[I]?i[I].pullRequests.push(o):i[I]={name:c.name,priority:0,pullRequests:[o],id:I,teamData:c}}}),a||i[n].pullRequests.push(o)}):i[n].pullRequests=s,te(i)};var ct={};j(ct,{getPullRequestRank:()=>Wn});var Wn=(s,t,e)=>{var o,a,u;let r=0,n,i;return(o=s.reviews)==null||o.forEach(l=>{l.reviewer.id===t&&(n=l.state),l.state==="CHANGES_REQUESTED"?i="CHANGES_REQUESTED":l.state==="APPROVED"&&i!=="CHANGES_REQUESTED"&&(i="APPROVED")}),i||(i="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),i==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:i=="CHANGES_REQUESTED"&&(r+=70),r};var gt={};j(gt,{default:()=>Hn});var Hn={};var mt={};j(mt,{default:()=>Jn});var Jn={};var ht={};j(ht,{default:()=>Vn});var Vn={};var es=s=>{let t={request:s==null?void 0:s.request};return{azureDevOps:new se({...t,...s==null?void 0:s.azureDevOps}),bitbucket:new ne({...t,...s==null?void 0:s.bitbucket}),bitbucketServer:new ie({...t,...s==null?void 0:s.bitbucketServer}),github:new ae({...t,...s==null?void 0:s.github}),gitlab:new le({...t,...s==null?void 0:s.gitlab}),jira:new pe({...t,...s==null?void 0:s.jira}),jiraServer:new de({...t,...s==null?void 0:s.jiraServer}),linear:new ce({...t,...s==null?void 0:s.linear}),trello:new ge({...t,...s==null?void 0:s.trello})}};var ts=(o=>(o.Conflicts="conflicts",o.Failure="failure",o.NotSet="notSet",o.Queued="queued",o.RejectedByPolicy="rejectedByPolicy",o.Succeeded="succeeded",o))(ts||{});var rs=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(rs||{});var Kn=es;var Xn={azureDevOps:Xe,bitbucket:Ye,bitbucketServer:qe,github:ct,gitlab:gt,gitProvider:dt,jira:mt,trello:ht,entityIdentifier:pt};
1350
+ `,p=(await this.rawRequest(e,l,{first:Qr,after:i})).data?.issues;return p?{data:await ht(p.nodes.map(Wt)),pageInfo:{hasNextPage:p.pageInfo.hasNextPage,endCursor:p.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var B="https://api.trello.com",Gn=1e3,Tn=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),On=(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}))}},le=class extends O{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||B}/1/members/me?key=${t.appKey}&token=${e.token||this.config.token}`,headers:h(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||B}/1/members/me/boards?fields=name&key=${t.appKey}&token=${e.token||this.config.token}&filter=open`,headers:h(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||B}/1/boards/${n}/lists?key=${r}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||B}/1/members/${n}/?key=${r}&token=${e.token||this.config.token}`});return{data:Tn(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||B}/1/boards/${n}/members?key=${r}&token=${e.token||this.config.token}`,headers:h(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(d=>r.push(`label:"${d}"`));let c=`${i?`${i}`:""}${r.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||B}/1/search?key=${n}&query=${c}&cards_limit=${Gn}&token=${e.token||this.config.token}&card_members=true`,headers:h(e.token||this.config.token)})).body.cards.map(d=>On(d,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||B}/1/cards/${e.id}?key=${t}&token=${n.token||this.config.token}&${r}`,headers:h(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||B}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(i)}`,headers:h(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||B}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&closed=${o}`,headers:h(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||B}/1/boards/${n}/labels?key=${r}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var He={};x(He,{default:()=>kn});var kn={};var Je={};x(Je,{default:()=>xn});var xn={};var it={};x(it,{decode:()=>Jt,decodeV0:()=>Qn,encode:()=>Bn,validate:()=>_n});var A=(e=>(e.Zero="0",e.One="1",e))(A||{}),L=(e=>(e.PullRequest="pr",e.Issue="issue",e))(L||{}),D=(d=>(d.Azure="azure",d.AzureDevOpsServer="azureDevOpsServer",d.Github="github",d.GithubEnterprise="githubEnterprise",d.Gitlab="gitlab",d.GitlabSelfHosted="gitlabSelfHosted",d.Bitbucket="bitbucket",d.BitbucketServer="bitbucketServer",d.Jira="jira",d.JiraServer="jiraServer",d.Linear="linear",d.Trello="trello",d))(D||{});var Ve=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var Ke=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var Xe=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 Ye=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 Ze=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for 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 et=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for 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 tt=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 rt=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 st=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 nt=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 ot=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new Ke:new Ve;case"bitbucket":case"bitbucketServer":return t==="pr"?new Ye:new Xe;case"github":case"githubEnterprise":return t==="pr"?new et:new Ze;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new rt:new tt;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new st;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new nt;default:throw new Error("unknown provider")}},Nn=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")},_n=s=>{if(s.version==="0"){Nn(s);return}ot(s.provider,s.entityType).validate(s)},Bn=s=>ot(s.provider,s.entityType).encode(s),Jt=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return ot(t[0],t[1]).decode(t)},Qn=(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 ot(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 at={};x(at,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>Kr,CHANGES_REQUESTED_BUCKET_ID:()=>tr,CONFLICTS_ACTION_CATEGORY:()=>Jr,CONFLICTS_BUCKET_ID:()=>Zt,DRAFT_ACTION_CATEGORY:()=>Zr,DRAFT_BUCKET_ID:()=>nr,FAILING_CI_ACTION_CATEGORY:()=>Hr,FAILING_CI_BUCKET_ID:()=>Yt,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Vr,NEEDS_MY_REVIEW_BUCKET_ID:()=>er,OTHER_ACTION_CATEGORY:()=>es,OTHER_BUCKET_ID:()=>or,PINNED_BUCKET_ID:()=>Vt,READY_TO_MERGE_ACTION_CATEGORY:()=>Mr,READY_TO_MERGE_BUCKET_ID:()=>Kt,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>Xr,REVIEWER_COMMENTED_BUCKET_ID:()=>rr,SNOOZED_BUCKET_ID:()=>ir,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Wr,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Xt,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>Yr,WAITING_FOR_REVIEW_BUCKET_ID:()=>sr,getActionablePullRequests:()=>ts,groupPullRequestsByAssignee:()=>zn,groupPullRequestsByAuthor:()=>Mn,groupPullRequestsByGitKrakenTeam:()=>Vn,groupPullRequestsByRepo:()=>Fn,groupPullRequestsByReviewer:()=>Wn,groupPullRequestsByWorkspace:()=>Jn,groupPullRequestsIntoBuckets:()=>jn});var G=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Vt="pinned",Kt="readyToMerge",Xt="unassignedReviewers",Yt="failingCI",Zt="conflicts",er="needsMyReview",tr="changesRequested",rr="reviewerCommented",sr="waitingForReview",nr="draft",or="other",ir="snoozed",Mr="readyToMerge",Wr="unassignedReviewers",Hr="failingCI",Jr="conflicts",Vr="needsMyReview",Kr="changesRequested",Xr="reviewerCommented",Yr="waitingForReview",Zr="draft",es="other",ts=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:es,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=r.author?.id===t.id,o.viewer.isAssignee=r.assignees?.some(u=>u.id===t.id)??!1,o.viewer.isReviewer=r.reviews?.some(u=>u.reviewer.id===t.id)??!1),o.viewer.canMerge=r.permissions?.canMerge??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=r.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=r.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=r.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=r.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(u=>u.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(u=>u.type==="snooze")&&(o.viewer.snoozed=!0));let a=e?.codeSuggestionsCountByPrUuid?.[r.uuid]?.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=Mr),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=Zr),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=Yr,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=Xr),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Hr),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=Jr),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=Kr),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=Wr,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=Vr,o.viewer.shouldReview=!0),o}),jn=(s,t,e)=>{let r={pinned:G(Vt,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:G(Kt,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:G(Xt,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:G(Yt,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:G(Zt,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:G(er,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:G(tr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:G(rr,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:G(sr,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:G(nr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:G(or,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:G(ir,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=ts(s,t,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){r[ir].pullRequests.push(i);return}a.viewer.pinned&&r[Vt].pullRequests.push(i),(!t||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(!i.reviewDecision||i.reviewDecision==="APPROVED")&&(r[Kt].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[Xt].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[Yt].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[Zt].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[er].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[tr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[rr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[sr].pullRequests.push(i),u=!1),a.isDraft&&(r[nr].pullRequests.push(i),u=!1),u&&r[or].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},Fn=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),X(t)},zn=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:Ie(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),X(e)},Mn=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:Ie(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),X(e)},Wn=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:Ie(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),X(e)},Hn=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],Jn=(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)=>(Hn(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Jt(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,c=u.reduce((p,d)=>n[d]?p.concat(n[d]):p,[]);c?.length&&c.forEach(p=>{l=!0;let d=p.id;r[d]?r[d].pullRequests.push(o):r[d]={name:p.name,priority:0,pullRequests:[o],id:d,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return X(r)},Vn=(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=>{let a=!1,u=new Set;u.add(i.author?.id),i.assignees?.forEach(l=>u.add(l.id)),i.reviews?.forEach(l=>u.add(l.reviewer.id)),r.forEach(l=>{if(l.members?.some(p=>{let d=t[p.id]?.[e]?.providerID;return d&&u.has(d)})){a=!0;let p=l.id;o[p]?o[p].pullRequests.push(i):o[p]={name:l.name,priority:0,pullRequests:[i],id:p,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,X(o)};var ut={};x(ut,{getPullRequestRank:()=>Kn});var Kn=(s,t,e)=>{let r=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===t&&(n=i.state),i.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":i.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),s.author?.id===t?r+=1e3:s.assignees?.find(i=>i.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 lt={};x(lt,{default:()=>Xn});var Xn={};var pt={};x(pt,{default:()=>Yn});var Yn={};var dt={};x(dt,{default:()=>Zn});var Zn={};var rs=s=>{let t={request:s?.request};return{azureDevOps:new Z({...t,...s?.azureDevOps}),bitbucket:new ee({...t,...s?.bitbucket}),bitbucketServer:new te({...t,...s?.bitbucketServer}),github:new se({...t,...s?.github}),gitlab:new oe({...t,...s?.gitlab}),jira:new ie({...t,...s?.jira}),jiraServer:new ae({...t,...s?.jiraServer}),linear:new ue({...t,...s?.linear}),trello:new le({...t,...s?.trello})}};var ss=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(ss||{});var ns=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(ns||{});var eo=rs;var to={azureDevOps:He,bitbucket:Je,bitbucketServer:we,github:ut,gitlab:lt,gitProvider:at,jira:pt,trello:dt,entityIdentifier:it};