@gitkraken/provider-apis 0.37.0 → 0.37.1

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 ht=Object.defineProperty;var ds=Object.getOwnPropertyDescriptor;var cs=Object.getOwnPropertyNames;var gs=Object.prototype.hasOwnProperty;var k=(s,t)=>{for(var e in t)ht(s,e,{get:t[e],enumerable:!0})},ms=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of cs(t))!gs.call(s,n)&&n!==e&&ht(s,n,{get:()=>t[n],enumerable:!(r=ds(t,n))||r.enumerable});return s};var hs=s=>ms(ht({},"__esModule",{value:!0}),s);var ao={};k(ao,{AzureDevOps:()=>ee,AzureDevopsUtils:()=>Ke,Bitbucket:()=>te,BitbucketServer:()=>re,BitbucketServerUtils:()=>qe,BitbucketUtils:()=>Xe,EntityIdentifierProviderType:()=>D,EntityIdentifierUtils:()=>lt,EntityType:()=>$,EntityVersion:()=>A,GitBuildStatusStage:()=>pr,GitBuildStatusState:()=>ge,GitDiffLineType:()=>ft,GitHub:()=>ne,GitHubIssueCloseReason:()=>ps,GitHubUtils:()=>dt,GitIssueState:()=>Se,GitLab:()=>ie,GitLabUtils:()=>ct,GitMergeStrategy:()=>Z,GitProviderUtils:()=>pt,GitPullRequestMergeableState:()=>j,GitPullRequestReviewState:()=>N,GitPullRequestState:()=>X,GraphQLErrors:()=>f,Jira:()=>ae,JiraServer:()=>ue,JiraUtils:()=>gt,Linear:()=>le,PullRequestAsyncStatus:()=>ls,Trello:()=>pe,TrelloUtils:()=>mt,Utils:()=>io,default:()=>oo,isFetch:()=>Pe});module.exports=hs(ao);var pr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(pr||{}),ge=(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))(ge||{}),Z=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(Z||{}),X=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(X||{}),N=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(N||{}),j=(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))(j||{}),ft=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(ft||{});var dr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},_=s=>!s||s.length===0?null:s.reduce((t,e)=>dr[e.state]>dr[t]?e.state:t,"APPROVED"),be=(s,t)=>s.name||s.username||s.email||t,Y=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 E=100;var cr=globalThis.fetch;var fs=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},It=s=>async({url:t,...e})=>{let r=await s(t,e);return fs(r)};var Pe=(s,t=!1)=>s.name==="fetch"||t;var O=class{constructor(t){let e=t?.request||cr;this.config={...t,request:Pe(e,t?.forceIsFetch)?It(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&Pe(t.request,t?.forceIsFetch??this.config.forceIsFetch)?It(t.request):this.config.request}}},U=class extends O{};var h=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},gr=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,J=(s,t,e)=>!s||t.some(r=>s[r])?e:"",mr=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 Rt(s){return(await Promise.allSettled(s)).map(e=>Is(e)).filter(e=>e!=null)}function Is(s,t=void 0){return s?.status==="fulfilled"?s.value:t}var Rs="https://app.vssps.visualstudio.com/_apis",ys="https://vssps.dev.azure.com/",bs="https://dev.azure.com",P=(s,t={})=>h(t.token||s.token,t.isPAT||s.isPAT),hr=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||Rs;return e=e.replace(/\/$/,""),e},w=(s,t)=>{let e=t.baseUrl||s.baseUrl||bs;return e=e.replace(/\/$/,""),e},bt=(s,t)=>{let e=t.baseUrl||s.baseUrl||ys;return e=e.replace(/\/$/,""),e};var Ps={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},ws={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}),ve=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,vs=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"}},we=(s,t)=>{let e=[],r=[];return t.reviewers.forEach(n=>{let o={reviewer:Pt(n),state:ws[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),r.push(o)}),{id:t.pullRequestId.toString(),title:t.title,description:t.description??null,number:t.codeReviewId,state:Ps[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:ve(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:ve(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:hr(t),assignees:t.reviewers.map(Pt),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:vs(t.mergeStatus),labels:t.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},fr=(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:ve(t.defaultBranch)}:null,permissions:null}),Es=(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()}))??[]}},ee=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=`${yt(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=`${yt(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",E.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:`${bt(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(`${bt(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:fr(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=>fr(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",E.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:ve(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=>we(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(we(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=>we(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(we(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=>Es(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 q=(s,t={})=>h(t.token||s.token,t.isPAT||s.isPAT);var C="https://api.bitbucket.org/2.0",qs={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},Ee=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}),Ir=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},Rr=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}),wt=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:Ee(r.user),state:n}})??[];return{id:t.toString(),title:s.title,description:s.description,number:t,state:qs[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:Ee(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:Ir(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:Ir(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Ss=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},te=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:`${C}/user`,headers:q(this.config,e)});return{data:Ee(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${C}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:q(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:`${C}/repositories/${t.namespace}/${t.name}`,headers:q(this.config,e)});return{data:Rr(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(`${C}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",E.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:q(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(Rr)}}async getBranches(t,e={}){let r=new URL(`${C}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",E.toString());let n=await this.config.request({url:r.toString(),headers:q(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(`${C}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",E.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:q(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(`${C}/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:q(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(`${C}/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:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(wt)}}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${C}/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:q(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{r.push(wt(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(wt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${C}/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:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>Ee(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${C}/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:q(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]:Ss(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:`${C}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:q(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:`${C}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...q(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:`${C}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var qe={};k(qe,{normalizePermissions:()=>vt,restApiPullRequestToCommonPullRequest:()=>Cs});var Cs=s=>me(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 he=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}},me=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:he(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,description:s.description,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:he(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}},yr=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}),re=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:he(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:he(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:yr(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(yr)}}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:vt(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(me(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(me(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(me)}}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=>he(i.user))}}};var Ar=require("js-base64");var Se=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Se||{});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 Ds={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]},br=15,Pr=100,fe={__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"},S=s=>!!s,Q=(s,t)=>{let e=Ds[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},De="https://api.github.com",Ls=`${De}/graphql`,Le=`
1
+ "use strict";var ft=Object.defineProperty;var cs=Object.getOwnPropertyDescriptor;var gs=Object.getOwnPropertyNames;var ms=Object.prototype.hasOwnProperty;var k=(s,t)=>{for(var e in t)ft(s,e,{get:t[e],enumerable:!0})},hs=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of gs(t))!ms.call(s,n)&&n!==e&&ft(s,n,{get:()=>t[n],enumerable:!(r=cs(t,n))||r.enumerable});return s};var fs=s=>hs(ft({},"__esModule",{value:!0}),s);var uo={};k(uo,{AzureDevOps:()=>te,AzureDevopsUtils:()=>Xe,Bitbucket:()=>re,BitbucketServer:()=>se,BitbucketServerUtils:()=>Se,BitbucketUtils:()=>Ye,EntityIdentifierProviderType:()=>D,EntityIdentifierUtils:()=>pt,EntityType:()=>U,EntityVersion:()=>A,GitBuildStatusStage:()=>dr,GitBuildStatusState:()=>me,GitDiffLineType:()=>It,GitHub:()=>oe,GitHubIssueCloseReason:()=>ds,GitHubUtils:()=>ct,GitIssueState:()=>Ce,GitLab:()=>ae,GitLabUtils:()=>gt,GitMergeStrategy:()=>ee,GitProviderUtils:()=>dt,GitPullRequestMergeableState:()=>F,GitPullRequestReviewState:()=>N,GitPullRequestState:()=>Y,GraphQLErrors:()=>h,Jira:()=>ue,JiraServer:()=>le,JiraUtils:()=>mt,Linear:()=>pe,PullRequestAsyncStatus:()=>ps,Trello:()=>de,TrelloUtils:()=>ht,Utils:()=>ao,default:()=>io,isFetch:()=>we});module.exports=fs(uo);var dr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(dr||{}),me=(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))(me||{}),ee=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ee||{}),Y=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(Y||{}),N=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(N||{}),F=(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))(F||{}),It=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(It||{});var cr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},_=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,Z=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var E=100;var gr=globalThis.fetch;var Is=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},Rt=s=>async({url:t,...e})=>{let r=await s(t,e);return Is(r)};var we=(s,t=!1)=>s.name==="fetch"||t;var O=class{constructor(t){let e=t?.request||gr;this.config={...t,request:we(e,t?.forceIsFetch)?Rt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&we(t.request,t?.forceIsFetch??this.config.forceIsFetch)?Rt(t.request):this.config.request}}},$=class extends O{};var I=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},mr=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,V=(s,t,e)=>!s||t.some(r=>s[r])?e:"",hr=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 yt(s){return(await Promise.allSettled(s)).map(e=>Rs(e)).filter(e=>e!=null)}function Rs(s,t=void 0){return s?.status==="fulfilled"?s.value:t}var ys="https://app.vssps.visualstudio.com/_apis",bs="https://vssps.dev.azure.com/",Ps="https://dev.azure.com",P=(s,t={})=>I(t.token||s.token,t.isPAT||s.isPAT),fr=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/"),bt=(s,t)=>{let e=t.baseUrl||s.baseUrl||ys;return e=e.replace(/\/$/,""),e},w=(s,t)=>{let e=t.baseUrl||s.baseUrl||Ps;return e=e.replace(/\/$/,""),e},Pt=(s,t)=>{let e=t.baseUrl||s.baseUrl||bs;return e=e.replace(/\/$/,""),e};var ws={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},vs={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},wt=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,Es=s=>{switch(s){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},ve=(s,t)=>{let e=[],r=[];return t.reviewers.forEach(n=>{let o={reviewer:wt(n),state:vs[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),r.push(o)}),{id:t.pullRequestId.toString(),title:t.title,description:t.description??null,number:t.codeReviewId,state:ws[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:wt(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:fr(t),assignees:t.reviewers.map(wt),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:Es(t.mergeStatus),labels:t.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},Ir=(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}),qs=(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()}))??[]}},te=class extends ${async getCurrentUser(t={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${bt(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=`${bt(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",E.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:`${Pt(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(`${Pt(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:Ir(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=>Ir(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",E.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: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: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=>ve(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(ve(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=>ve(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(ve(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=>qs(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 q=(s,t={})=>I(t.token||s.token,t.isPAT||s.isPAT);var C="https://api.bitbucket.org/2.0",Ss={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},qe=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}),Rr=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},yr=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}),vt=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:qe(r.user),state:n}})??[];return{id:t.toString(),title:s.title,description:s.description,number:t,state:Ss[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:qe(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:Rr(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:Rr(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Cs=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},re=class extends 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:`${C}/user`,headers:q(this.config,e)});return{data:qe(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${C}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:q(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:`${C}/repositories/${t.namespace}/${t.name}`,headers:q(this.config,e)});return{data:yr(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(`${C}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",E.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:q(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(yr)}}async getBranches(t,e={}){let r=new URL(`${C}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",E.toString());let n=await this.config.request({url:r.toString(),headers:q(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(`${C}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",E.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:q(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(`${C}/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:q(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(`${C}/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:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(vt)}}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${C}/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:q(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{r.push(vt(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(vt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${C}/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:q(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>qe(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${C}/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:q(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]:Cs(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:`${C}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:q(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:`${C}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...q(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:`${C}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...q(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var Se={};k(Se,{normalizePermissions:()=>Et,restApiPullRequestToCommonPullRequest:()=>Ds});var Ds=s=>he(s),Et=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 fe=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}},he=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:fe(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,description:s.description,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:fe(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}},br=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}),se=class extends ${getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return I(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:fe(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:fe(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:br(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(br)}}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:Et(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(he(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(he(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getPullRequestsForCurrentUser(t,e={}){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(he)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}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=>fe(i.user))}}};var Ur=require("js-base64");var Ce=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Ce||{});var h=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 Ls={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]},Pr=15,wr=100,Ie={__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"},S=s=>!!s,Q=(s,t)=>{let e=Ls[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Le="https://api.github.com",As=`${Le}/graphql`,Ae=`
2
2
  description
3
3
  dueOn
4
4
  id
@@ -6,7 +6,7 @@ number
6
6
  state
7
7
  title
8
8
  url
9
- `,As=`
9
+ `,Us=`
10
10
  ... on CheckRun {
11
11
  completedAt
12
12
  conclusion
@@ -15,21 +15,21 @@ url
15
15
  permalink
16
16
  startedAt
17
17
  }
18
- `,Ce=/\/api\/v\d+$/,Ae=`
18
+ `,De=/\/api\/v\d+$/,Ue=`
19
19
  color
20
20
  description
21
21
  id
22
22
  name
23
- `,wr=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.")},$s=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),wr(e),Ce.test(e)&&(e=e.replace(Ce,"")),`${e}/api/graphql`):Ls},se=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),wr(e),Ce.test(e)&&(e=e.replace(Ce,"")),`${e}/api/v3`):De},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:$s(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},Us={user:!0,"user:email":!0,"read:user":!0},F=s=>s.some(t=>Us[t]),G=(s=!1,t=!1,e)=>`
23
+ `,vr=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.")},$s=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),vr(e),De.test(e)&&(e=e.replace(De,"")),`${e}/api/graphql`):As},ne=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),vr(e),De.test(e)&&(e=e.replace(De,"")),`${e}/api/v3`):Le},f=(s,t,e)=>{let r=I(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:$s(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},Gs={user:!0,"user:email":!0,"read:user":!0},z=s=>s.some(t=>Gs[t]),G=(s=!1,t=!1,e)=>`
24
24
  __typename
25
- ${J(e,["graphQLId"],"id")}
26
- ${J(e,["id"],"databaseId")}
27
- ${J(e,["name"],"name")}
28
- ${J(e,["name","username"],"login")}
29
- ${t?J(e,["email"],"email"):""}
30
- ${J(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
31
- ${J(e,["url"],"url")}
32
- `,Gs=(s=!1)=>`
25
+ ${V(e,["graphQLId"],"id")}
26
+ ${V(e,["id"],"databaseId")}
27
+ ${V(e,["name"],"name")}
28
+ ${V(e,["name","username"],"login")}
29
+ ${t?V(e,["email"],"email"):""}
30
+ ${V(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
31
+ ${V(e,["url"],"url")}
32
+ `,Ts=(s=!1)=>`
33
33
  latestReviews(first: 100) {
34
34
  nodes {
35
35
  author {
@@ -37,20 +37,20 @@ latestReviews(first: 100) {
37
37
  ${G(!1,s)}
38
38
  }
39
39
  ... on EnterpriseUserAccount {
40
- ${Et(!1)}
40
+ ${qt(!1)}
41
41
  }
42
42
  }
43
43
  state
44
44
  }
45
45
  }
46
- `,vr=(s=!1)=>`
46
+ `,Er=(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
+ `,qt=(s=!1)=>`
54
54
  __typename
55
55
  id
56
56
  login
@@ -68,10 +68,10 @@ author {
68
68
  ${G(!1,t)}
69
69
  }
70
70
  ... on Bot {
71
- ${vr(!1)}
71
+ ${Er(!1)}
72
72
  }
73
73
  ... on EnterpriseUserAccount {
74
- ${Et(!1)}
74
+ ${qt(!1)}
75
75
  }
76
76
  }
77
77
  commits(last: 1) {
@@ -84,7 +84,7 @@ commits(last: 1) {
84
84
  contexts(first: 100) {
85
85
  totalCount
86
86
  nodes {
87
- ${!e||Q(e,"CHECK_RUN")?As:""}
87
+ ${!e||Q(e,"CHECK_RUN")?Us:""}
88
88
  ... on StatusContext {
89
89
  context
90
90
  createdAt
@@ -159,22 +159,22 @@ reviewRequests(first: 100) {
159
159
  }
160
160
  }
161
161
  }
162
- ${!e||Q(e,"LATEST_REVIEWS")?Gs(t):""}
162
+ ${!e||Q(e,"LATEST_REVIEWS")?Ts(t):""}
163
163
  additions
164
164
  deletions
165
165
  changedFiles
166
166
  mergeable
167
167
  mergeStateStatus
168
168
  milestone {
169
- ${Le}
169
+ ${Ae}
170
170
  }
171
171
  labels(first: 100) {
172
172
  nodes {
173
- ${Ae}
173
+ ${Ue}
174
174
  }
175
175
  }
176
176
  ${!e||Q(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
177
- `,Ts=(s=!1,t)=>`
177
+ `,Os=(s=!1,t)=>`
178
178
  id
179
179
  ${!t||Q(t,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
180
180
  title
@@ -183,10 +183,10 @@ author {
183
183
  ${G(!1,s)}
184
184
  }
185
185
  ... on Bot {
186
- ${vr(!1)}
186
+ ${Er(!1)}
187
187
  }
188
188
  ... on EnterpriseUserAccount {
189
- ${Et(!1)}
189
+ ${qt(!1)}
190
190
  }
191
191
  }
192
192
  closedAt
@@ -215,14 +215,14 @@ assignees(first: 100) {
215
215
  }
216
216
  state
217
217
  milestone {
218
- ${Le}
218
+ ${Ae}
219
219
  }
220
220
  labels(first: 100) {
221
221
  nodes {
222
- ${Ae}
222
+ ${Ue}
223
223
  }
224
224
  }
225
- `,Os={"-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"},xs=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),qt=s=>{let t=[];return(s.match(xs)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];Os[n]&&t.push(r)}}),t},St=(s,t,e,r)=>{let n=s==="issue";return{query:`
225
+ `,xs={"-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"},ks=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),St=s=>{let t=[];return(s.match(ks)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];xs[n]&&t.push(r)}}),t},Ct=(s,t,e,r)=>{let n=s==="issue";return{query:`
226
226
  query SearchIssuesOrPullRequests($query: String! $after: String) {
227
227
  search(type:ISSUE query:$query first: ${r.maxPageSize} after:$after) {
228
228
  pageInfo {
@@ -231,18 +231,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
231
231
  }
232
232
  nodes {
233
233
  ... on ${n?"Issue":"PullRequest"} {
234
- ${n?Ts(r.supportsEmail,r.enterpriseVersion??null):$e(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
234
+ ${n?Os(r.supportsEmail,r.enterpriseVersion??null):$e(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
235
235
  }
236
236
  }
237
237
  }
238
- }`,variables:{query:`is:${s} is:open ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},ks="Field 'isDraft' doesn't exist on type 'PullRequest'",Ue=(s=[])=>s.some(t=>t?.message===ks),Ns=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,_s=`
238
+ }`,variables:{query:`is:${s} is:open ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},Ns="Field 'isDraft' doesn't exist on type 'PullRequest'",Ge=(s=[])=>s.some(t=>t?.message===Ns),_s=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Qs=`
239
239
  \
240
- +`,Er=(s,t,e,r)=>{let n=Ns.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(_s,`
240
+ +`,qr=(s,t,e,r)=>{let n=_s.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(Qs,`
241
241
  +`).split(`
242
242
  `).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)}
243
243
  `;break}case"+":{m="ADDED",l+=1,y=`${g.slice(1)}
244
244
  `;break}default:m="UNMODIFIED",l+=1,u+=1,y=`${g}
245
- `}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 H=c[R][y];H===p?g=R:H===d&&(m=R)}c=c.slice(g,m+1)}return c},qr=s=>{let t=s.author;return t||(t=fe),{author:{id:"databaseId"in t?t.databaseId.toString():t.id,graphQLId:t.id,name:("name"in t?t.name:t.login)??t.login,username:t.login,email:("email"in t?t.email:null)??null,avatarUrl:t.avatarUrl,url:t.url},body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId?.toString()??s.id,url:s.url}};var Sr=`mutation DeletePullRequestReviewComment(
245
+ `}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 J=c[R][y];J===p?g=R:J===d&&(m=R)}c=c.slice(g,m+1)}return c},Sr=s=>{let t=s.author;return t||(t=Ie),{author:{id:"databaseId"in t?t.databaseId.toString():t.id,graphQLId:t.id,name:("name"in t?t.name:t.login)??t.login,username:t.login,email:("email"in t?t.email:null)??null,avatarUrl:t.avatarUrl,url:t.url},body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId?.toString()??s.id,url:s.url}};var Cr=`mutation DeletePullRequestReviewComment(
246
246
  $pullRequestReviewCommentId: ID!
247
247
  ) {
248
248
  deletePullRequestReviewComment(input: {
@@ -252,7 +252,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
252
252
  id
253
253
  }
254
254
  }
255
- }`,Cr=`mutation UpdatePullRequestReviewComment(
255
+ }`,Dr=`mutation UpdatePullRequestReviewComment(
256
256
  $pullRequestReviewCommentId: ID!,
257
257
  $body: String!
258
258
  ) {
@@ -265,7 +265,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
265
265
  body
266
266
  }
267
267
  }
268
- }`;var Dr=s=>`
268
+ }`;var Lr=s=>`
269
269
  query GetPullRequestComments(
270
270
  $namespace: String!
271
271
  $name: String!
@@ -311,7 +311,7 @@ query GetPullRequestComments(
311
311
  }
312
312
  }
313
313
  }
314
- `;var Ct=`
314
+ `;var Dt=`
315
315
  id
316
316
  databaseId
317
317
  owner {
@@ -324,18 +324,18 @@ defaultBranchRef {
324
324
  name
325
325
  }
326
326
  viewerPermission
327
- `,Qs={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Bs={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},js={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Fs={OPEN:"OPEN",CLOSED:"CLOSED"},zs=["ADMIN","MAINTAIN","TRIAGE","WRITE"],At=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Ms=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:Ms(s.viewerPermission)}),Ws=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),Lr=s=>({id:s.id.toString(),graphQLId:s.node_id,namespace:s.owner.login,name:s.name,webUrl:s.html_url,httpsUrl:s.clone_url,sshUrl:s.ssh_url,defaultBranch:{name:s.default_branch},permissions:Ws(s.permissions)}),Hs=s=>({path:s.path,isDirectory:s.type==="tree"}),Js={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Vs={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},x=(s,t=Vs)=>{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},Ks=(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]},Xs=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],Lt=s=>{let t=null;s.author?t=s.author:t=fe;let e=(s.reviewRequests?.nodes||[]).filter(S).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:x(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(S).map(i=>{let a=fe;return i.author&&i.author.__typename&&(a=i.author),{reviewer:x(a),state:Qs[i.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,description:s.body,number:s.number,state:Js[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?x(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(S)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(S).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Xs(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:Ks(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(S).map(i=>x(i)):null,reviews:o,reviewDecision:_(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:js[s.mergeStateStatus]??Bs[s.mergeable],milestone:s.milestone?$t(s.milestone):null,labels:s.labels?.nodes?.filter(S).map(At)??[],permissions:{canMerge:zs.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Ys=s=>{let{id:t,comments:e,isOutdated:r,isResolved:n,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:c}=s,p=e.nodes?.[0];if(!p)return null;let{author:d,body:g,databaseId:m,fullDatabaseId:y,id:R,path:L,publishedAt:H,url:lr}=p,ye=o??u,v=i??l,de=a??c;return{author:d?{avatarUrl:d.avatarUrl,email:null,name:d.login}:null,body:g,createdAt:H?new Date(H):null,diffLines:Er(p.diffHunk,ye,v,de),id:y??m.toString(),isOutdated:r,isResolved:n,graphQLId:R,threadId:t,filename:L,replies:e.nodes?.filter(S).slice(1).map(Zs)??[],url:lr,line:ye,startLine:v,side:de}},Zs=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}),en=s=>{let t=null;return s.author?t=s.author:t=fe,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?x(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:Fs[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(S).map(e=>x(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?$t(s.milestone):null,labels:s.labels?.nodes?.filter(S).map(At)??[]}},$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}),ne=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:`${se(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(De)?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=gr(e.fields),o=await this.getScopes(r),i=await I(this.config,{query:`
327
+ `,Bs={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},js={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Fs={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},zs={OPEN:"OPEN",CLOSED:"CLOSED"},Ms=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Ut=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Ws=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Lt=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:Ws(s.viewerPermission)}),Hs=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),Ar=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:Hs(s.permissions)}),Js=s=>({path:s.path,isDirectory:s.type==="tree"}),Vs={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Ks={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},x=(s,t=Ks)=>{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},Xs=(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]},Ys=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],At=s=>{let t=null;s.author?t=s.author:t=Ie;let e=(s.reviewRequests?.nodes||[]).filter(S).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:x(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(S).map(i=>{let a=Ie;return i.author&&i.author.__typename&&(a=i.author),{reviewer:x(a),state:Bs[i.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,description:s.body,number:s.number,state:Vs[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?x(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(S)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(S).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Ys(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:Xs(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(S).map(i=>x(i)):null,reviews:o,reviewDecision:_(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:Fs[s.mergeStateStatus]??js[s.mergeable],milestone:s.milestone?$t(s.milestone):null,labels:s.labels?.nodes?.filter(S).map(Ut)??[],permissions:{canMerge:Ms.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Zs=s=>{let{id:t,comments:e,isOutdated:r,isResolved:n,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:c}=s,p=e.nodes?.[0];if(!p)return null;let{author:d,body:g,databaseId:m,fullDatabaseId:y,id:R,path:L,publishedAt:J,url:pr}=p,be=o??u,v=i??l,ce=a??c;return{author:d?{avatarUrl:d.avatarUrl,email:null,name:d.login}:null,body:g,createdAt:J?new Date(J):null,diffLines:qr(p.diffHunk,be,v,ce),id:y??m.toString(),isOutdated:r,isResolved:n,graphQLId:R,threadId:t,filename:L,replies:e.nodes?.filter(S).slice(1).map(en)??[],url:pr,line:be,startLine:v,side:ce}},en=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}),tn=s=>{let t=null;return s.author?t=s.author:t=Ie,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?x(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:zs[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(S).map(e=>x(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?$t(s.milestone):null,labels:s.labels?.nodes?.filter(S).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}),oe=class extends ${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 f(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[r]=n}return n}async getEnterpriseVersion(e){let r=e.baseUrl||this.config.baseUrl;if(!r)return null;let n=this._enterpriseVersionsCache[r];if(!n){let o=await this.config.request({url:`${ne(this.config,e)}/meta`,headers:I(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(Le)?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=mr(e.fields),o=await this.getScopes(r),i=await f(this.config,{query:`
328
328
  query getCurrentUser {
329
329
  viewer {
330
- ${G(!1,F(o),n)}
330
+ ${G(!1,z(o),n)}
331
331
  }
332
332
  }
333
- `},r),a=i.body.data?.viewer;if(!a)throw new f("Current user not found.",i.body.errors);return{data:x(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:`
333
+ `},r),a=i.body.data?.viewer;if(!a)throw new h("Current user not found.",i.body.errors);return{data:x(a,n)}}async getAccountsForRepo(e,r={}){let n=await this.getScopes(r),{repo:{namespace:o,name:i},cursor:a}=e,u=await f(this.config,{query:`
334
334
  query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
335
335
  repository(owner: $owner, name: $name) {
336
336
  assignableUsers(first: $first, after: $cursor) {
337
337
  nodes {
338
- ${G(!1,F(n))}
338
+ ${G(!1,z(n))}
339
339
  }
340
340
  pageInfo {
341
341
  endCursor
@@ -344,7 +344,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
344
344
  }
345
345
  }
346
346
  }
347
- `,variables:{owner:o,name:i,cursor:a,first:E}},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=>x(l))??[]}}async getUserForCommit(e,r={}){let n=await I(this.config,{query:`
347
+ `,variables:{owner:o,name:i,cursor:a,first:E}},r);if(!u.body.data)throw new h("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=>x(l))??[]}}async getUserForCommit(e,r={}){let n=await f(this.config,{query:`
348
348
  query getUserForCommit(
349
349
  $owner: String!
350
350
  $name: String!
@@ -363,7 +363,7 @@ query getUserForCommit(
363
363
  }
364
364
  }
365
365
  }
366
- `,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:`
366
+ `,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 h("Repository not found.",n.body.errors);let i=o.object?.author;if(!i)throw new h("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 f(this.config,{query:`
367
367
  mutation createCommitOnBranch(
368
368
  $branchName: String!,
369
369
  $expectedHeadOid: GitObjectID!,
@@ -390,23 +390,23 @@ mutation createCommitOnBranch(
390
390
  }
391
391
  }
392
392
  }
393
- `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([c,p])=>({contents:Ar.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:`
393
+ `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([c,p])=>({contents:Ur.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 h("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 f(this.config,{query:`
394
394
  query getAccountForEmail($query: String! $avatarSize: Int) {
395
395
  search(query: $query, type: USER, first: 1) {
396
396
  nodes {
397
397
  ... on User {
398
- ${G(!0,F(n))}
398
+ ${G(!0,z(n))}
399
399
  }
400
400
  }
401
401
  }
402
402
  }
403
- `,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:x({...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:`
403
+ `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},r),i=o.body.data?.search?.nodes?.[0];if(!i)throw new h("Could not find user via email",o.body.errors);return{data:x({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getAccountForUsername(e,r={}){let n=await this.getScopes(r),o=await f(this.config,{query:`
404
404
  query getUserForUsername($login: String! $avatarSize: Int) {
405
405
  user(login: $login) {
406
- ${G(!0,F(n))}
406
+ ${G(!0,z(n))}
407
407
  }
408
408
  }
409
- `,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:x({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await I(this.config,{query:`
409
+ `,variables:{login:e.username,avatarSize:e.avatarSize}},r),i=o.body.data?.user;if(!i)throw new h("Could not find user via username",o.body.errors);return{data:x({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await f(this.config,{query:`
410
410
  query getOrgsForCurrentUser($cursor: String, $first: Int!) {
411
411
  viewer {
412
412
  organizations(first: $first after: $cursor) {
@@ -425,7 +425,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
425
425
  }
426
426
  }
427
427
  }
428
- `,variables:{cursor:e.cursor,first:E}},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:`
428
+ `,variables:{cursor:e.cursor,first:E}},r);if(!n.body.data)throw new h("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 f(this.config,{query:`
429
429
  query getOrgMember($cursor: String, $first: Int!, $login: String!) {
430
430
  viewer {
431
431
  organization(login: $login) {
@@ -441,22 +441,22 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
441
441
  }
442
442
  }
443
443
  }
444
- `,variables:{cursor:e.cursor,first:E,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=>x({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}))}}async getRepo(e,r={}){let n=await I(this.config,{query:`
444
+ `,variables:{cursor:e.cursor,first:E,login:e.org}},r);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new h("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=>x({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}))}}async getRepo(e,r={}){let n=await f(this.config,{query:`
445
445
  query getRepo($owner: String!, $name: String!) {
446
446
  repository(owner: $owner, name: $name) {
447
- ${Ct}
447
+ ${Dt}
448
448
  }
449
449
  }
450
- `,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:Dt(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},c)=>`
450
+ `,variables:{owner:e.namespace,name:e.name}},r);if(!n.body.data?.repository)throw new h(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:Lt(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},c)=>`
451
451
  getRepo_${c}: repository(owner: "${u}", name: "${l}") {
452
- ${Ct}
452
+ ${Dt}
453
453
  }
454
454
  `).join(`
455
- `),o=await I(this.config,{query:`
455
+ `),o=await f(this.config,{query:`
456
456
  query batchGetRepos {
457
457
  ${n}
458
458
  }
459
- `},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(Dt(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:`${se(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,Lr)}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:`${se(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,Lr)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await I(this.config,{query:`
459
+ `},r);if(!o.body.data)throw new h("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(Lt(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:`${ne(this.config,r)}/user/repos?${n.toString()}&page=${i}`,headers:{...I(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,Ar)}async getReposForOrg(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${ne(this.config,r)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...I(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,Ar)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await f(this.config,{query:`
460
460
  query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
461
461
  search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
462
462
  pageInfo {
@@ -465,12 +465,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
465
465
  }
466
466
  nodes {
467
467
  ... on Repository {
468
- ${Ct}
468
+ ${Dt}
469
469
  }
470
470
  }
471
471
  }
472
472
  }
473
- `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:E}},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(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={}){let o=await I(this.config,{query:`
473
+ `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:E}},r);if(!n.body.data)throw new h("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(Lt)}}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 f(this.config,{query:`
474
474
  query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
475
475
  repository(owner: $owner, name: $name) {
476
476
  refs(refPrefix: $refPrefix first: $first after: $cursor) {
@@ -491,7 +491,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
491
491
  }
492
492
  }
493
493
  }
494
- `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:E}},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:`
494
+ `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:E}},n),i=o.body.data?.repository;if(!i)throw new h("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 f(this.config,{query:`
495
495
  query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
496
496
  repository(owner: $owner, name: $name) {
497
497
  object(expression: $ref) {
@@ -530,7 +530,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
530
530
  }
531
531
  }
532
532
  }
533
- `,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:`${se(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 St("pr",p,e.cursor,{maxPageSize:e.maxPageSize??br,supportsEmail:i,supportsDrafts:c,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await I(this.config,a(!0),r);u.body.errors&&Ue(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(S).map(Lt)||[]}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=await I(this.config,St("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??Pr,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(S).map(en)||[]}}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=qt(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(
533
+ `,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 h("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new h("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new h("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:`${ne(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...I(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=z(o),a=c=>{let p=c&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Ct("pr",p,e.cursor,{maxPageSize:e.maxPageSize??Pr,supportsEmail:i,supportsDrafts:c,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await f(this.config,a(!0),r);u.body.errors&&Ge(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await f(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new h("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(S).map(At)||[]}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=z(o),a=await f(this.config,Ct("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??wr,enterpriseVersion:n}),r),{data:u}=a.body;if(!u)throw new h("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(S).map(tn)||[]}}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=St(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=z(o),a=p=>({query:`query getPullRequest(
534
534
  $owner: String!
535
535
  $name: String!
536
536
  $number: Int!
@@ -543,7 +543,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
543
543
  ${$e(p,i,n)}
544
544
  }
545
545
  }
546
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await I(this.config,a(!0),r);u.body.errors&&Ue(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?Lt(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(
546
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await f(this.config,a(!0),r);u.body.errors&&Ge(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await f(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new h("Could not fetch pull request by number",u.body.errors);let c=u.body.data?.repository.pullRequest;return{data:c?At(c):null}}async getPullRequestByGraphQLId(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=z(o),a=p=>({query:`query getPullRequest(
547
547
  $graphQLId: ID!
548
548
  ) {
549
549
  node(id: $graphQLId) {
@@ -551,13 +551,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
551
551
  ${$e(p,i,n)}
552
552
  }
553
553
  }
554
- }`,variables:{graphQLId:e.graphQLId}}),u=await I(this.config,a(!0),r);u.body.errors&&Ue(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?Lt(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!) {
554
+ }`,variables:{graphQLId:e.graphQLId}}),u=await f(this.config,a(!0),r);u.body.errors&&Ge(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await f(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new h("Could not fetch pull request by id",u.body.errors);let c=u.body.data?.node;return{data:c?At(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!) {
555
555
  closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
556
556
  pullRequest {
557
557
  id
558
558
  }
559
559
  }
560
- }`,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(
560
+ }`,i=await f(this.config,{query:`${o}`,variables:{pullRequestGraphQLId:n}},r);if(!i.body.data?.closePullRequest?.pullRequest?.id)throw new h("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(
561
561
  $pullRequestGraphQLId: ID!,
562
562
  $expectedSourceSha: GitObjectID!,
563
563
  $mergeStrategy: PullRequestMergeMethod,
@@ -571,7 +571,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
571
571
  id
572
572
  }
573
573
  }
574
- }`,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 approvePullRequest(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation ApprovePullRequest(
574
+ }`,u=await f(this.config,{query:`${a}`,variables:{pullRequestGraphQLId:n.graphQLId,expectedSourceSha:n.headRef.oid,mergeStrategy:i}},r);if(!u.body.data?.mergePullRequest?.pullRequest?.id)throw new h("Could not merge pull request",u.body.errors)}async approvePullRequest(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation ApprovePullRequest(
575
575
  $pullRequestId: ID!,
576
576
  $body: String
577
577
  ) {
@@ -584,7 +584,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
584
584
  id
585
585
  }
586
586
  }
587
- }`,a=await I(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o||null}},r);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not approve pull request",a.body.errors)}async requestPullRequestChanges(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when requesting changes.");let i=`mutation RequestPullRequestChanges(
587
+ }`,a=await f(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o||null}},r);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new h("Could not approve pull request",a.body.errors)}async requestPullRequestChanges(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when requesting changes.");let i=`mutation RequestPullRequestChanges(
588
588
  $pullRequestId: ID!,
589
589
  $body: String!
590
590
  ) {
@@ -597,7 +597,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
597
597
  id
598
598
  }
599
599
  }
600
- }`,a=await I(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o}},r);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not request pull request changes",a.body.errors)}async commentOnPullRequest(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when commenting on a pull request.");let i=`mutation CommentOnPullRequest(
600
+ }`,a=await f(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o}},r);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new h("Could not request pull request changes",a.body.errors)}async commentOnPullRequest(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when commenting on a pull request.");let i=`mutation CommentOnPullRequest(
601
601
  $pullRequestId: ID!,
602
602
  $body: String!
603
603
  ) {
@@ -610,7 +610,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
610
610
  id
611
611
  }
612
612
  }
613
- }`,a=await I(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o}},r);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not comment on pull request",a.body.errors)}async addCommentToPullRequest(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when adding a comment to a pull request.");let i=`mutation AddCommentToPullRequest(
613
+ }`,a=await f(this.config,{query:i,variables:{pullRequestId:n.graphQLId,body:o}},r);if(!a.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new h("Could not comment on pull request",a.body.errors)}async addCommentToPullRequest(e,r={}){let{pullRequest:n,comment:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o||o.trim()==="")throw new Error("GitHub requires a comment when adding a comment to a pull request.");let i=`mutation AddCommentToPullRequest(
614
614
  $subjectId: ID!,
615
615
  $body: String!
616
616
  ) {
@@ -624,7 +624,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
624
624
  }
625
625
  }
626
626
  }
627
- }`,a=await I(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},r);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new f("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,r={}){let{pullRequest:n,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(l)return this.addReplyToReviewThread({threadId:l,comment:o},r);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:n,comment:o,path:i,line:a,side:u},r)}async deleteInlineComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await I(this.config,{query:Sr,variables:{pullRequestReviewCommentId:n}},r);if(!o.body.data?.deletePullRequestReviewComment)throw new f("Could not delete inline comment",o.body.errors)}async editInlineComment(e,r={}){let{commentId:n,body:o}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing an inline comment.");let i=await I(this.config,{query:Cr,variables:{pullRequestReviewCommentId:n,body:o}},r);if(!i.body.data?.updatePullRequestReviewComment?.pullRequestReviewComment?.id)throw new f("Could not edit inline comment",i.body.errors)}async addReplyToReviewThread(e,r){let{threadId:n,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
627
+ }`,a=await f(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},r);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new h("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,r={}){let{pullRequest:n,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(l)return this.addReplyToReviewThread({threadId:l,comment:o},r);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:n,comment:o,path:i,line:a,side:u},r)}async deleteInlineComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await f(this.config,{query:Cr,variables:{pullRequestReviewCommentId:n}},r);if(!o.body.data?.deletePullRequestReviewComment)throw new h("Could not delete inline comment",o.body.errors)}async editInlineComment(e,r={}){let{commentId:n,body:o}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing an inline comment.");let i=await f(this.config,{query:Dr,variables:{pullRequestReviewCommentId:n,body:o}},r);if(!i.body.data?.updatePullRequestReviewComment?.pullRequestReviewComment?.id)throw new h("Could not edit inline comment",i.body.errors)}async addReplyToReviewThread(e,r){let{threadId:n,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
628
628
  $threadId: ID!,
629
629
  $body: String!
630
630
  ) {
@@ -636,7 +636,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
636
636
  id
637
637
  }
638
638
  }
639
- }`,a=await I(this.config,{query:i,variables:{threadId:n,body:o}},r);if(!a.body.data?.addPullRequestReviewThreadReply?.comment?.id)throw new f("Could not add reply to pull request review thread",a.body.errors);return n}async createReviewThread(e,r){let{pullRequest:n,comment:o,path:i,line:a,side:u}=e,l=`mutation AddInlineCommentToPullRequest(
639
+ }`,a=await f(this.config,{query:i,variables:{threadId:n,body:o}},r);if(!a.body.data?.addPullRequestReviewThreadReply?.comment?.id)throw new h("Could not add reply to pull request review thread",a.body.errors);return n}async createReviewThread(e,r){let{pullRequest:n,comment:o,path:i,line:a,side:u}=e,l=`mutation AddInlineCommentToPullRequest(
640
640
  $pullRequestId: ID!,
641
641
  $body: String!,
642
642
  $path: String!,
@@ -662,43 +662,43 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
662
662
  }
663
663
  }
664
664
  }
665
- }`,c=await I(this.config,{query:l,variables:{pullRequestId:n.graphQLId,body:o,path:i,line:a,side:u}},r);if(!c.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not add inline comment to pull request",c.body.errors);return c.body.data?.addPullRequestReview?.pullRequestReview?.comments?.nodes?.[0]?.id}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) {
665
+ }`,c=await f(this.config,{query:l,variables:{pullRequestId:n.graphQLId,body:o,path:i,line:a,side:u}},r);if(!c.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new h("Could not add inline comment to pull request",c.body.errors);return c.body.data?.addPullRequestReview?.pullRequestReview?.comments?.nodes?.[0]?.id}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) {
666
666
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
667
667
  pullRequest {
668
668
  id
669
669
  }
670
670
  }
671
- }`,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!) {
671
+ }`,a=await f(this.config,{query:`${i}`,variables:{pullRequestGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},r);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new h("Could not set milestone of pull request",a.body.errors)}async markPullRequestReadyForReview(e,r){let n=`mutation MarkReadyToReview($pullRequestGraphQLId: ID!) {
672
672
  markPullRequestReadyForReview(input: { pullRequestId: $pullRequestGraphQLId }) {
673
673
  pullRequest {
674
674
  id
675
675
  }
676
676
  }
677
- }`,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!) {
677
+ }`,o=await f(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!o.body.data?.markPullRequestReadyForReview?.pullRequest?.id)throw new h("Could not mark pull request ready to review",o.body.errors)}async convertPullRequestToDraft(e,r){let n=`mutation ConvertToDraft($pullRequestGraphQLId: ID!) {
678
678
  convertPullRequestToDraft(input: { pullRequestId: $pullRequestGraphQLId }) {
679
679
  pullRequest {
680
680
  id
681
681
  }
682
682
  }
683
- }`,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!]!) {
683
+ }`,o=await f(this.config,{query:n,variables:{pullRequestGraphQLId:e}},r);if(!o.body.data?.convertPullRequestToDraft?.pullRequest?.id)throw new h("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!]!) {
684
684
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds }) {
685
685
  pullRequest {
686
686
  id
687
687
  }
688
688
  }
689
- }`,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!]!) {
689
+ }`,c=await f(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},r);if(!c.body.data?.requestReviews?.pullRequest?.id)throw new h("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!]!) {
690
690
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
691
691
  pullRequest {
692
692
  id
693
693
  }
694
694
  }
695
- }`,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!]!) {
695
+ }`,l=await f(this.config,{query:u,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:a}},r);if(!l.body.data?.requestReviews?.pullRequest?.id)throw new h("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!]!) {
696
696
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
697
697
  pullRequest {
698
698
  id
699
699
  }
700
700
  }
701
- }`,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(
701
+ }`,u=await f(this.config,{query:a,variables:{pullRequestGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},r);if(!u.body.data?.updatePullRequest?.pullRequest?.id)throw new h("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(
702
702
  $namespace: String!
703
703
  $name: String!
704
704
  $pullRequestId: Int!
@@ -754,54 +754,54 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
754
754
  }
755
755
  }
756
756
  }
757
- }`,l=await I(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),c=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(S).reduce((d,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return d;let m=g.comments.nodes[0].pullRequestReview,y=Ys(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(S).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 getCommentsForPullRequest(e,r={}){let n=await this.getEnterpriseVersion(r),o=!n||Q(n,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,c=await I(this.config,{query:Dr(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:E}},r),p=c.body.data?.repository;if(!p)throw new f("Could not fetch pull request comments",c.body.errors);return{data:p.pullRequest.comments.nodes?.filter(S).map(qr)??[],pageInfo:p.pullRequest.comments.pageInfo}}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!]) {
757
+ }`,l=await f(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),c=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(S).reduce((d,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return d;let m=g.comments.nodes[0].pullRequestReview,y=Zs(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(S).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 getCommentsForPullRequest(e,r={}){let n=await this.getEnterpriseVersion(r),o=!n||Q(n,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,c=await f(this.config,{query:Lr(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:E}},r),p=c.body.data?.repository;if(!p)throw new h("Could not fetch pull request comments",c.body.errors);return{data:p.pullRequest.comments.nodes?.filter(S).map(Sr)??[],pageInfo:p.pullRequest.comments.pageInfo}}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!]) {
758
758
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
759
759
  pullRequest {
760
760
  id
761
761
  }
762
762
  }
763
- }`,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=qt(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!) {
763
+ }`,a=await f(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 h("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=St(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!) {
764
764
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
765
765
  issue {
766
766
  id
767
767
  }
768
768
  }
769
- }`,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!) {
769
+ }`,a=await f(this.config,{query:i,variables:{issueGraphQLId:n.graphQLId,reason:o}},r);if(!a.body.data?.closeIssue?.issue?.id)throw new h("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!) {
770
770
  updateIssue(input: { id: $issueGraphQLId, state: CLOSED }) {
771
771
  issue {
772
772
  id
773
773
  }
774
774
  }
775
- }`,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!) {
775
+ }`,i=await f(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!i.body.data?.updateIssue?.issue?.id)throw new h("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!) {
776
776
  reopenIssue(input: { issueId: $issueGraphQLId }) {
777
777
  issue {
778
778
  id
779
779
  }
780
780
  }
781
- }`,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!]) {
781
+ }`,i=await f(this.config,{query:o,variables:{issueGraphQLId:n.graphQLId}},r);if(!i.body.data?.reopenIssue?.issue?.id)throw new h("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!]) {
782
782
  updateIssue(input: { id: $issueGraphQLId, labelIds: $labelGraphQLIds }) {
783
783
  issue {
784
784
  id
785
785
  }
786
786
  }
787
- }`,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) {
787
+ }`,u=await f(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,labelGraphQLIds:i}},r);if(!u.body.data?.updateIssue?.issue?.id)throw new h("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) {
788
788
  updateIssue(input: { id: $issueGraphQLId, milestoneId: $milestoneGraphQLId }) {
789
789
  issue {
790
790
  id
791
791
  }
792
792
  }
793
- }`,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!]!) {
793
+ }`,a=await f(this.config,{query:`${i}`,variables:{issueGraphQLId:n.graphQLId,milestoneGraphQLId:o?.graphQLId??null}},r);if(!a.body.data?.updateIssue?.issue?.id)throw new h("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!]!) {
794
794
  updateIssue(input: { id: $issueGraphQLId, assigneeIds: $assigneeGraphQLIds }) {
795
795
  issue {
796
796
  id
797
797
  }
798
798
  }
799
- }`,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:`
799
+ }`,u=await f(this.config,{query:a,variables:{issueGraphQLId:n.graphQLId,assigneeGraphQLIds:i}},r);if(!u.body.data?.updateIssue?.issue?.id)throw new h("Could not set issue assignees",u.body.errors)}async getMilestonesForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await f(this.config,{query:`
800
800
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
801
801
  repository(owner: $owner, name: $name) {
802
802
  milestones(first: $first, after: $cursor) {
803
803
  nodes {
804
- ${Le}
804
+ ${Ae}
805
805
  }
806
806
  pageInfo {
807
807
  endCursor
@@ -810,12 +810,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
810
810
  }
811
811
  }
812
812
  }
813
- `,variables:{owner:n,name:o,cursor:i,first:E}},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($t)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await I(this.config,{query:`
813
+ `,variables:{owner:n,name:o,cursor:i,first:E}},r);if(!a.body.data)throw new h("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($t)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await f(this.config,{query:`
814
814
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
815
815
  repository(owner: $owner, name: $name) {
816
816
  labels(first: $first, after: $cursor) {
817
817
  nodes {
818
- ${Ae}
818
+ ${Ue}
819
819
  }
820
820
  pageInfo {
821
821
  endCursor
@@ -824,7 +824,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
824
824
  }
825
825
  }
826
826
  }
827
- `,variables:{owner:n,name:o,cursor:i,first:E}},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(At)??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${se(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(Hs)}}};var tn="https://gitlab.com/api/v4",rn="https://gitlab.com/api/graphql",Ut=/\/api\/v\d+$/,$r=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.")},Ge=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),$r(e),Ut.test(e)||(e=e+"/api/v4"),e):tn},sn=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),$r(e),Ut.test(e)&&(e=e.replace(Ut,"")),`${e}/api/graphql`):rn},b=(s,t,e)=>{let r=h(e.token||s.token);return s.request({url:sn(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},Te=s=>s?.map(t=>`"${t.message}"`).join(", ");var kt=s=>s.split("/").slice(0,-1).join("/"),Nt=s=>s.split("/").at(-1)??"",Oe=s=>({id:s.id.replace(oe,""),graphQLId:s.id,namespace:kt(s.fullPath),name:Nt(s.fullPath),webUrl:s.webUrl}),Ur=s=>({id:s.id.replace(oe,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:kt(s.fullPath),name:Nt(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),nn={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},on={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var an="gid://gitlab/User/",oe="gid://gitlab/Project/",un="gid://gitlab/MergeRequest/",ln="gid://gitlab/Issue/",pn="gid://gitlab/ProjectLabel/",dn="gid://gitlab/Milestone/",cn="gid://gitlab/Ci::Build/",_t=`
827
+ `,variables:{owner:n,name:o,cursor:i,first:E}},r);if(!a.body.data)throw new h("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(Ut)??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${ne(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...I(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(Js)}}};var rn="https://gitlab.com/api/v4",sn="https://gitlab.com/api/graphql",Gt=/\/api\/v\d+$/,$r=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(/\/$/,""),$r(e),Gt.test(e)||(e=e+"/api/v4"),e):rn},nn=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),$r(e),Gt.test(e)&&(e=e.replace(Gt,"")),`${e}/api/graphql`):sn},b=(s,t,e)=>{let r=I(e.token||s.token);return s.request({url:nn(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},Oe=s=>s?.map(t=>`"${t.message}"`).join(", ");var Nt=s=>s.split("/").slice(0,-1).join("/"),_t=s=>s.split("/").at(-1)??"",xe=s=>({id:s.id.replace(ie,""),graphQLId:s.id,namespace:Nt(s.fullPath),name:_t(s.fullPath),webUrl:s.webUrl}),Gr=s=>({id:s.id.replace(ie,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:Nt(s.fullPath),name:_t(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),on={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},an={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var un="gid://gitlab/User/",ie="gid://gitlab/Project/",ln="gid://gitlab/MergeRequest/",pn="gid://gitlab/Issue/",dn="gid://gitlab/ProjectLabel/",cn="gid://gitlab/Milestone/",gn="gid://gitlab/Ci::Build/",Qt=`
828
828
  description
829
829
  dueDate
830
830
  id
@@ -833,7 +833,7 @@ startDate
833
833
  state
834
834
  title
835
835
  webPath
836
- `,Gt=`
836
+ `,Tt=`
837
837
  id
838
838
  fullPath
839
839
  webUrl
@@ -847,25 +847,25 @@ userPermissions {
847
847
  downloadCode
848
848
  pushCode
849
849
  }
850
- `,z=`
850
+ `,M=`
851
851
  id
852
852
  name
853
853
  username
854
854
  publicEmail
855
855
  avatarUrl
856
856
  webUrl
857
- `,Qt=`
857
+ `,Bt=`
858
858
  color
859
859
  description
860
860
  id
861
861
  title
862
- `,Tt=`
862
+ `,Ot=`
863
863
  author {
864
- ${z}
864
+ ${M}
865
865
  }
866
866
  assignees {
867
867
  nodes {
868
- ${z}
868
+ ${M}
869
869
  }
870
870
  }
871
871
  closedAt
@@ -876,7 +876,7 @@ id
876
876
  iid
877
877
  labels {
878
878
  nodes {
879
- ${Qt}
879
+ ${Bt}
880
880
  }
881
881
  }
882
882
  state
@@ -887,9 +887,9 @@ upvotes
887
887
  userNotesCount
888
888
  webUrl
889
889
  milestone {
890
- ${_t}
890
+ ${Qt}
891
891
  }
892
- `,gn=`
892
+ `,mn=`
893
893
  stages {
894
894
  nodes {
895
895
  jobs {
@@ -905,11 +905,11 @@ stages {
905
905
  name
906
906
  }
907
907
  }
908
- `,Gr=(s,t,e)=>`
908
+ `,Tr=(s,t,e)=>`
909
909
  id
910
910
  state
911
911
  author {
912
- ${z}
912
+ ${M}
913
913
  }
914
914
  diffRefs {
915
915
  baseSha
@@ -935,12 +935,12 @@ targetBranch
935
935
  sourceBranch
936
936
  assignees {
937
937
  nodes {
938
- ${z}
938
+ ${M}
939
939
  }
940
940
  }
941
941
  reviewers {
942
942
  nodes {
943
- ${z}
943
+ ${M}
944
944
  mergeRequestInteraction {
945
945
  approved
946
946
  reviewState
@@ -950,19 +950,19 @@ reviewers {
950
950
  mergeStatusEnum
951
951
  labels {
952
952
  nodes {
953
- ${Qt}
953
+ ${Bt}
954
954
  }
955
955
  }
956
956
  ${s?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
957
- ${t?`milestone { ${_t} }`:""}
958
- ${e?`headPipeline { ${gn} }`:""}
959
- `,V=s=>`${s.namespace}/${s.name}`,mn=s=>`${s.namespace}/${s.name}`,hn=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),Ot=s=>({id:s.id.replace(oe,""),graphQLId:s.id,namespace:kt(s.fullPath),name:Nt(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:hn(s.userPermissions)}),fn=s=>({path:s.path,isDirectory:s.type==="tree"}),In={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Or=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,M=(s,t,e)=>{let r=Or(s.avatarUrl,t,e);return{id:s.id.replace(an,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},Bt=s=>({color:s.color,description:s.description,id:s.id.replace(pn,""),graphQLId:s.id,name:s.title}),Rn=(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,yn=(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"}},Tr=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>yn(i,r,n)):null;return{id:s.id.replace(un,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:In[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:Rn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(cn,"")}`}))??[])??[]},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:on[s.mergeStatusEnum],milestone:s.milestone?jt(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(Bt)??[],permissions:null}},xt=(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(ln,""),labels:s.labels?.nodes?.map(Bt)??[],number:s.iid,repository:{id:t.id.replace(oe,""),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?jt(s.milestone,t.webUrl):null}),jt=(s,t)=>({id:s.id.replace(dn,""),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}),ie=class extends U{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){let n=(await b(this.config,{query:`
957
+ ${t?`milestone { ${Qt} }`:""}
958
+ ${e?`headPipeline { ${mn} }`:""}
959
+ `,K=s=>`${s.namespace}/${s.name}`,hn=s=>`${s.namespace}/${s.name}`,fn=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),xt=s=>({id:s.id.replace(ie,""),graphQLId:s.id,namespace:Nt(s.fullPath),name:_t(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:fn(s.userPermissions)}),In=s=>({path:s.path,isDirectory:s.type==="tree"}),Rn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},xr=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,W=(s,t,e)=>{let r=xr(s.avatarUrl,t,e);return{id:s.id.replace(un,""),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(dn,""),graphQLId:s.id,name:s.title}),yn=(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,bn=(s,t,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:W(s,t,e),state:s.mergeRequestInteraction?.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},Or=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>bn(i,r,n)):null;return{id:s.id.replace(ln,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:Rn[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?W(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:yn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(gn,"")}`}))??[])??[]},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=>W(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:an[s.mergeStatusEnum],milestone:s.milestone?Ft(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(jt)??[],permissions:null}},kt=(s,t,e,r)=>({author:W(s.author,e,r),assignees:s.assignees.nodes.map(n=>W(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(pn,""),labels:s.labels?.nodes?.map(jt)??[],number:s.iid,repository:{id:t.id.replace(ie,""),graphQLId:t.id,name:t.name,owner:{login:t.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?Ft(s.milestone,t.webUrl):null}),Ft=(s,t)=>({id:s.id.replace(cn,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${t}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),ae=class extends ${getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){let n=(await b(this.config,{query:`
960
960
  query getCurrentUser {
961
961
  currentUser {
962
- ${z}
962
+ ${M}
963
963
  }
964
964
  }
965
- `},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=V(t.repo),o=(await b(this.config,{query:`
965
+ `},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:W(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(t,e={}){let r=K(t.repo),o=(await b(this.config,{query:`
966
966
  query getUserForCommit($fullPath: ID!, $oid: String!) {
967
967
  project(fullPath: $fullPath) {
968
968
  repository {
@@ -978,21 +978,21 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
978
978
  }
979
979
  }
980
980
  }
981
- `,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Or(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:`
981
+ `,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=xr(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:`
982
982
  query getAccountForEmail($email: String!) {
983
983
  users(search: $email) {
984
984
  nodes {
985
- ${z}
985
+ ${M}
986
986
  }
987
987
  }
988
988
  }
989
- `,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:`
989
+ `,variables:{email:t.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:W(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(t,e={}){let n=(await b(this.config,{query:`
990
990
  query getAccountForUsername($username: String!) {
991
991
  user(username: $username) {
992
- ${z}
992
+ ${M}
993
993
  }
994
994
  }
995
- `,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:`
995
+ `,variables:{username:t.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:W(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:`
996
996
  query getAccountsForRepo(
997
997
  $fullPath: ID!
998
998
  $after: String
@@ -1003,7 +1003,7 @@ query getAccountsForRepo(
1003
1003
  projectMembers(after: $after) {
1004
1004
  nodes {
1005
1005
  user {
1006
- ${z}
1006
+ ${M}
1007
1007
  }
1008
1008
  }
1009
1009
  pageInfo {
@@ -1013,22 +1013,22 @@ query getAccountsForRepo(
1013
1013
  }
1014
1014
  }
1015
1015
  }
1016
- `,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=V(t),n=await b(this.config,{query:`
1016
+ `,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=>W(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(t,e={}){let r=K(t),n=await b(this.config,{query:`
1017
1017
  query getRepo($fullPath: ID!) {
1018
1018
  project(fullPath: $fullPath) {
1019
- ${Gt}
1019
+ ${Tt}
1020
1020
  }
1021
1021
  }
1022
- `,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:Ot(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(V).map((u,l)=>`
1022
+ `,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:xt(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(K).map((u,l)=>`
1023
1023
  getRepo_${l}: project(fullPath: "${u}") {
1024
- ${Gt}
1024
+ ${Tt}
1025
1025
  }
1026
1026
  `).join(`
1027
1027
  `),o=await b(this.config,{query:`
1028
1028
  query batchGetRepos {
1029
1029
  ${n}
1030
1030
  }
1031
- `},e);if(!o.body.data)throw new Error(Te(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(Ot(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:`
1031
+ `},e);if(!o.body.data)throw new Error(Oe(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(xt(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:`
1032
1032
  query getReposForCurrentUser($after: String) {
1033
1033
  projects(membership: true first: 100 after: $after) {
1034
1034
  pageInfo {
@@ -1036,11 +1036,11 @@ query getReposForCurrentUser($after: String) {
1036
1036
  hasNextPage
1037
1037
  }
1038
1038
  nodes {
1039
- ${Gt}
1039
+ ${Tt}
1040
1040
  }
1041
1041
  }
1042
1042
  }
1043
- `,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(Te(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(Ot)}}async getRefs(t,e,r={}){let n=V(e.repo),o=new URL(`${Ge(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",E.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=V(t.repo),n=new URL(`${Ge(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=nn[t.association],o=await b(this.config,{query:`
1043
+ `,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(Oe(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(xt)}}async getRefs(t,e,r={}){let n=K(e.repo),o=new URL(`${Te(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",E.toString());let i=await this.config.request({url:o.toString(),headers:I(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=K(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 o=await this.config.request({url:n.toString(),headers:I(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=on[t.association],o=await b(this.config,{query:`
1044
1044
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
1045
1045
  user(username: $username) {
1046
1046
  ${n}(state:opened first:100 after:$cursor labels: $labelNames${r?` ${r}`:""}) {
@@ -1049,12 +1049,12 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
1049
1049
  hasNextPage
1050
1050
  }
1051
1051
  nodes {
1052
- ${Gr(!0,!0,!0)}
1052
+ ${Tr(!0,!0,!0)}
1053
1053
  }
1054
1054
  }
1055
1055
  }
1056
1056
  }
1057
- `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!o.body.data)throw new Error(Te(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=>Tr(a,Ur(a.project),Ur(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 v=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,...v&&{repo:v}},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,...v&&{repo:v}},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,...v&&{repo:v}},e)),d++}while(d<(t.repos?.length||0));let g=[l,c,p].flat(),m=await Promise.all(g),y={},R=[],L=v=>{y[v.id]||(y[v.id]=!0,R.push(v))},H=!1,ye=m.map((v,de)=>{let ce="";return v&&v.data.forEach(L),v?.pageInfo.hasNextPage?(H=!0,ce+=`${v.pageInfo.endCursor||"null"}`):ce+="null",t.repos?.length&&(de+1)%t.repos.length!==0?ce+="-":de+1<m.length&&(ce+=";"),ce}).join("");return{pageInfo:{hasNextPage:H,endCursor:ye},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=V(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),c={fullPath:i,...a},p=await b(this.config,{query:`
1057
+ `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!o.body.data)throw new Error(Oe(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=>Or(a,Gr(a.project),Gr(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 v=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,...v&&{repo:v}},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,...v&&{repo:v}},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,...v&&{repo:v}},e)),d++}while(d<(t.repos?.length||0));let g=[l,c,p].flat(),m=await Promise.all(g),y={},R=[],L=v=>{y[v.id]||(y[v.id]=!0,R.push(v))},J=!1,be=m.map((v,ce)=>{let ge="";return v&&v.data.forEach(L),v?.pageInfo.hasNextPage?(J=!0,ge+=`${v.pageInfo.endCursor||"null"}`):ge+="null",t.repos?.length&&(ce+1)%t.repos.length!==0?ge+="-":ce+1<m.length&&(ge+=";"),ge}).join("");return{pageInfo:{hasNextPage:J,endCursor:be},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=K(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),c={fullPath:i,...a},p=await b(this.config,{query:`
1058
1058
  query getPullRequestsForRepo(
1059
1059
  $fullPath: ID!
1060
1060
  $after: String
@@ -1079,12 +1079,12 @@ query getPullRequestsForRepo(
1079
1079
  hasNextPage
1080
1080
  }
1081
1081
  nodes {
1082
- ${Gr(!1,!0,!0)}
1082
+ ${Tr(!1,!0,!0)}
1083
1083
  }
1084
1084
  }
1085
1085
  }
1086
1086
  }
1087
- `,variables:{...c,after:n}},e),d=[],g=p.body.data?.project;if(!r&&g?.archived)return{pageInfo:null,data:[]};let m=Oe(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(R=>{d.push(Tr(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!) {
1087
+ `,variables:{...c,after:n}},e),d=[],g=p.body.data?.project;if(!r&&g?.archived)return{pageInfo:null,data:[]};let m=xe(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(R=>{d.push(Or(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!) {
1088
1088
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
1089
1089
  errors,
1090
1090
  mergeRequest {
@@ -1149,18 +1149,18 @@ query getPullRequestsForRepo(
1149
1149
  id
1150
1150
  }
1151
1151
  }
1152
- }`;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=mn(t),n=await b(this.config,{query:`
1152
+ }`;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=hn(t),n=await b(this.config,{query:`
1153
1153
  query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1154
1154
  project(fullPath: $projectId) {
1155
1155
  id
1156
1156
  fullPath
1157
1157
  webUrl
1158
1158
  issue(iid: $issueNumber) {
1159
- ${Tt}
1159
+ ${Ot}
1160
1160
  }
1161
1161
  }
1162
1162
  }
1163
- `,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:xt(n.body.data.project.issue,Oe(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=V(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:o,...i},c=`
1163
+ `,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:kt(n.body.data.project.issue,xe(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=K(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:o,...i},c=`
1164
1164
  query GetIssuesFromProject(
1165
1165
  $fullPath: ID!
1166
1166
  $after: String
@@ -1180,7 +1180,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1180
1180
  ${u.length?u.join(" "):""}
1181
1181
  ) {
1182
1182
  nodes {
1183
- ${Tt}
1183
+ ${Ot}
1184
1184
  }
1185
1185
  pageInfo {
1186
1186
  endCursor
@@ -1188,7 +1188,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1188
1188
  }
1189
1189
  }
1190
1190
  }
1191
- }`,p=await b(this.config,{query:c,variables:{...l,after:r}},e),d=[],g=p.body.data?.project,m=Oe(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(R=>{d.push(xt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:d.sort((R,L)=>(R.updatedDate||R.createdDate).getTime()-(L.updatedDate||L.createdDate).getTime())}}async getIssuesForRepos(t,e={}){let{cursor:r}=t||{},n=t.repoIds.map(g=>g.toString().startsWith(oe)?g:`${oe}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(t),u={projectIds:n,...o},l=`
1191
+ }`,p=await b(this.config,{query:c,variables:{...l,after:r}},e),d=[],g=p.body.data?.project,m=xe(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(R=>{d.push(kt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:d.sort((R,L)=>(R.updatedDate||R.createdDate).getTime()-(L.updatedDate||L.createdDate).getTime())}}async getIssuesForRepos(t,e={}){let{cursor:r}=t||{},n=t.repoIds.map(g=>g.toString().startsWith(ie)?g:`${ie}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(t),u={projectIds:n,...o},l=`
1192
1192
  query GetIssuesFromProject(
1193
1193
  $projectIds: [ID!]
1194
1194
  $after: String
@@ -1214,12 +1214,12 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1214
1214
  ${a.length?a.join(" "):""}
1215
1215
  ) {
1216
1216
  nodes {
1217
- ${Tt}
1217
+ ${Ot}
1218
1218
  }
1219
1219
  }
1220
1220
  }
1221
1221
  }
1222
- }`,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=Oe(g);(g.issues?.nodes||[]).forEach(R=>p.push(xt(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!) {
1222
+ }`,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=xe(g);(g.issues?.nodes||[]).forEach(R=>p.push(kt(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!) {
1223
1223
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1224
1224
  issue {
1225
1225
  id
@@ -1259,7 +1259,7 @@ query getLabelsForRepo(
1259
1259
  webUrl
1260
1260
  milestones(after: $after) {
1261
1261
  nodes {
1262
- ${_t}
1262
+ ${Qt}
1263
1263
  }
1264
1264
  pageInfo {
1265
1265
  endCursor
@@ -1268,7 +1268,7 @@ query getLabelsForRepo(
1268
1268
  }
1269
1269
  }
1270
1270
  }
1271
- `,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=>jt(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:`
1271
+ `,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=>Ft(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:`
1272
1272
  query getLabelsForRepo(
1273
1273
  $fullPath: ID!
1274
1274
  $after: String
@@ -1278,7 +1278,7 @@ query getLabelsForRepo(
1278
1278
  ) {
1279
1279
  labels(after: $after) {
1280
1280
  nodes {
1281
- ${Qt}
1281
+ ${Bt}
1282
1282
  }
1283
1283
  pageInfo {
1284
1284
  endCursor
@@ -1287,8 +1287,8 @@ query getLabelsForRepo(
1287
1287
  }
1288
1288
  }
1289
1289
  }
1290
- `,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(Bt)??[]}}async getTreeForRepo(t,e={}){let r=V(t.repo),n=new URL(t.cursor??`${Ge(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(fn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var bn="https://api.atlassian.com/ex/jira",xe=100,Ft=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],xr="/rest/api/2/search/jql",kr="/rest/api/2/search",zt=(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:ke(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[ke(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:En(s.fields.status),statusTransitions:s.transitions?.map(Pn)??[],components:s.fields.components?.map(wn)??[],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(qn),fixVersions:s.fields.fixVersions.map(Sn)}},Pn=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}}},wn=s=>({description:s.description??null,id:s.id,name:s.name}),vn=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,ke=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:vn(s,t,e)}),En=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}},qn=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}),Sn=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),K=(s,t,e)=>e?`${t.baseUrl||bn}/${e}`:`${t?.baseUrl||s.baseUrl}`,Ne=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${K(s,e,r)}/rest/api/2/field`,headers:h(e.token||s.token)})).body},_e=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${K(s,r,o)}/rest/api/2/issue/${n}?fields=${Ft.join(",")}&expand=transitions`,headers:h(r.token||s.token)});return{data:zt(a.body,i,e,o)}},Qe=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1291
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(L=>u.push(`labels = "${L}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,c=!o,p=c?kr:xr,d=new URL(`${K(s,r,o)}${p}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",xe.toString()),d.searchParams.set("fields",Ft.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(L=>zt(L,a,e,o)),y=!1,R="";return c?(y=m.length==xe,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},Nr=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=[...Ft],l=a?.Sprint;l&&u.push(l);let c=!o,p=c?kr:xr,d=new URL(`${K(s,r,o)}${p}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",xe.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(L=>zt(L,a,e,o)),y=!1,R="";return c?(y=m.length==xe,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},Be=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}"`)),Nr(s,{resourceId:c,jql:d,cursor:u,fields:p},e,r)},je=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}"`)),Nr(s,{resourceId:c,jql:g,fields:p,cursor:u},e,r)},Fe=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:`${K(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"}})},ze=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:`${K(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"}})},Me=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:`${K(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"}})},We=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${K(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 Ie="https://api.atlassian.com/ex/jira",Mt=100,ae=class extends O{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Ne(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||Ie}/${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||Ie}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Mt.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 mr(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||Ie}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Mt.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=>ke(c,a,!1))}}async getComponentsForJiraProject(e,r={}){return await We(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 _e(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 Be(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 je(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 Qe(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await Me(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||Ie}/${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 ze(this.config,e,r)}async setIssueLabels(e,r={}){await Fe(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||Ie}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Mt.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 ue=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 Ne(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 _e(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 Be(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 je(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 Qe(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await Me(this.config,e,r)}async setIssueLabels(e,r={}){await Fe(this.config,e,r)}async setIssueComponents(e,r={}){await ze(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 We(this.config,e,r)}};var Ht=100,He=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},Wt=s=>s?s instanceof Date?s:new Date(s):null,Cn=`
1290
+ `,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(jt)??[]}}async getTreeForRepo(t,e={}){let r=K(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 o=await this.config.request({url:n.toString(),headers:I(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(In),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var Pn="https://api.atlassian.com/ex/jira",ke=100,zt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],kr="/rest/api/2/search/jql",Nr="/rest/api/2/search",Mt=(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:Ne(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[Ne(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:qn(s.fields.status),statusTransitions:s.transitions?.map(wn)??[],components:s.fields.components?.map(vn)??[],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(Sn),fixVersions:s.fields.fixVersions.map(Cn)}},wn=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}}},vn=s=>({description:s.description??null,id:s.id,name:s.name}),En=(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:En(s,t,e)}),qn=s=>{let t;switch(s.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:t}},Sn=s=>({id:s.id.toString(),name:s.name,isActive:s.state==="active",startDate:s.startDate?new Date(s.startDate):null,endDate:s.endDate?new Date(s.endDate):null,completedDate:s.completeDate?new Date(s.completeDate):null}),Cn=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),X=(s,t,e)=>e?`${t.baseUrl||Pn}/${e}`:`${t?.baseUrl||s.baseUrl}`,_e=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${X(s,e,r)}/rest/api/2/field`,headers:I(e.token||s.token)})).body},Qe=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${X(s,r,o)}/rest/api/2/issue/${n}?fields=${zt.join(",")}&expand=transitions`,headers:I(r.token||s.token)});return{data:Mt(a.body,i,e,o)}},Be=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1291
+ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(L=>u.push(`labels = "${L}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,c=!o,p=c?Nr:kr,d=new URL(`${X(s,r,o)}${p}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",ke.toString()),d.searchParams.set("fields",zt.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:I(r.token||s.token)}),m=g.body.issues.map(L=>Mt(L,a,e,o)),y=!1,R="";return c?(y=m.length==ke,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=[...zt],l=a?.Sprint;l&&u.push(l);let c=!o,p=c?Nr:kr,d=new URL(`${X(s,r,o)}${p}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",ke.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:I(r.token||s.token)}),m=g.body.issues.map(L=>Mt(L,a,e,o)),y=!1,R="";return c?(y=m.length==ke,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},je=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)},Fe=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)},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 o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${X(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...I(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 o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${X(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...I(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 o={transition:{id:n.id}};await s.request({method:"POST",url:`${X(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...I(e.token||s.token),"Content-Type":"application/json"}})},He=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${X(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:I(e.token||s.token)})).body}};var Re="https://api.atlassian.com/ex/jira",Wt=100,ue=class extends O{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await _e(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){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||Re}/${e.resourceId}/rest/api/2/myself`,headers:I(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:I(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||Re}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Wt.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:I(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 hr(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||Re}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Wt.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:I(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=>Ne(c,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),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Qe(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 je(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 Fe(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 Be(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await We(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||Re}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...I(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:o}=e,i=new URL(`${r.baseUrl||Re}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Wt.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:I(r.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var le=class extends ${constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await _e(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:I(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:I(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 Qe(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 je(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 Fe(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 Be(this.config,{...e,fields:o},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?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:I(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 Jt=100,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}},H=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},Ht=s=>s?s instanceof Date?s:new Date(s):null,Dn=`
1292
1292
  id
1293
1293
  name
1294
1294
  description
@@ -1296,11 +1296,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1296
1296
  startDate
1297
1297
  targetDate
1298
1298
  url
1299
- `,_r=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:Wt(s.startDate),targetDate:Wt(s.targetDate),url:s.url}),Qr=async(s,t,e)=>{let r=`
1299
+ `,Qr=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:Ht(s.startDate),targetDate:Ht(s.targetDate),url:s.url}),Br=async(s,t,e)=>{let r=`
1300
1300
  query GetProjects($first: Int!, $after: String) {
1301
1301
  projects(first: $first, after: $after) {
1302
1302
  nodes {
1303
- ${Cn}
1303
+ ${Dn}
1304
1304
  }
1305
1305
  pageInfo {
1306
1306
  hasNextPage
@@ -1308,7 +1308,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1308
1308
  }
1309
1309
  }
1310
1310
  }
1311
- `;return(await W(s,t,r,{first:Ht,after:e})).projects},Dn=`
1311
+ `;return(await H(s,t,r,{first:Jt,after:e})).projects},Ln=`
1312
1312
  id
1313
1313
  name
1314
1314
  number
@@ -1316,11 +1316,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1316
1316
  startsAt
1317
1317
  endsAt
1318
1318
  completedAt
1319
- `,Br=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:Wt(s.completedAt),url:""}),jr=async(s,t,e)=>{let r=`
1319
+ `,jr=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:Ht(s.completedAt),url:""}),Fr=async(s,t,e)=>{let r=`
1320
1320
  query GetCycles($first: Int!, $after: String) {
1321
1321
  cycles(first: $first, after: $after) {
1322
1322
  nodes {
1323
- ${Dn}
1323
+ ${Ln}
1324
1324
  }
1325
1325
  pageInfo {
1326
1326
  hasNextPage
@@ -1328,16 +1328,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1328
1328
  }
1329
1329
  }
1330
1330
  }
1331
- `;return(await W(s,t,r,{first:Ht,after:e})).cycles},Ln=`
1331
+ `;return(await H(s,t,r,{first:Jt,after:e})).cycles},An=`
1332
1332
  id
1333
1333
  name
1334
1334
  color
1335
1335
  description
1336
- `,Fr=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),zr=async(s,t,e)=>{let r=`
1336
+ `,zr=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),Mr=async(s,t,e)=>{let r=`
1337
1337
  query GetLabels($first: Int!, $after: String) {
1338
1338
  projectLabels(first: $first, after: $after) {
1339
1339
  nodes {
1340
- ${Ln}
1340
+ ${An}
1341
1341
  }
1342
1342
  pageInfo {
1343
1343
  hasNextPage
@@ -1345,36 +1345,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1345
1345
  }
1346
1346
  }
1347
1347
  }
1348
- `;return(await W(s,t,r,{first:Ht,after:e})).projectLabels};var Re=(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))(Re||{});function Mr(s,t){return s?`${Re[s]}:${t||""}`:t??null}function Wr(s){if(!s)return{category:0};let[t,e]=s.split(":");return t in Re?{category:Re[t],cursor:e||void 0}:{category:0,cursor:s}}var Hr=100;function Ve(s){return s?s instanceof Date?s:new Date(s):null}var Kr=`
1348
+ `;return(await H(s,t,r,{first:Jt,after:e})).projectLabels};var ye=(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))(ye||{});function Wr(s,t){return s?`${ye[s]}:${t||""}`:t??null}function Hr(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 Jr=100;function Ke(s){return s?s instanceof Date?s:new Date(s):null}var Xr=`
1349
1349
  id
1350
1350
  name
1351
1351
  key
1352
1352
  icon
1353
- `;function An(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var Jr=`
1353
+ `;function Un(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var Vr=`
1354
1354
  id
1355
1355
  name
1356
1356
  avatarUrl
1357
- `;function Vr(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var $n=`
1357
+ `;function Kr(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var $n=`
1358
1358
  id
1359
1359
  name
1360
- `;function Un(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var Gn=`
1360
+ `;function Gn(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var Tn=`
1361
1361
  id
1362
1362
  sortOrder
1363
1363
  name
1364
1364
  description
1365
1365
  status
1366
1366
  targetDate
1367
- `;function Tn(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:Ve(s.targetDate)}:null}function On(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var xn=`
1367
+ `;function On(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 xn(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var kn=`
1368
1368
  id
1369
1369
  name
1370
1370
  color
1371
1371
  type
1372
- `;function kn(s){return s?{id:s.id,name:s.name,color:s.color,category:On(s.type)}:null}var Vt=`
1372
+ `;function Nn(s){return s?{id:s.id,name:s.name,color:s.color,category:xn(s.type)}:null}var Kt=`
1373
1373
  creator {
1374
- ${Jr}
1374
+ ${Vr}
1375
1375
  }
1376
1376
  assignee {
1377
- ${Jr}
1377
+ ${Vr}
1378
1378
  }
1379
1379
  archivedAt
1380
1380
  createdAt
@@ -1385,32 +1385,32 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1385
1385
  ${$n}
1386
1386
  }
1387
1387
  team {
1388
- ${Kr}
1388
+ ${Xr}
1389
1389
  }
1390
1390
  state {
1391
- ${xn}
1391
+ ${kn}
1392
1392
  }
1393
1393
  title
1394
1394
  updatedAt
1395
1395
  url
1396
1396
  projectMilestone {
1397
- ${Gn}
1397
+ ${Tn}
1398
1398
  }
1399
- `;async function Jt(s){return{author:Vr(await s.creator),assignees:[Vr(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:Ve(s.archivedAt),createdDate:Ve(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:Un(await s.project,await s.team),state:kn(await s.state),title:s.title,type:null,updatedDate:Ve(s.updatedAt),upvoteCount:null,url:s.url,milestone:Tn(await s.projectMilestone)}}var Je=`
1399
+ `;async function Vt(s){return{author:Kr(await s.creator),assignees:[Kr(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:Gn(await s.project,await s.team),state:Nn(await s.state),title:s.title,type:null,updatedDate:Ke(s.updatedAt),upvoteCount:null,url:s.url,milestone:On(await s.projectMilestone)}}var Ve=`
1400
1400
  nodes {
1401
- ${Vt}
1401
+ ${Kt}
1402
1402
  }
1403
1403
  pageInfo {
1404
1404
  hasNextPage
1405
1405
  endCursor
1406
1406
  }
1407
- `,le=class extends O{async fetchIssue(t,e){let r=`
1407
+ `,pe=class extends O{async fetchIssue(t,e){let r=`
1408
1408
  query GetIssue($identifier: String!) {
1409
1409
  issue(id: $identifier) {
1410
- ${Vt}
1410
+ ${Kt}
1411
1411
  }
1412
1412
  }
1413
- `;return(await W(this.config,e,r,{identifier:t})).issue}async fetchOrganization(t){let e=`
1413
+ `;return(await H(this.config,e,r,{identifier:t})).issue}async fetchOrganization(t){let e=`
1414
1414
  query GetOrganization {
1415
1415
  organization {
1416
1416
  id
@@ -1418,15 +1418,15 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1418
1418
  urlKey
1419
1419
  }
1420
1420
  }
1421
- `;return(await W(this.config,t,e)).organization}async fetchTeams(t){let e=`
1421
+ `;return(await H(this.config,t,e)).organization}async fetchTeams(t){let e=`
1422
1422
  query GetTeams {
1423
1423
  teams {
1424
1424
  nodes {
1425
- ${Kr}
1425
+ ${Xr}
1426
1426
  }
1427
1427
  }
1428
1428
  }
1429
- `;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=`
1429
+ `;return(await H(this.config,t,e)).teams}async rawRequest(t,e,r){return{data:await H(this.config,t,e,r)}}async fetchViewer(t){let e=`
1430
1430
  query GetViewer {
1431
1431
  viewer {
1432
1432
  id
@@ -1435,11 +1435,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1435
1435
  displayName
1436
1436
  }
1437
1437
  }
1438
- `;return(await W(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await Jt(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(An)}}async getProjects(t={},e={}){let r=await Qr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(_r),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await jr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Br),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await zr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Fr),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}=Wr(r),i=await this.fetchViewer(e),a,u,l=new He,c=async(p,d)=>{if(u||n>p)return;let g=await d(Math.max(Hr-l.length,1),n===p?o:void 0);if(!g)return;let m=await Rt(g.nodes.map(Jt));l.push(...m),g.pageInfo.hasNextPage&&(a=p,u=g.pageInfo.endCursor)};return await c(1,async(p,d)=>(await this.rawRequest(e,`
1438
+ `;return(await H(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await Vt(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(Un)}}async getProjects(t={},e={}){let r=await Br(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Qr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await Fr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(jr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await Mr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(zr),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}=Hr(r),i=await this.fetchViewer(e),a,u,l=new Je,c=async(p,d)=>{if(u||n>p)return;let g=await d(Math.max(Jr-l.length,1),n===p?o:void 0);if(!g)return;let m=await yt(g.nodes.map(Vt));l.push(...m),g.pageInfo.hasNextPage&&(a=p,u=g.pageInfo.endCursor)};return await c(1,async(p,d)=>(await this.rawRequest(e,`
1439
1439
  query GetAssignedIssues($first: Int!, $after: String) {
1440
1440
  viewer {
1441
1441
  issues: assignedIssues(first: $first, after: $after) {
1442
- ${Je}
1442
+ ${Ve}
1443
1443
  }
1444
1444
  }
1445
1445
  }
@@ -1447,7 +1447,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1447
1447
  query GetCreatedIssues($first: Int!, $after: String) {
1448
1448
  viewer {
1449
1449
  issues: createdIssues(first: $first, after: $after) {
1450
- ${Je}
1450
+ ${Ve}
1451
1451
  }
1452
1452
  }
1453
1453
  }
@@ -1472,7 +1472,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1472
1472
  }]
1473
1473
  }
1474
1474
  ){
1475
- ${Je}
1475
+ ${Ve}
1476
1476
  }
1477
1477
  }
1478
1478
  `,{first:p,after:d})).data?.issues),await c(5,async(p,d)=>{let m=(await this.rawRequest(e,`
@@ -1498,7 +1498,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1498
1498
  ){
1499
1499
  nodes {
1500
1500
  issue {
1501
- ${Vt}
1501
+ ${Kt}
1502
1502
  }
1503
1503
  }
1504
1504
  pageInfo {
@@ -1507,10 +1507,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1507
1507
  }
1508
1508
  }
1509
1509
  }
1510
- `,{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:Mr(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=`
1510
+ `,{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:Wr(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=`
1511
1511
  query GetIssues($first: Int!, $after: String) {
1512
1512
  issues(first: $first, after: $after${u?", ":""}${u}) {
1513
- ${Je}
1513
+ ${Ve}
1514
1514
  }
1515
1515
  }
1516
- `,p=(await this.rawRequest(e,l,{first:Hr,after:i})).data?.issues;return p?{data:await Rt(p.nodes.map(Jt)),pageInfo:{hasNextPage:p.pageInfo.hasNextPage,endCursor:p.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var B="https://api.trello.com",Nn=1e3,_n=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),Qn=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},pe=class extends 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:_n(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=${Nn}&token=${e.token||this.config.token}&card_members=true`,headers:h(e.token||this.config.token)})).body.cards.map(d=>Qn(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 Ke={};k(Ke,{default:()=>Bn});var Bn={};var Xe={};k(Xe,{default:()=>jn});var jn={};var lt={};k(lt,{decode:()=>Kt,decodeV0:()=>Wn,encode:()=>Mn,validate:()=>zn});var A=(e=>(e.Zero="0",e.One="1",e))(A||{}),$=(e=>(e.PullRequest="pr",e.Issue="issue",e))($||{}),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 Ye=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 Ze=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(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 et=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 tt=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 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 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 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 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 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 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 it=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 at=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 ut=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new Ze:new Ye;case"bitbucket":case"bitbucketServer":return t==="pr"?new tt:new et;case"github":case"githubEnterprise":return t==="pr"?new st:new rt;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new ot:new nt;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new it;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new at;default:throw new Error("unknown provider")}},Fn=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")},zn=s=>{if(s.version==="0"){Fn(s);return}ut(s.provider,s.entityType).validate(s)},Mn=s=>ut(s.provider,s.entityType).encode(s),Kt=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return ut(t[0],t[1]).decode(t)},Wn=(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 ut(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 pt={};k(pt,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>rs,CHANGES_REQUESTED_BUCKET_ID:()=>sr,CONFLICTS_ACTION_CATEGORY:()=>es,CONFLICTS_BUCKET_ID:()=>tr,DRAFT_ACTION_CATEGORY:()=>os,DRAFT_BUCKET_ID:()=>ir,FAILING_CI_ACTION_CATEGORY:()=>Zr,FAILING_CI_BUCKET_ID:()=>er,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>ts,NEEDS_MY_REVIEW_BUCKET_ID:()=>rr,OTHER_ACTION_CATEGORY:()=>is,OTHER_BUCKET_ID:()=>ar,PINNED_BUCKET_ID:()=>Xt,READY_TO_MERGE_ACTION_CATEGORY:()=>Xr,READY_TO_MERGE_BUCKET_ID:()=>Yt,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>ss,REVIEWER_COMMENTED_BUCKET_ID:()=>nr,SNOOZED_BUCKET_ID:()=>ur,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Yr,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Zt,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>ns,WAITING_FOR_REVIEW_BUCKET_ID:()=>or,getActionablePullRequests:()=>as,groupPullRequestsByAssignee:()=>Vn,groupPullRequestsByAuthor:()=>Kn,groupPullRequestsByGitKrakenTeam:()=>eo,groupPullRequestsByRepo:()=>Jn,groupPullRequestsByReviewer:()=>Xn,groupPullRequestsByWorkspace:()=>Zn,groupPullRequestsIntoBuckets:()=>Hn});var T=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Xt="pinned",Yt="readyToMerge",Zt="unassignedReviewers",er="failingCI",tr="conflicts",rr="needsMyReview",sr="changesRequested",nr="reviewerCommented",or="waitingForReview",ir="draft",ar="other",ur="snoozed",Xr="readyToMerge",Yr="unassignedReviewers",Zr="failingCI",es="conflicts",ts="needsMyReview",rs="changesRequested",ss="reviewerCommented",ns="waitingForReview",os="draft",is="other",as=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:is,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=Xr),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=os),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=ns,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=ss),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Zr),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=es),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=rs),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=Yr,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=ts,o.viewer.shouldReview=!0),o}),Hn=(s,t,e)=>{let r={pinned:T(Xt,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:T(Yt,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:T(Zt,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:T(er,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:T(tr,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:T(rr,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:T(sr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:T(nr,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:T(or,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:T(ir,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:T(ar,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:T(ur,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=as(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[ur].pullRequests.push(i);return}a.viewer.pinned&&r[Xt].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[Yt].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[Zt].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[er].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[tr].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[rr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[sr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[nr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[or].pullRequests.push(i),u=!1),a.isDraft&&(r[ir].pullRequests.push(i),u=!1),u&&r[ar].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},Jn=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}}),Y(t)},Vn=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:be(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Y(e)},Kn=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:be(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),Y(e)},Xn=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:be(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Y(e)},Yn=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.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((o,i)=>(Yn(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Kt(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 Y(r)},eo=(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,Y(o)};var dt={};k(dt,{getPullRequestRank:()=>to});var to=(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 ct={};k(ct,{default:()=>ro});var ro={};var gt={};k(gt,{default:()=>so});var so={};var mt={};k(mt,{default:()=>no});var no={};var us=s=>{let t={request:s?.request};return{azureDevOps:new ee({...t,...s?.azureDevOps}),bitbucket:new te({...t,...s?.bitbucket}),bitbucketServer:new re({...t,...s?.bitbucketServer}),github:new ne({...t,...s?.github}),gitlab:new ie({...t,...s?.gitlab}),jira:new ae({...t,...s?.jira}),jiraServer:new ue({...t,...s?.jiraServer}),linear:new le({...t,...s?.linear}),trello:new pe({...t,...s?.trello})}};var ls=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(ls||{});var ps=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(ps||{});var oo=us;var io={azureDevOps:Ke,bitbucket:Xe,bitbucketServer:qe,github:dt,gitlab:ct,gitProvider:pt,jira:gt,trello:mt,entityIdentifier:lt};
1516
+ `,p=(await this.rawRequest(e,l,{first:Jr,after:i})).data?.issues;return p?{data:await yt(p.nodes.map(Vt)),pageInfo:{hasNextPage:p.pageInfo.hasNextPage,endCursor:p.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var B="https://api.trello.com",_n=1e3,j=(s,t)=>({...I(t),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${t}"`}),Qn=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),Bn=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},de=class extends O{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||B}/1/members/me`,headers:j(t.appKey,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&filter=open`,headers:j(t.appKey,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`,headers:j(r,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}`,headers:j(r,e.token||this.config.token)});return{data:Qn(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`,headers:j(r,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?query=${c}&cards_limit=${_n}&card_members=true`,headers:j(n,e.token||this.config.token)})).body.cards.map(d=>Bn(d,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||B}/1/cards/${e.id}?${r}`,headers:j(t,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}?idLabels=${encodeURIComponent(i)}`,headers:j(r,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}?closed=${o}`,headers:j(r,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`,headers:j(r,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var Xe={};k(Xe,{default:()=>jn});var jn={};var Ye={};k(Ye,{default:()=>Fn});var Fn={};var pt={};k(pt,{decode:()=>Xt,decodeV0:()=>Hn,encode:()=>Wn,validate:()=>Mn});var A=(e=>(e.Zero="0",e.One="1",e))(A||{}),U=(e=>(e.PullRequest="pr",e.Issue="issue",e))(U||{}),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 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 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 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 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 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 it:new ot;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")}},zn=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")},Mn=s=>{if(s.version==="0"){zn(s);return}lt(s.provider,s.entityType).validate(s)},Wn=s=>lt(s.provider,s.entityType).encode(s),Xt=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)},Hn=(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={};k(dt,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>ss,CHANGES_REQUESTED_BUCKET_ID:()=>nr,CONFLICTS_ACTION_CATEGORY:()=>ts,CONFLICTS_BUCKET_ID:()=>rr,DRAFT_ACTION_CATEGORY:()=>is,DRAFT_BUCKET_ID:()=>ar,FAILING_CI_ACTION_CATEGORY:()=>es,FAILING_CI_BUCKET_ID:()=>tr,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>rs,NEEDS_MY_REVIEW_BUCKET_ID:()=>sr,OTHER_ACTION_CATEGORY:()=>as,OTHER_BUCKET_ID:()=>ur,PINNED_BUCKET_ID:()=>Yt,READY_TO_MERGE_ACTION_CATEGORY:()=>Yr,READY_TO_MERGE_BUCKET_ID:()=>Zt,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>ns,REVIEWER_COMMENTED_BUCKET_ID:()=>or,SNOOZED_BUCKET_ID:()=>lr,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Zr,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>er,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>os,WAITING_FOR_REVIEW_BUCKET_ID:()=>ir,getActionablePullRequests:()=>us,groupPullRequestsByAssignee:()=>Kn,groupPullRequestsByAuthor:()=>Xn,groupPullRequestsByGitKrakenTeam:()=>to,groupPullRequestsByRepo:()=>Vn,groupPullRequestsByReviewer:()=>Yn,groupPullRequestsByWorkspace:()=>eo,groupPullRequestsIntoBuckets:()=>Jn});var T=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Yt="pinned",Zt="readyToMerge",er="unassignedReviewers",tr="failingCI",rr="conflicts",sr="needsMyReview",nr="changesRequested",or="reviewerCommented",ir="waitingForReview",ar="draft",ur="other",lr="snoozed",Yr="readyToMerge",Zr="unassignedReviewers",es="failingCI",ts="conflicts",rs="needsMyReview",ss="changesRequested",ns="reviewerCommented",os="waitingForReview",is="draft",as="other",us=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:as,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=Yr),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=is),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=os,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=ns),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=es),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=ts),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=ss),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=Zr,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=rs,o.viewer.shouldReview=!0),o}),Jn=(s,t,e)=>{let r={pinned:T(Yt,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:T(Zt,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:T(er,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:T(tr,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:T(rr,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:T(sr,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:T(nr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:T(or,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:T(ir,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:T(ar,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:T(ur,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:T(lr,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=us(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[lr].pullRequests.push(i);return}a.viewer.pinned&&r[Yt].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[Zt].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[er].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[tr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[rr].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[sr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[nr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[or].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[ir].pullRequests.push(i),u=!1),a.isDraft&&(r[ar].pullRequests.push(i),u=!1),u&&r[ur].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},Vn=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),Z(t)},Kn=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:Pe(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Z(e)},Xn=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)}),Z(e)},Yn=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Pe(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Z(e)},Zn=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],eo=(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)=>(Zn(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Xt(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 Z(r)},to=(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,Z(o)};var ct={};k(ct,{getPullRequestRank:()=>ro});var ro=(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 gt={};k(gt,{default:()=>so});var so={};var mt={};k(mt,{default:()=>no});var no={};var ht={};k(ht,{default:()=>oo});var oo={};var ls=s=>{let t={request:s?.request};return{azureDevOps:new te({...t,...s?.azureDevOps}),bitbucket:new re({...t,...s?.bitbucket}),bitbucketServer:new se({...t,...s?.bitbucketServer}),github:new oe({...t,...s?.github}),gitlab:new ae({...t,...s?.gitlab}),jira:new ue({...t,...s?.jira}),jiraServer:new le({...t,...s?.jiraServer}),linear:new pe({...t,...s?.linear}),trello:new de({...t,...s?.trello})}};var ps=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(ps||{});var ds=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(ds||{});var io=ls;var ao={azureDevOps:Xe,bitbucket:Ye,bitbucketServer:Se,github:ct,gitlab:gt,gitProvider:dt,jira:mt,trello:ht,entityIdentifier:pt};