@gitkraken/provider-apis 0.31.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var ct=Object.defineProperty;var is=Object.getOwnPropertyDescriptor;var as=Object.getOwnPropertyNames;var us=Object.prototype.hasOwnProperty;var x=(s,t)=>{for(var e in t)ct(s,e,{get:t[e],enumerable:!0})},ls=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of as(t))!us.call(s,n)&&n!==e&&ct(s,n,{get:()=>t[n],enumerable:!(r=is(t,n))||r.enumerable});return s};var ps=s=>ls(ct({},"__esModule",{value:!0}),s);var ro={};x(ro,{AzureDevOps:()=>Z,AzureDevopsUtils:()=>He,Bitbucket:()=>ee,BitbucketServer:()=>te,BitbucketServerUtils:()=>we,BitbucketUtils:()=>Je,EntityIdentifierProviderType:()=>D,EntityIdentifierUtils:()=>it,EntityType:()=>L,EntityVersion:()=>A,GitBuildStatusStage:()=>ur,GitBuildStatusState:()=>ce,GitDiffLineType:()=>gt,GitHub:()=>se,GitHubIssueCloseReason:()=>ns,GitHubUtils:()=>ut,GitIssueState:()=>ve,GitLab:()=>oe,GitLabUtils:()=>lt,GitMergeStrategy:()=>Y,GitProviderUtils:()=>at,GitPullRequestMergeableState:()=>Q,GitPullRequestReviewState:()=>N,GitPullRequestState:()=>K,GraphQLErrors:()=>f,Jira:()=>ie,JiraServer:()=>ae,JiraUtils:()=>pt,Linear:()=>ue,PullRequestAsyncStatus:()=>ss,Trello:()=>le,TrelloUtils:()=>dt,Utils:()=>to,default:()=>eo,isFetch:()=>Re});module.exports=ps(ro);var ur=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(ur||{}),ce=(c=>(c.ActionRequired="ACTION_REQUIRED",c.Cancelled="CANCELLED",c.Error="ERROR",c.Failed="FAILED",c.Pending="PENDING",c.Running="RUNNING",c.Skipped="SKIPPED",c.Success="SUCCESS",c.Warning="WARNING",c.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",c))(ce||{}),Y=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(Y||{}),K=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(K||{}),N=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(N||{}),Q=(u=>(u.Behind="BEHIND",u.Blocked="BLOCKED",u.Conflicts="CONFLICTS",u.FailingChecks="FAILING_CHECKS",u.Mergeable="MERGEABLE",u.Unknown="UNKNOWN",u.UnknownAndBlocked="UNKNOWN_AND_BLOCKED",u.Unstable="UNSTABLE",u))(Q||{}),gt=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(gt||{});var lr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},_=s=>!s||s.length===0?null:s.reduce((t,e)=>lr[e.state]>lr[t]?e.state:t,"APPROVED"),Ie=(s,t)=>s.name||s.username||s.email||t,X=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var v=100;var pr=globalThis.fetch;var ds=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(t.startsWith("text/")||t==="")e=await s.text();else if(t.startsWith("application/vnd.github.raw+json"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${t}`);let r={};s.headers.forEach((o,i)=>{r[i]=o});let n={body:e,headers:r,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},mt=s=>async({url:t,...e})=>{let r=await s(t,e);return ds(r)};var Re=(s,t=!1)=>s.name==="fetch"||t;var O=class{constructor(t){let e=t?.request||pr;this.config={...t,request:Re(e,t?.forceIsFetch)?mt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&Re(t.request,t?.forceIsFetch??this.config.forceIsFetch)?mt(t.request):this.config.request}}},$=class extends O{};var h=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},dr=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,H=(s,t,e)=>!s||t.some(r=>s[r])?e:"",cr=async s=>{let t=[],e=!0,r;for(;e;){let n=await s(r);t=t.concat(n.data),e=!!n?.pageInfo?.hasNextPage,r=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return t};async function ht(s){return(await Promise.allSettled(s)).map(e=>cs(e)).filter(e=>e!=null)}function cs(s,t=void 0){return s?.status==="fulfilled"?s.value:t}var gs="https://app.vssps.visualstudio.com/_apis",ms="https://vssps.dev.azure.com/",hs="https://dev.azure.com",P=(s,t={})=>h(t.token||s.token,t.isPAT||s.isPAT),gr=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),ft=(s,t)=>{let e=t.baseUrl||s.baseUrl||gs;return e=e.replace(/\/$/,""),e},w=(s,t)=>{let e=t.baseUrl||s.baseUrl||hs;return e=e.replace(/\/$/,""),e},It=(s,t)=>{let e=t.baseUrl||s.baseUrl||ms;return e=e.replace(/\/$/,""),e};var fs={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Is={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},Rt=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),be=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Rs=s=>{switch(s){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},ye=(s,t)=>{let e=[],r=[];return t.reviewers.forEach(n=>{let o={reviewer:Rt(n),state:Is[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),r.push(o)}),{id:t.pullRequestId.toString(),title:t.title,number:t.codeReviewId,state:fs[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:Rt(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:be(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:be(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:gr(t),assignees:t.reviewers.map(Rt),reviews:r,reviewDecision:_(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:null}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:Rs(t.mergeStatus),labels:t.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},mr=(s,t)=>({id:t.id,name:t.name,namespace:s,project:t.project.name,projectId:t.project.id,webUrl:t.webUrl,httpsUrl:t.remoteUrl,sshUrl:t.sshUrl,defaultBranch:t.defaultBranch?{name:be(t.defaultBranch)}:null,permissions:null}),ys=(s,t,e,r)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=r[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},Z=class extends ${async getCurrentUser(t={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${ft(this.config,e)}/profile/profiles/me`,n=await this.config.request({url:r,headers:P(this.config,e)});return{data:{id:n.body.id,name:n.body.displayName,username:n.body.displayName,email:n.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(t,e={}){let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/ConnectionData`,headers:P(this.config,e)})).body.authorizedUser;if(n.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:n.id,name:n.providerDisplayName,username:n.providerDisplayName,email:n.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/commits/${t.oid}`,headers:P(this.config,e)})).body.author;return{data:{name:n.name,email:n.email,avatarUrl:n.imageUrl}}}async getOrgsForUser(t,e={}){let r=`${ft(this.config,e)}/accounts?memberId=${t.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:P(this.config,e)})).body.value.map(o=>({id:o.accountId,name:o.accountName}))}}async getCollectionsForUser(t,e={}){let r=`${w(this.config,e)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:P(this.config,e)})).body.value.map(o=>({id:o.id,name:o.name}))}}async getAzureProjects(t,e={}){let r=new URL(`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/_apis/projects`);r.searchParams.set("$top",v.toString()),t.cursor&&r.searchParams.set("$skip",t.cursor);let n=await this.config.request({url:r.toString(),headers:P(this.config,e)}),o=n.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:n.body.value.map(i=>({id:i.id,name:i.name,namespace:t.namespace}))}}async getAzureProjectScopeDescriptor(t,e={}){let{namespace:r,projectId:n}=t;return{data:{scope:(await this.config.request({url:`${It(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${n}?api-version=6.0`,headers:P(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(t,e={}){let{namespace:r,projectScopeDescriptor:n,cursor:o}=t,i=new URL(`${It(this.config,e)}/${encodeURIComponent(r)}/_apis/graph/users`);n&&i.searchParams.set("scopeDescriptor",n),o&&i.searchParams.set("continuationToken",o);let a=await this.config.request({url:i.toString(),headers:P(this.config,e)}),u=a.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:a.body.value.map(l=>({avatarUrl:l._links?.avatar?.href??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:l._links?.storageKey?.href??null,username:l.displayName??null}))}}async getAccountFromAzureGraphAccount(t,e={}){let{azureGraphAccount:r}=t;if(!r.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let n=await this.config.request({url:r.storageKeyURL,headers:P(this.config,e)});return{data:{avatarUrl:r.avatarUrl,email:r.email,id:n.body.value,name:r.name,username:r.username,url:null}}}async getAccountsFromAzureGraphAccounts(t,e={}){let r=[];for(let n of t.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:n},e);r.push(o.data)}return{data:r}}async getRepo(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories/${encodeURIComponent(t.name)}`,headers:P(this.config,e)});return{data:mr(t.namespace,r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/git/repositories`,headers:P(this.config,e)})).body.value.map(n=>mr(t.namespace,n))}}async getRefs(t,e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=new URL(`${w(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);n.searchParams.set("filter",t),n.searchParams.set("$top",v.toString()),e.cursor&&n.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:n.toString(),headers:P(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({name:be(a.name),commit:{oid:a.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(t,e={}){return this.getRefs("heads",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getPullRequestsForRepoBase(t,e={},r=100){let{page:n,repo:o,assigneeLogins:i,authorLogin:a}=t||{},u=n||1;if(!o.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return i&&i.length&&(l+=`&searchCriteria.reviewerId=${i[0]}`),a&&(l+=`&searchCriteria.creatorId=${a}`),await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${r}&%24skip=${(u-1)*r}`,headers:P(this.config,e)})}async getPullRequestsForRepo(t,e={}){let n=t.page||1,o=await this.getPullRequestsForRepoBase(t,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:n+1},data:o.body.value.map(i=>ye(t.repo.namespace,i))}}async getPullRequestsForRepos(t,e={}){if(!t.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...t},e)).body.value.forEach(a=>{n.push(ye(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(t,e={},r=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=t;if(l?.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let c=i||1,p=new URL(`${w(this.config,e)}/${encodeURIComponent(n)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return p.searchParams.set("searchCriteria.status","1"),p.searchParams.set("$top",r.toString()),p.searchParams.set("$skip",((c-1)*r).toString()),l?.id&&l?.project===o&&p.searchParams.set("searchCriteria.repositoryId",l.id),a&&a.length&&p.searchParams.set("searchCriteria.reviewerId",a[0]),u&&p.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:p.toString(),headers:P(this.config,e)})}async getPullRequestsForProject(t,e={}){let n=t.page||1,o=await this.getPullRequestsForProjectBase(t,e,100);return{pageInfo:{hasNextPage:o?.body.value.length===100,nextPage:n+1},data:o?.body.value.map(i=>ye(t.namespace,i))||[]}}async getPullRequestsForProjects(t,e={}){let{projects:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(!t.repo||t.repo.project&&t.repo.project===o.project)&&(await this.getPullRequestsForProjectBase({...o,...t},e))?.body.value.forEach(a=>{n.push(ye(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getAzurePullRequestLastMergeStatus(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:r,project:n,name:o},pullRequestId:i}=t,a=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/git/repositories/${o}/pullrequests/${i}?includeCommits=true?api-version=6.0`,headers:{...P(this.config,e)}});if(!a.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:a.body.mergeStatus}}async updatePullRequest(t,e,r){return await this.config.request({method:"PATCH",url:`${w(this.config,r)}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}?api-version=6.0`,body:e,headers:{...P(this.config,r),"Content-Type":"application/json"}})}async closePullRequest(t,e={}){let{pullRequest:r}=t,n={status:"abandoned"};if(!(await this.updatePullRequest(r,JSON.stringify(n),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="noFastForward";break}case"REBASE":{o="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{o="rebaseMerge";break}case"SQUASH":{o="squash";break}}let i={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:r.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(i),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(t,e={}){let{pullRequest:r,label:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o={name:n.name};if(!(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels?api-version=6.0`,body:JSON.stringify(o),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(t,e={}){let{pullRequest:r,label:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(n.name)}?api-version=6.0`,headers:{...P(this.config,e)}})}async setPullRequestLabels(t,e={}){let{pullRequest:r,labels:n}=t;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=r.labels;if(!o)throw new Error('Azure DevOps requires "labels" for this function.');for(let i of n)o.find(a=>a.id===i.id)||await this.addPullRequestLabel({pullRequest:r,label:i},e);for(let i of o)n.find(a=>i.id===a.id)||await this.removePullRequestLabel({pullRequest:r,label:i},e)}async setPullRequestAsDraft(t,e={}){let{pullRequest:r,isDraft:n}=t,o={isDraft:n};if(!(await this.updatePullRequest(r,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n,isRequired:o}=t,i={id:n.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,body:JSON.stringify(i),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(t,e={}){let{pullRequest:r,reviewer:n}=t;await this.config.request({method:"DELETE",url:`${w(this.config,e)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${n.id}?api-version=6.0`,headers:{...P(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;for(let o of n)r.assignees.find(i=>i.id===o.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:o,isRequired:!0},e);for(let o of r.assignees)n.find(i=>o.id===i.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:o},e)}async getIssuesForAzureProject(t,e={}){let{page:r,assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,statusByWorkItemIdByStatusId:u}=t||{},l=r||1,c=200,p=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&p.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),n&&n[0]&&p.push(`[System.AssignedTo] = '${n[0].replace("'","''")}'`),i&&p.push("[System.Id] IN (@recentMentions)"),a&&a.forEach(R=>p.push(`[System.Tags] Contains '${R}'`));let d=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${p.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:d}),method:"POST",headers:{...P(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*c,c*l).map(R=>R.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let y=await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(t.namespace)}/${encodeURIComponent(t.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...P(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>c*l,nextPage:l+1},data:y.body.value.map(R=>ys(t.namespace,t.project,R,u||{}))}}async getPermissionsForRepos(t,e={}){let{namespace:r,repos:n}=t,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},i=c=>{let p="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",d=`repoV2/${c.projectId}/${c.id}`;return Object.keys(o).map(g=>({securityNamespaceId:p,token:d,permissions:g}))},a={alwaysAllowAdministrators:!1,evaluations:n.flatMap(i)};return{data:(await this.config.request({method:"POST",url:`${w(this.config,e)}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(a),headers:{...P(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((c,p)=>{let[,d,g]=p.token.split("/"),m=`${d}/${g}`,y=o[p.permissions];for(let R of y)c[m]===void 0&&(c[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),p.value===!1&&(c[m][R]=!1);return c},{})}}async decorateReposWithPermissions(t,e={}){let{namespace:r,repos:n}=t,o=await this.getPermissionsForRepos({namespace:r,repos:n},e);return{data:n.map(i=>({...i,permissions:o.data[`${i.projectId}/${i.id}`]}))}}async updateIssue(t,e,r={}){return await this.config.request({method:"PATCH",url:`${w(this.config,r)}/${encodeURIComponent(t.project.namespace)}/${encodeURIComponent(t.project.name)}/_apis/wit/workitems/${t.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...P(this.config,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(t,e={}){let{issue:r,status:n}=t,o=[{op:"add",path:"/fields/System.State",value:n.name}];if(!(await this.updateIssue(r,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(t,e={}){let{issue:r,assignee:n}=t,o=[{op:"add",path:"/fields/System.AssignedTo",value:n?.name??""}];if(!(await this.updateIssue(r,o,e)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(t,e={}){let{issue:r,labels:n}=t,i=[{op:"replace",path:"/fields/System.Tags",value:n.map(u=>u.name).join(";")}];if(!(await this.updateIssue(r,i,e)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(t,e={}){if(!t.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...P(this.config,e)}})).body.value}}async getLabelsForProject(t,e={}){let{namespace:r,project:n}=t;return{data:(await this.config.request({url:`${w(this.config,e)}/${encodeURIComponent(r)}/${encodeURIComponent(n||"")}/_apis/wit/tags?api-version=6.0`,headers:{...P(this.config,e)}})).body.value.map(i=>({color:null,description:null,id:i.id,name:i.name,url:i.url}))}}};var q=(s,t={})=>h(t.token||s.token,t.isPAT||s.isPAT);var S="https://api.bitbucket.org/2.0",bs={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},Pe=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),hr=s=>{let t=s.links.clone,e=t?.find(n=>n.name==="ssh"),r=t?.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},fr=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(t=>t.name==="https")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),yt=s=>{let t=s.id,e=s.participants?.map(r=>{let n="REVIEW_REQUESTED";return r.approved?n="APPROVED":r.state==="changes_requested"?n="CHANGES_REQUESTED":r.participated_on!==null&&(n="COMMENTED"),{reviewer:Pe(r.user),state:n}})??[];return{id:t.toString(),title:s.title,number:t,state:bs[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:Pe(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo:hr(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:_(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:hr(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Ps=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},ee=class extends O{async refreshToken(t){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${S}/user`,headers:q(this.config,e)});return{data:Pe(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${S}/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:`${S}/repositories/${t.namespace}/${t.name}`,headers:q(this.config,e)});return{data:fr(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=new URL(`${S}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",v.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers: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(fr)}}async getBranches(t,e={}){let r=new URL(`${S}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",v.toString());let n=await this.config.request({url:r.toString(),headers: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(`${S}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",v.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers: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(`${S}/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(`${S}/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(yt)}}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${S}/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(yt(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{r.push(yt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${S}/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=>Pe(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${S}/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]:Ps(a.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${S}/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:`${S}/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:`${S}/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 we={};x(we,{normalizePermissions:()=>bt,restApiPullRequestToCommonPullRequest:()=>ws});var ws=s=>ge(s),bt=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var me=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},ge=s=>{let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(u=>({reviewer:me(u.user),state:e[u.status]})),n=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:s.id.toString(),number:s.id,title:s.title,url:s.links.self[0].href,state:t[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:me(s.author.user),assignees:null,reviews:r,reviewDecision:_(r),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},Ir=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(t=>t.name==="https"||t.name==="http")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),te=class extends ${getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return h(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:c,id:p,name:d,slug:g})=>i?i===p:a===d||a===c||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:me(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:me(o.body.author)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data:Ir(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=t.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Ir)}}async getRepoPermissionsForUsername(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:bt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests?state=OPEN`);return r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50"),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(ge(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(ge(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getPullRequestsForCurrentUser(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state","OPEN"),r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(ge)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>me(i.user))}}};var Er=require("js-base64");var ve=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ve||{});var f=class extends Error{constructor(e,r){let n=r?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var vs={AS_CODE_OWNER:[3,0,0],CHECK_RUN:[3,0,0],LATEST_REVIEWS:[3,0,0],VIEWER_CAN_MERGE_AS_ADMIN:[3,5,0],ISSUE_FULL_DATABASE_ID:[3,12,0],PR_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_COMMENT_FULL_DATABASE_ID:[3,13,0]},Rr=15,yr=100,C=s=>!!s,j=(s,t)=>{let e=vs[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},qe="https://api.github.com",Es=`${qe}/graphql`,Se=`
1
+ "use strict";var mt=Object.defineProperty;var as=Object.getOwnPropertyDescriptor;var us=Object.getOwnPropertyNames;var ls=Object.prototype.hasOwnProperty;var x=(s,t)=>{for(var e in t)mt(s,e,{get:t[e],enumerable:!0})},ps=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of us(t))!ls.call(s,n)&&n!==e&&mt(s,n,{get:()=>t[n],enumerable:!(r=as(t,n))||r.enumerable});return s};var ds=s=>ps(mt({},"__esModule",{value:!0}),s);var so={};x(so,{AzureDevOps:()=>ee,AzureDevopsUtils:()=>Je,Bitbucket:()=>te,BitbucketServer:()=>re,BitbucketServerUtils:()=>ve,BitbucketUtils:()=>Ve,EntityIdentifierProviderType:()=>L,EntityIdentifierUtils:()=>at,EntityType:()=>$,EntityVersion:()=>A,GitBuildStatusStage:()=>pr,GitBuildStatusState:()=>ce,GitDiffLineType:()=>ht,GitHub:()=>ne,GitHubIssueCloseReason:()=>is,GitHubUtils:()=>lt,GitIssueState:()=>qe,GitLab:()=>ie,GitLabUtils:()=>pt,GitMergeStrategy:()=>Z,GitProviderUtils:()=>ut,GitPullRequestMergeableState:()=>Q,GitPullRequestReviewState:()=>N,GitPullRequestState:()=>X,GraphQLErrors:()=>f,Jira:()=>ae,JiraServer:()=>ue,JiraUtils:()=>dt,Linear:()=>le,PullRequestAsyncStatus:()=>os,Trello:()=>pe,TrelloUtils:()=>ct,Utils:()=>ro,default:()=>to,isFetch:()=>ye});module.exports=ds(so);var pr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(pr||{}),ce=(d=>(d.ActionRequired="ACTION_REQUIRED",d.Cancelled="CANCELLED",d.Error="ERROR",d.Failed="FAILED",d.Pending="PENDING",d.Running="RUNNING",d.Skipped="SKIPPED",d.Success="SUCCESS",d.Warning="WARNING",d.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",d))(ce||{}),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||{}),Q=(u=>(u.Behind="BEHIND",u.Blocked="BLOCKED",u.Conflicts="CONFLICTS",u.FailingChecks="FAILING_CHECKS",u.Mergeable="MERGEABLE",u.Unknown="UNKNOWN",u.UnknownAndBlocked="UNKNOWN_AND_BLOCKED",u.Unstable="UNSTABLE",u))(Q||{}),ht=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(ht||{});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"),Re=(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 q=100;var cr=globalThis.fetch;var cs=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},ft=s=>async({url:t,...e})=>{let r=await s(t,e);return cs(r)};var ye=(s,t=!1)=>s.name==="fetch"||t;var O=class{constructor(t){let e=t?.request||cr;this.config={...t,request:ye(e,t?.forceIsFetch)?ft(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&ye(t.request,t?.forceIsFetch??this.config.forceIsFetch)?ft(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,H=(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 It(s){return(await Promise.allSettled(s)).map(e=>gs(e)).filter(e=>e!=null)}function gs(s,t=void 0){return s?.status==="fulfilled"?s.value:t}var ms="https://app.vssps.visualstudio.com/_apis",hs="https://vssps.dev.azure.com/",fs="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/"),Rt=(s,t)=>{let e=t.baseUrl||s.baseUrl||ms;return e=e.replace(/\/$/,""),e},w=(s,t)=>{let e=t.baseUrl||s.baseUrl||fs;return e=e.replace(/\/$/,""),e},yt=(s,t)=>{let e=t.baseUrl||s.baseUrl||hs;return e=e.replace(/\/$/,""),e};var Is={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Rs={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},bt=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Pe=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,ys=s=>{switch(s){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},be=(s,t)=>{let e=[],r=[];return t.reviewers.forEach(n=>{let o={reviewer:bt(n),state:Rs[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:Is[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:bt(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Pe(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Pe(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:hr(t),assignees:t.reviewers.map(bt),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:ys(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:Pe(t.defaultBranch)}:null,permissions:null}),bs=(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=`${Rt(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=`${Rt(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",q.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:`${yt(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(`${yt(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",q.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:Pe(a.name),commit:{oid:a.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(t,e={}){return this.getRefs("heads",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getPullRequestsForRepoBase(t,e={},r=100){let{page:n,repo:o,assigneeLogins:i,authorLogin:a}=t||{},u=n||1;if(!o.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return i&&i.length&&(l+=`&searchCriteria.reviewerId=${i[0]}`),a&&(l+=`&searchCriteria.creatorId=${a}`),await this.config.request({url:`${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=>be(t.repo.namespace,i))}}async getPullRequestsForRepos(t,e={}){if(!t.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:r}=t||{},n=[];return await Promise.all(r.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...t},e)).body.value.forEach(a=>{n.push(be(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getPullRequestsForProjectBase(t,e={},r=100){let{namespace:n,project:o,page:i,assigneeLogins:a,authorLogin:u,repo:l}=t;if(l?.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let d=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",((d-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=>be(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(be(o.namespace,a))})}catch(i){if(i.statusCode!==404&&i.statusCode!==401)throw i}})),{data:n}}async getAzurePullRequestLastMergeStatus(t,e={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:r,project:n,name:o},pullRequestId:i}=t,a=await this.config.request({url:`${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,d=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 c=`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:c}),method:"POST",headers:{...P(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*d,d*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>d*l,nextPage:l+1},data:y.body.value.map(R=>bs(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=d=>{let p="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${d.projectId}/${d.id}`;return Object.keys(o).map(g=>({securityNamespaceId:p,token:c,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((d,p)=>{let[,c,g]=p.token.split("/"),m=`${c}/${g}`,y=o[p.permissions];for(let R of y)d[m]===void 0&&(d[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),p.value===!1&&(d[m][R]=!1);return d},{})}}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 E=(s,t={})=>h(t.token||s.token,t.isPAT||s.isPAT);var C="https://api.bitbucket.org/2.0",Ps={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},we=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),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}),Pt=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:we(r.user),state:n}})??[];return{id:t.toString(),title:s.title,description:s.description,number:t,state:Ps[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:we(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo: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}},ws=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:E(this.config,e)});return{data:we(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:E(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:E(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",q.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:E(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",q.toString());let n=await this.config.request({url:r.toString(),headers:E(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",q.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:E(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:E(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:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Pt)}}async getPullRequestsForRepoBase(t,e={}){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:E(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{r.push(Pt(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{r.push(Pt(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:E(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>we(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:E(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]:ws(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:E(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:{...E(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:{...E(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var ve={};x(ve,{normalizePermissions:()=>wt,restApiPullRequestToCommonPullRequest:()=>vs});var vs=s=>ge(s),wt=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var me=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},ge=s=>{let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(u=>({reviewer:me(u.user),state:e[u.status]})),n=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:s.id.toString(),number:s.id,title:s.title,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:me(s.author.user),assignees:null,reviews:r,reviewDecision:_(r),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},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:d,id:p,name:c,slug:g})=>i?i===p:a===c||a===d||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:me(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:me(o.body.author)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data: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:wt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests?state=OPEN`);return r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50"),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(ge(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(ge(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getPullRequestsForCurrentUser(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state","OPEN"),r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(ge)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>me(i.user))}}};var Sr=require("js-base64");var qe=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(qe||{});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 qs={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,D=s=>!!s,j=(s,t)=>{let e=qs[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Se="https://api.github.com",Es=`${Se}/graphql`,Ce=`
2
2
  description
3
3
  dueOn
4
4
  id
@@ -6,7 +6,7 @@ number
6
6
  state
7
7
  title
8
8
  url
9
- `,qs=`
9
+ `,Ss=`
10
10
  ... on CheckRun {
11
11
  completedAt
12
12
  conclusion
@@ -15,12 +15,12 @@ url
15
15
  permalink
16
16
  startedAt
17
17
  }
18
- `,Ee=/\/api\/v\d+$/,Ce=`
18
+ `,Ee=/\/api\/v\d+$/,De=`
19
19
  color
20
20
  description
21
21
  id
22
22
  name
23
- `,br=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},Ss=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),br(e),Ee.test(e)&&(e=e.replace(Ee,"")),`${e}/api/graphql`):Es},re=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),br(e),Ee.test(e)&&(e=e.replace(Ee,"")),`${e}/api/v3`):qe},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:Ss(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},Cs={user:!0,"user:email":!0,"read:user":!0},F=s=>s.some(t=>Cs[t]),U=(s=!1,t=!1,e)=>`
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.")},Cs=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),wr(e),Ee.test(e)&&(e=e.replace(Ee,"")),`${e}/api/graphql`):Es},se=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),wr(e),Ee.test(e)&&(e=e.replace(Ee,"")),`${e}/api/v3`):Se},I=(s,t,e)=>{let r=h(e.token||s.token);return r["X-Github-Next-Global-ID"]="1",r["Content-Type"]="application/json",r.Accept="application/vnd.github.merge-info-preview+json",s.request({url:Cs(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},Ds={user:!0,"user:email":!0,"read:user":!0},F=s=>s.some(t=>Ds[t]),G=(s=!1,t=!1,e)=>`
24
24
  __typename
25
25
  ${H(e,["graphQLId"],"id")}
26
26
  ${H(e,["id"],"databaseId")}
@@ -29,48 +29,49 @@ ${H(e,["name","username"],"login")}
29
29
  ${t?H(e,["email"],"email"):""}
30
30
  ${H(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
31
31
  ${H(e,["url"],"url")}
32
- `,Ds=(s=!1)=>`
32
+ `,Ls=(s=!1)=>`
33
33
  latestReviews(first: 100) {
34
34
  nodes {
35
35
  author {
36
36
  ... on User {
37
- ${U(!1,s)}
37
+ ${G(!1,s)}
38
38
  }
39
39
  ... on EnterpriseUserAccount {
40
- ${Pt(!1)}
40
+ ${vt(!1)}
41
41
  }
42
42
  }
43
43
  state
44
44
  }
45
45
  }
46
- `,Pr=(s=!1)=>`
46
+ `,vr=(s=!1)=>`
47
47
  __typename
48
48
  id
49
49
  databaseId
50
50
  login
51
51
  avatarUrl${s?"(size: $avatarSize)":""}
52
52
  url
53
- `,Pt=(s=!1)=>`
53
+ `,vt=(s=!1)=>`
54
54
  __typename
55
55
  id
56
56
  login
57
57
  avatarUrl${s?"(size: $avatarSize)":""}
58
58
  url
59
- `,De=(s,t=!1,e)=>`
59
+ `,Le=(s,t=!1,e)=>`
60
60
  id
61
61
  ${!e||j(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
62
62
  number
63
63
  title
64
+ body
64
65
  state
65
66
  author {
66
67
  ... on User {
67
- ${U(!1,t)}
68
+ ${G(!1,t)}
68
69
  }
69
70
  ... on Bot {
70
- ${Pr(!1)}
71
+ ${vr(!1)}
71
72
  }
72
73
  ... on EnterpriseUserAccount {
73
- ${Pt(!1)}
74
+ ${vt(!1)}
74
75
  }
75
76
  }
76
77
  commits(last: 1) {
@@ -83,7 +84,7 @@ commits(last: 1) {
83
84
  contexts(first: 100) {
84
85
  totalCount
85
86
  nodes {
86
- ${!e||j(e,"CHECK_RUN")?qs:""}
87
+ ${!e||j(e,"CHECK_RUN")?Ss:""}
87
88
  ... on StatusContext {
88
89
  context
89
90
  createdAt
@@ -145,7 +146,7 @@ closedAt
145
146
  mergedAt
146
147
  assignees(first: 100) {
147
148
  nodes {
148
- ${U(!1,t)}
149
+ ${G(!1,t)}
149
150
  }
150
151
  }
151
152
  reviewRequests(first: 100) {
@@ -153,23 +154,23 @@ reviewRequests(first: 100) {
153
154
  ${!e||j(e,"AS_CODE_OWNER")?"asCodeOwner":""}
154
155
  requestedReviewer {
155
156
  ... on User {
156
- ${U(!1,t)}
157
+ ${G(!1,t)}
157
158
  }
158
159
  }
159
160
  }
160
161
  }
161
- ${!e||j(e,"LATEST_REVIEWS")?Ds(t):""}
162
+ ${!e||j(e,"LATEST_REVIEWS")?Ls(t):""}
162
163
  additions
163
164
  deletions
164
165
  changedFiles
165
166
  mergeable
166
167
  mergeStateStatus
167
168
  milestone {
168
- ${Se}
169
+ ${Ce}
169
170
  }
170
171
  labels(first: 100) {
171
172
  nodes {
172
- ${Ce}
173
+ ${De}
173
174
  }
174
175
  }
175
176
  ${!e||j(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
@@ -179,13 +180,13 @@ ${!t||j(t,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
179
180
  title
180
181
  author {
181
182
  ... on User {
182
- ${U(!1,s)}
183
+ ${G(!1,s)}
183
184
  }
184
185
  ... on Bot {
185
- ${Pr(!1)}
186
+ ${vr(!1)}
186
187
  }
187
188
  ... on EnterpriseUserAccount {
188
- ${Pt(!1)}
189
+ ${vt(!1)}
189
190
  }
190
191
  }
191
192
  closedAt
@@ -209,19 +210,19 @@ comments {
209
210
  }
210
211
  assignees(first: 100) {
211
212
  nodes {
212
- ${U(!1,s)}
213
+ ${G(!1,s)}
213
214
  }
214
215
  }
215
216
  state
216
217
  milestone {
217
- ${Se}
218
+ ${Ce}
218
219
  }
219
220
  labels(first: 100) {
220
221
  nodes {
221
- ${Ce}
222
+ ${De}
222
223
  }
223
224
  }
224
- `,Ls={"-linked":"-linked",archived:"archived",assignee:"assignee",author:"author",base:"base",closed:"closed",commenter:"commenter",comments:"comments",created:"created",draft:"draft",head:"head",label:"label",language:"language",linked:"linked",in:"in",interactions:"interactions",involves:"involves",is:"is",mentions:"mentions",merged:"merged",milestone:"milestone",no:"no",org:"org",project:"project",reactions:"reactions",repo:"repo",review:"review","reviewed-by":"reviewed-by","review-requested":"review-requested",state:"state",status:"status",team:"team","team-review-requested":"team-review-requested",type:"type",updated:"updated",user:"user","user-review-requested":"user-review-requested"},$s=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),wt=s=>{let t=[];return(s.match($s)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];Ls[n]&&t.push(r)}}),t},vt=(s,t,e,r)=>{let n=s==="issue";return{query:`
225
+ `,$s={"-linked":"-linked",archived:"archived",assignee:"assignee",author:"author",base:"base",closed:"closed",commenter:"commenter",comments:"comments",created:"created",draft:"draft",head:"head",label:"label",language:"language",linked:"linked",in:"in",interactions:"interactions",involves:"involves",is:"is",mentions:"mentions",merged:"merged",milestone:"milestone",no:"no",org:"org",project:"project",reactions:"reactions",repo:"repo",review:"review","reviewed-by":"reviewed-by","review-requested":"review-requested",state:"state",status:"status",team:"team","team-review-requested":"team-review-requested",type:"type",updated:"updated",user:"user","user-review-requested":"user-review-requested"},Us=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),qt=s=>{let t=[];return(s.match(Us)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];$s[n]&&t.push(r)}}),t},Et=(s,t,e,r)=>{let n=s==="issue";return{query:`
225
226
  query SearchIssuesOrPullRequests($query: String! $after: String) {
226
227
  search(type:ISSUE query:$query first: ${r.maxPageSize} after:$after) {
227
228
  pageInfo {
@@ -230,18 +231,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
230
231
  }
231
232
  nodes {
232
233
  ... on ${n?"Issue":"PullRequest"} {
233
- ${n?As(r.supportsEmail,r.enterpriseVersion??null):De(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
234
+ ${n?As(r.supportsEmail,r.enterpriseVersion??null):Le(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
234
235
  }
235
236
  }
236
237
  }
237
- }`,variables:{query:`is:${s} is:open ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},Us="Field 'isDraft' doesn't exist on type 'PullRequest'",Ae=(s=[])=>s.some(t=>t?.message===Us),Gs=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Ts=`
238
+ }`,variables:{query:`is:${s} is:open ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},Gs="Field 'isDraft' doesn't exist on type 'PullRequest'",Ae=(s=[])=>s.some(t=>t?.message===Gs),Ts=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,Os=`
238
239
  \
239
- +`,wr=(s,t,e,r)=>{let n=Gs.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(Ts,`
240
+ +`,qr=(s,t,e,r)=>{let n=Ts.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(Os,`
240
241
  +`).split(`
241
- `).slice(1),u=o-1,l=i-1,c=a.map(g=>{let m,y;switch(g[0]){case"-":{m="DELETED",u+=1,y=`${g.slice(1)}
242
+ `).slice(1),u=o-1,l=i-1,d=a.map(g=>{let m,y;switch(g[0]){case"-":{m="DELETED",u+=1,y=`${g.slice(1)}
242
243
  `;break}case"+":{m="ADDED",l+=1,y=`${g.slice(1)}
243
244
  `;break}default:m="UNMODIFIED",l+=1,u+=1,y=`${g}
244
- `}return{line:y,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),p=e,d=t;if(p!==null&&d!==null&&r!==null&&p<d){let g=0,m=c.length,y=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let R=0;R<c.length;R++){let pe=c[R][y];pe===p?g=R:pe===d&&(m=R)}c=c.slice(g,m+1)}return c};var Et=`
245
+ `}return{line:y,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),p=e,c=t;if(p!==null&&c!==null&&r!==null&&p<c){let g=0,m=d.length,y=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let R=0;R<d.length;R++){let K=d[R][y];K===p?g=R:K===c&&(m=R)}d=d.slice(g,m+1)}return d};var St=`
245
246
  id
246
247
  databaseId
247
248
  owner {
@@ -254,10 +255,10 @@ defaultBranchRef {
254
255
  name
255
256
  }
256
257
  viewerPermission
257
- `,Ct={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},Os={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},ks={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},xs={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Ns={OPEN:"OPEN",CLOSED:"CLOSED"},_s=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Dt=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Bs=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),qt=s=>({id:s.databaseId.toString(),graphQLId:s.id,namespace:s.owner.login,name:s.name,webUrl:s.url,httpsUrl:s.url.endsWith(".git")?s.url:`${s.url}.git`,sshUrl:s.sshUrl,defaultBranch:s.defaultBranchRef,permissions:Bs(s.viewerPermission)}),Qs=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),vr=s=>({id:s.id.toString(),graphQLId:s.node_id,namespace:s.owner.login,name:s.name,webUrl:s.html_url,httpsUrl:s.clone_url,sshUrl:s.ssh_url,defaultBranch:{name:s.default_branch},permissions:Qs(s.permissions)}),js=s=>({path:s.path,isDirectory:s.type==="tree"}),Fs={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},zs={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},k=(s,t=zs)=>{let e={};return t.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),t.graphQLId&&(e.graphQLId=s.id),t.name&&(e.name=s.name??s.login),t.username&&(e.username=s.login),t.email&&(e.email=s.email??null),t.avatarUrl&&(e.avatarUrl=s.avatarUrl),t.url&&(e.url=s.url),e},Ms=(s,t)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return s!=="COMPLETED"?e[s]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[t]},Ws=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],St=s=>{let t=null;s.author?t=s.author:t=Ct;let e=(s.reviewRequests?.nodes||[]).filter(C).filter(i=>!i.asCodeOwner),r=s.headRepository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=s.repository?.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:k(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(C).map(i=>{let a=Ct;return i.author&&i.author.__typename&&(a=i.author),{reviewer:k(a),state:Os[i.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,number:s.number,state:Fs[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?k(t):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:s.repository.sshUrl}},headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(C)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(C).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Ws(i.state),startedAt:new Date(i.createdAt),stage:null,url:i.targetUrl}:{completedAt:i.completedAt?new Date(i.completedAt):null,description:null,name:i.name,state:Ms(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:s.headRef?{name:s.headRef.name,oid:s.headRef.target?.oid??null}:null,baseRef:s.baseRef?{name:s.baseRef.name,oid:s.baseRef.target?.oid??null}:null,url:s.url,updatedDate:new Date(s.updatedAt),closedDate:s.closedAt?new Date(s.closedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees.nodes?s.assignees.nodes.filter(C).map(i=>k(i)):null,reviews:o,reviewDecision:_(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:xs[s.mergeStateStatus]??ks[s.mergeable],milestone:s.milestone?At(s.milestone):null,labels:s.labels?.nodes?.filter(C).map(Dt)??[],permissions:{canMerge:_s.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Hs=s=>{let{comments:t,isOutdated:e,isResolved:r,originalLine:n,originalStartLine:o,startDiffSide:i}=s,a=t.nodes?.[0];if(!a)return null;let{author:u,body:l,databaseId:c,fullDatabaseId:p,id:d,path:g,publishedAt:m,url:y}=a;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:m?new Date(m):null,diffLines:wr(a.diffHunk,n,o,i),id:p??c.toString(),isOutdated:e,isResolved:r,graphQLId:d,filename:g,replies:t.nodes?.filter(C).slice(1).map(Js)??[],url:y}},Js=s=>({author:s.author?{avatarUrl:s.author.avatarUrl,email:null,name:s.author.login}:null,body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId.toString(),url:s.url}),Vs=s=>{let t=null;return s.author?t=s.author:t=Ct,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?k(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:Ns[s.state],color:null},type:null,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login}},url:s.url,updatedDate:new Date(s.updatedAt),assignees:s.assignees.nodes?.filter(C).map(e=>k(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?At(s.milestone):null,labels:s.labels?.nodes?.filter(C).map(Dt)??[]}},At=s=>({id:s.number.toString(),graphQLId:s.id.toString(),number:s.number,title:s.title,description:s.description,isOpen:s.state=="OPEN",url:s.url,startDate:null,dueDate:s.dueOn?new Date(s.dueOn):null}),se=class extends ${constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let r=e.token||this.config.token;if(!r)return[];let n=this._scopesCache[r];if(!n){let i=(await I(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[r]=n}return n}async getEnterpriseVersion(e){let r=e.baseUrl||this.config.baseUrl;if(!r)return null;let n=this._enterpriseVersionsCache[r];if(!n){let o=await this.config.request({url:`${re(this.config,e)}/meta`,headers:h(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[r]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,r,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(qe)?e:r?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(r)}`:""}async getCurrentUser(e={},r={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=dr(e.fields),o=await this.getScopes(r),i=await I(this.config,{query:`
258
+ `,Lt={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},ks={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},xs={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Ns={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},_s={OPEN:"OPEN",CLOSED:"CLOSED"},Bs=["ADMIN","MAINTAIN","TRIAGE","WRITE"],At=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Qs=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Ct=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:Qs(s.viewerPermission)}),js=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),Er=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:js(s.permissions)}),Fs=s=>({path:s.path,isDirectory:s.type==="tree"}),zs={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Ms={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},k=(s,t=Ms)=>{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},Ws=(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]},Hs=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],Dt=s=>{let t=null;s.author?t=s.author:t=Lt;let e=(s.reviewRequests?.nodes||[]).filter(D).filter(i=>!i.asCodeOwner),r=s.headRepository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=s.repository?.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:k(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(D).map(i=>{let a=Lt;return i.author&&i.author.__typename&&(a=i.author),{reviewer:k(a),state:ks[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:zs[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?k(t):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:s.repository.sshUrl}},headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(D)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(D).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Hs(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:Ws(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(D).map(i=>k(i)):null,reviews:o,reviewDecision:_(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:Ns[s.mergeStateStatus]??xs[s.mergeable],milestone:s.milestone?$t(s.milestone):null,labels:s.labels?.nodes?.filter(D).map(At)??[],permissions:{canMerge:Bs.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Js=s=>{let{comments:t,isOutdated:e,isResolved:r,line:n,startLine:o,diffSide:i,originalLine:a,originalStartLine:u,startDiffSide:l}=s,d=t.nodes?.[0];if(!d)return null;let{author:p,body:c,databaseId:g,fullDatabaseId:m,id:y,path:R,publishedAt:S,url:K}=d,gt=n??a,Ie=o??u,v=i??l;return{author:p?{avatarUrl:p.avatarUrl,email:null,name:p.login}:null,body:c,createdAt:S?new Date(S):null,diffLines:qr(d.diffHunk,gt,Ie,v),id:m??g.toString(),isOutdated:e,isResolved:r,graphQLId:y,filename:R,replies:t.nodes?.filter(D).slice(1).map(Vs)??[],url:K,line:gt,startLine:Ie,side:v}},Vs=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}),Ks=s=>{let t=null;return s.author?t=s.author:t=Lt,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?k(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:_s[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(D).map(e=>k(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?$t(s.milestone):null,labels:s.labels?.nodes?.filter(D).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(Se)?e:r?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(r)}`:""}async getCurrentUser(e={},r={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=gr(e.fields),o=await this.getScopes(r),i=await I(this.config,{query:`
258
259
  query getCurrentUser {
259
260
  viewer {
260
- ${U(!1,F(o),n)}
261
+ ${G(!1,F(o),n)}
261
262
  }
262
263
  }
263
264
  `},r),a=i.body.data?.viewer;if(!a)throw new f("Current user not found.",i.body.errors);return{data:k(a,n)}}async getAccountsForRepo(e,r={}){let n=await this.getScopes(r),{repo:{namespace:o,name:i},cursor:a}=e,u=await I(this.config,{query:`
@@ -265,7 +266,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
265
266
  repository(owner: $owner, name: $name) {
266
267
  assignableUsers(first: $first, after: $cursor) {
267
268
  nodes {
268
- ${U(!1,F(n))}
269
+ ${G(!1,F(n))}
269
270
  }
270
271
  pageInfo {
271
272
  endCursor
@@ -274,7 +275,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
274
275
  }
275
276
  }
276
277
  }
277
- `,variables:{owner:o,name:i,cursor:a,first:v}},r);if(!u.body.data)throw new f("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(l=>k(l))??[]}}async getUserForCommit(e,r={}){let n=await I(this.config,{query:`
278
+ `,variables:{owner:o,name:i,cursor:a,first:q}},r);if(!u.body.data)throw new f("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(l=>k(l))??[]}}async getUserForCommit(e,r={}){let n=await I(this.config,{query:`
278
279
  query getUserForCommit(
279
280
  $owner: String!
280
281
  $name: String!
@@ -320,12 +321,12 @@ mutation createCommitOnBranch(
320
321
  }
321
322
  }
322
323
  }
323
- `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([c,p])=>({contents:Er.Base64.encode(p),path:c})),deletions:o.map(c=>({path:c}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},r);if(!l.body.data)throw new f("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,r={}){let n=await this.getScopes(r),o=await I(this.config,{query:`
324
+ `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([d,p])=>({contents:Sr.Base64.encode(p),path:d})),deletions:o.map(d=>({path:d}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},r);if(!l.body.data)throw new f("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,r={}){let n=await this.getScopes(r),o=await I(this.config,{query:`
324
325
  query getAccountForEmail($query: String! $avatarSize: Int) {
325
326
  search(query: $query, type: USER, first: 1) {
326
327
  nodes {
327
328
  ... on User {
328
- ${U(!0,F(n))}
329
+ ${G(!0,F(n))}
329
330
  }
330
331
  }
331
332
  }
@@ -333,7 +334,7 @@ query getAccountForEmail($query: String! $avatarSize: Int) {
333
334
  `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},r),i=o.body.data?.search?.nodes?.[0];if(!i)throw new f("Could not find user via email",o.body.errors);return{data:k({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getAccountForUsername(e,r={}){let n=await this.getScopes(r),o=await I(this.config,{query:`
334
335
  query getUserForUsername($login: String! $avatarSize: Int) {
335
336
  user(login: $login) {
336
- ${U(!0,F(n))}
337
+ ${G(!0,F(n))}
337
338
  }
338
339
  }
339
340
  `,variables:{login:e.username,avatarSize:e.avatarSize}},r),i=o.body.data?.user;if(!i)throw new f("Could not find user via username",o.body.errors);return{data:k({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await I(this.config,{query:`
@@ -355,7 +356,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
355
356
  }
356
357
  }
357
358
  }
358
- `,variables:{cursor:e.cursor,first:v}},r);if(!n.body.data)throw new f("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.body.data.viewer.organizations.pageInfo,data:o.map(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,r={}){let n=await I(this.config,{query:`
359
+ `,variables:{cursor:e.cursor,first:q}},r);if(!n.body.data)throw new f("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.body.data.viewer.organizations.pageInfo,data:o.map(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,r={}){let n=await I(this.config,{query:`
359
360
  query getOrgMember($cursor: String, $first: Int!, $login: String!) {
360
361
  viewer {
361
362
  organization(login: $login) {
@@ -365,28 +366,28 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
365
366
  hasNextPage
366
367
  }
367
368
  nodes {
368
- ${U(!1,!0)}
369
+ ${G(!1,!0)}
369
370
  }
370
371
  }
371
372
  }
372
373
  }
373
374
  }
374
- `,variables:{cursor:e.cursor,first:v,login:e.org}},r);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new f("Could not read the members of the organization",n.body.errors);let o=n.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:n.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:n.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>k({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}))}}async getRepo(e,r={}){let n=await I(this.config,{query:`
375
+ `,variables:{cursor:e.cursor,first:q,login:e.org}},r);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new f("Could not read the members of the organization",n.body.errors);let o=n.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:n.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:n.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>k({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}))}}async getRepo(e,r={}){let n=await I(this.config,{query:`
375
376
  query getRepo($owner: String!, $name: String!) {
376
377
  repository(owner: $owner, name: $name) {
377
- ${Et}
378
+ ${St}
378
379
  }
379
380
  }
380
- `,variables:{owner:e.namespace,name:e.name}},r);if(!n.body.data?.repository)throw new f(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:qt(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},c)=>`
381
- getRepo_${c}: repository(owner: "${u}", name: "${l}") {
382
- ${Et}
381
+ `,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:Ct(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},d)=>`
382
+ getRepo_${d}: repository(owner: "${u}", name: "${l}") {
383
+ ${St}
383
384
  }
384
385
  `).join(`
385
386
  `),o=await I(this.config,{query:`
386
387
  query batchGetRepos {
387
388
  ${n}
388
389
  }
389
- `},r);if(!o.body.data)throw new f("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let c=o.body.data[`getRepo_${l}`];c?i.push(qt(c)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,r,n,o){let i=[];for(let p=0;p<r;p++)i.push(n(e+p));let a=await Promise.all(i),u=[];for(let p of a){if(!p.body)throw new Error(p.statusText||"Unknown error");u=u.concat(p.body.map(d=>o(d)))}let l=a.every(p=>p.body.length===100),c=e+r;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?c:null}}}async getReposForCurrentUser(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${re(this.config,r)}/user/repos?${n.toString()}&page=${i}`,headers:{...h(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,vr)}async getReposForOrg(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${re(this.config,r)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...h(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,n,vr)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await I(this.config,{query:`
390
+ `},r);if(!o.body.data)throw new f("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(Ct(d)):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(c=>o(c)))}let l=a.every(p=>p.body.length===100),d=e+r;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?d: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,Er)}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,Er)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await I(this.config,{query:`
390
391
  query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
391
392
  search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
392
393
  pageInfo {
@@ -395,12 +396,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
395
396
  }
396
397
  nodes {
397
398
  ... on Repository {
398
- ${Et}
399
+ ${St}
399
400
  }
400
401
  }
401
402
  }
402
403
  }
403
- `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:v}},r);if(!n.body.data)throw new f("Could not fetch repos for usernames",n.body.errors);let o=n.body.data.search.nodes||[];return{pageInfo:n.body.data.search.pageInfo,data:o.map(qt)}}async getReposForOwners(e,r={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},r)}async getRefs(e,r,n={}){let o=await I(this.config,{query:`
404
+ `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:q}},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(Ct)}}async getReposForOwners(e,r={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},r)}async getRefs(e,r,n={}){let o=await I(this.config,{query:`
404
405
  query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
405
406
  repository(owner: $owner, name: $name) {
406
407
  refs(refPrefix: $refPrefix first: $first after: $cursor) {
@@ -421,7 +422,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
421
422
  }
422
423
  }
423
424
  }
424
- `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:v}},n),i=o.body.data?.repository;if(!i)throw new f("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,r={}){return this.getRefs("refs/heads/",e,r)}async getTags(e,r={}){return this.getRefs("refs/tags/",e,r)}async getBlame(e,r={}){let n=await I(this.config,{query:`
425
+ `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:q}},n),i=o.body.data?.repository;if(!i)throw new f("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,r={}){return this.getRefs("refs/heads/",e,r)}async getTags(e,r={}){return this.getRefs("refs/tags/",e,r)}async getBlame(e,r={}){let n=await I(this.config,{query:`
425
426
  query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
426
427
  repository(owner: $owner, name: $name) {
427
428
  object(expression: $ref) {
@@ -460,7 +461,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
460
461
  }
461
462
  }
462
463
  }
463
- `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},r),o=n.body.data?.repository;if(!o)throw new f("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new f("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new f("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,r={}){let n=await this.config.request({url:`${re(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...h(r.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async searchPullRequests(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=c=>{let p=c&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return vt("pr",p,e.cursor,{maxPageSize:e.maxPageSize??Rr,supportsEmail:i,supportsDrafts:c,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await I(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(C).map(St)||[]}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=await I(this.config,vt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??yr,enterpriseVersion:n}),r),{data:u}=a.body;if(!u)throw new f("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(C).map(Vs)||[]}}async getPullRequestsAssociatedWithUser(e,r={}){let n=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{n.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{n.push(`label:"${o}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async getPullRequestsForRepos(e,r={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:c,labelNames:p,maxPageSize:d}=e,g=wt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),c&&g.push(`mentions:${c}`),p&&p.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:d},r)}async getPullRequestForRepo(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=p=>({query:`query getPullRequest(
464
+ `,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=d=>{let p=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Et("pr",p,e.cursor,{maxPageSize:e.maxPageSize??br,supportsEmail:i,supportsDrafts:d,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await I(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(D).map(Dt)||[]}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=await I(this.config,Et("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(D).map(Ks)||[]}}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:d,labelNames:p,maxPageSize:c}=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}`),d&&g.push(`mentions:${d}`),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:c},r)}async getPullRequestForRepo(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=p=>({query:`query getPullRequest(
464
465
  $owner: String!
465
466
  $name: String!
466
467
  $number: Int!
@@ -470,18 +471,18 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
470
471
  name: $name
471
472
  ) {
472
473
  pullRequest(number: $number) {
473
- ${De(p,i,n)}
474
+ ${Le(p,i,n)}
474
475
  }
475
476
  }
476
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await I(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not fetch pull request by number",u.body.errors);let c=u.body.data?.repository.pullRequest;return{data:c?St(c):null}}async getPullRequestByGraphQLId(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=p=>({query:`query getPullRequest(
477
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await I(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not fetch pull request by number",u.body.errors);let d=u.body.data?.repository.pullRequest;return{data:d?Dt(d):null}}async getPullRequestByGraphQLId(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=F(o),a=p=>({query:`query getPullRequest(
477
478
  $graphQLId: ID!
478
479
  ) {
479
480
  node(id: $graphQLId) {
480
481
  ... on PullRequest {
481
- ${De(p,i,n)}
482
+ ${Le(p,i,n)}
482
483
  }
483
484
  }
484
- }`,variables:{graphQLId:e.graphQLId}}),u=await I(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not fetch pull request by id",u.body.errors);let c=u.body.data?.node;return{data:c?St(c):null}}async closePullRequest(e,r={}){let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
485
+ }`,variables:{graphQLId:e.graphQLId}}),u=await I(this.config,a(!0),r);u.body.errors&&Ae(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await I(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new f("Could not fetch pull request by id",u.body.errors);let d=u.body.data?.node;return{data:d?Dt(d):null}}async closePullRequest(e,r={}){let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
485
486
  closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
486
487
  pullRequest {
487
488
  id
@@ -540,7 +541,59 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
540
541
  id
541
542
  }
542
543
  }
543
- }`,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 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) {
544
+ }`,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(
545
+ $subjectId: ID!,
546
+ $body: String!
547
+ ) {
548
+ addComment(input: {
549
+ subjectId: $subjectId,
550
+ body: $body
551
+ }) {
552
+ commentEdge {
553
+ node {
554
+ id
555
+ }
556
+ }
557
+ }
558
+ }`,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 addReplyToReviewThread(e,r){let{threadId:n,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
559
+ $threadId: ID!,
560
+ $body: String!
561
+ ) {
562
+ addPullRequestReviewThreadReply(input: {
563
+ pullRequestReviewThreadId: $threadId,
564
+ body: $body
565
+ }) {
566
+ comment {
567
+ id
568
+ }
569
+ }
570
+ }`,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(
571
+ $pullRequestId: ID!,
572
+ $body: String!,
573
+ $path: String!,
574
+ $line: Int!,
575
+ $side: DiffSide
576
+ ) {
577
+ addPullRequestReview(input: {
578
+ pullRequestId: $pullRequestId,
579
+ event: COMMENT,
580
+ threads: [{
581
+ path: $path,
582
+ body: $body,
583
+ line: $line,
584
+ side: $side
585
+ }]
586
+ }) {
587
+ pullRequestReview {
588
+ id
589
+ comments(first: 1) {
590
+ nodes {
591
+ id
592
+ }
593
+ }
594
+ }
595
+ }
596
+ }`,d=await I(this.config,{query:l,variables:{pullRequestId:n.graphQLId,body:o,path:i,line:a,side:u}},r);if(!d.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new f("Could not add inline comment to pull request",d.body.errors);return d.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) {
544
597
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
545
598
  pullRequest {
546
599
  id
@@ -564,7 +617,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
564
617
  id
565
618
  }
566
619
  }
567
- }`,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!]!) {
620
+ }`,d=await I(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},r);if(!d.body.data?.requestReviews?.pullRequest?.id)throw new f("Could not set pull request reviewers",d.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 d of i){if(!d.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!n.find(p=>p.reviewer.graphQLId===d.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(d.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
568
621
  requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
569
622
  pullRequest {
570
623
  id
@@ -590,6 +643,9 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
590
643
  nodes {
591
644
  isOutdated
592
645
  isResolved
646
+ line
647
+ startLine
648
+ diffSide
593
649
  originalLine
594
650
  originalStartLine
595
651
  startDiffSide
@@ -628,13 +684,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
628
684
  }
629
685
  }
630
686
  }
631
- }`,l=await I(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),c=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(C).reduce((d,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return d;let m=g.comments.nodes[0].pullRequestReview,y=Hs(g);return y&&(d[m.id]||(d[m.id]=[]),d[m.id].push(y)),d},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(C).filter(d=>c[d.id]).map(d=>({author:d.author?{avatarUrl:d.author.avatarUrl,email:null,name:d.author.login}:null,body:d.body,createdAt:d.publishedAt?new Date(d.publishedAt):null,id:d.fullDatabaseId??d.databaseId.toString(),graphQLId:d.id,reviewComments:c[d.id],url:d.url}))??[]}}async getIssuesAssociatedWithUser(e,r={}){let[n,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(d=>{i.push(`label:"${d}"`)});let[a,u]=await Promise.all([n==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)]),l={},c=[],p=d=>{l[d.id]||(l[d.id]=!0,c.push(d))};return a?.data.forEach(p),u?.data.forEach(p),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:c}}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
687
+ }`,l=await I(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),d=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(D).reduce((c,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return c;let m=g.comments.nodes[0].pullRequestReview,y=Js(g);return y&&(c[m.id]||(c[m.id]=[]),c[m.id].push(y)),c},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(D).filter(c=>d[c.id]).map(c=>({author:c.author?{avatarUrl:c.author.avatarUrl,email:null,name:c.author.login}:null,body:c.body,createdAt:c.publishedAt?new Date(c.publishedAt):null,id:c.fullDatabaseId??c.databaseId.toString(),graphQLId:c.id,reviewComments:d[c.id],url:c.url}))??[]}}async getIssuesAssociatedWithUser(e,r={}){let[n,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(c=>{i.push(`label:"${c}"`)});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={},d=[],p=c=>{l[c.id]||(l[c.id]=!0,d.push(c))};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:d}}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!]) {
632
688
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
633
689
  pullRequest {
634
690
  id
635
691
  }
636
692
  }
637
- }`,a=await I(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},r);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new f("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=wt(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:c}=e;return e.repos.forEach(p=>{n.push(`repo:${p.namespace}/${p.name}`)}),i&&i.forEach(p=>{n.push(`assignee:${p}`)}),a&&n.push(`updated:<${a}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),c&&c.forEach(p=>{n.push(`label:"${p}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)}async closeIssueWithReason(e,r={}){let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
693
+ }`,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:d}=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}`),d&&d.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!) {
638
694
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
639
695
  issue {
640
696
  id
@@ -675,7 +731,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
675
731
  repository(owner: $owner, name: $name) {
676
732
  milestones(first: $first, after: $cursor) {
677
733
  nodes {
678
- ${Se}
734
+ ${Ce}
679
735
  }
680
736
  pageInfo {
681
737
  endCursor
@@ -684,12 +740,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
684
740
  }
685
741
  }
686
742
  }
687
- `,variables:{owner:n,name:o,cursor:i,first:v}},r);if(!a.body.data)throw new f("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(At)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await I(this.config,{query:`
743
+ `,variables:{owner:n,name:o,cursor:i,first:q}},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:`
688
744
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
689
745
  repository(owner: $owner, name: $name) {
690
746
  labels(first: $first, after: $cursor) {
691
747
  nodes {
692
- ${Ce}
748
+ ${De}
693
749
  }
694
750
  pageInfo {
695
751
  endCursor
@@ -698,7 +754,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
698
754
  }
699
755
  }
700
756
  }
701
- `,variables:{owner:n,name:o,cursor:i,first:v}},r);if(!a.body.data)throw new f("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(Dt)??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${re(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...h(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(js)}}};var Ks="https://gitlab.com/api/v4",Xs="https://gitlab.com/api/graphql",Lt=/\/api\/v\d+$/,qr=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},Le=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),qr(e),Lt.test(e)||(e=e+"/api/v4"),e):Ks},Ys=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),qr(e),Lt.test(e)&&(e=e.replace(Lt,"")),`${e}/api/graphql`):Xs},b=(s,t,e)=>{let r=h(e.token||s.token);return s.request({url:Ys(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},$e=s=>s?.map(t=>`"${t.message}"`).join(", ");var Ot=s=>s.split("/").slice(0,-1).join("/"),kt=s=>s.split("/").at(-1)??"",Ue=s=>({id:s.id.replace(ne,""),graphQLId:s.id,namespace:Ot(s.fullPath),name:kt(s.fullPath),webUrl:s.webUrl}),Sr=s=>({id:s.id.replace(ne,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:Ot(s.fullPath),name:kt(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Zs={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},en={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var tn="gid://gitlab/User/",ne="gid://gitlab/Project/",rn="gid://gitlab/MergeRequest/",sn="gid://gitlab/Issue/",nn="gid://gitlab/ProjectLabel/",on="gid://gitlab/Milestone/",an="gid://gitlab/Ci::Build/",xt=`
757
+ `,variables:{owner:n,name:o,cursor:i,first:q}},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(Fs)}}};var Xs="https://gitlab.com/api/v4",Ys="https://gitlab.com/api/graphql",Ut=/\/api\/v\d+$/,Cr=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.")},$e=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Cr(e),Ut.test(e)||(e=e+"/api/v4"),e):Xs},Zs=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Cr(e),Ut.test(e)&&(e=e.replace(Ut,"")),`${e}/api/graphql`):Ys},b=(s,t,e)=>{let r=h(e.token||s.token);return s.request({url:Zs(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},Ue=s=>s?.map(t=>`"${t.message}"`).join(", ");var xt=s=>s.split("/").slice(0,-1).join("/"),Nt=s=>s.split("/").at(-1)??"",Ge=s=>({id:s.id.replace(oe,""),graphQLId:s.id,namespace:xt(s.fullPath),name:Nt(s.fullPath),webUrl:s.webUrl}),Dr=s=>({id:s.id.replace(oe,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:xt(s.fullPath),name:Nt(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),en={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},tn={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var rn="gid://gitlab/User/",oe="gid://gitlab/Project/",sn="gid://gitlab/MergeRequest/",nn="gid://gitlab/Issue/",on="gid://gitlab/ProjectLabel/",an="gid://gitlab/Milestone/",un="gid://gitlab/Ci::Build/",_t=`
702
758
  description
703
759
  dueDate
704
760
  id
@@ -707,7 +763,7 @@ startDate
707
763
  state
708
764
  title
709
765
  webPath
710
- `,$t=`
766
+ `,Gt=`
711
767
  id
712
768
  fullPath
713
769
  webUrl
@@ -728,12 +784,12 @@ username
728
784
  publicEmail
729
785
  avatarUrl
730
786
  webUrl
731
- `,Nt=`
787
+ `,Bt=`
732
788
  color
733
789
  description
734
790
  id
735
791
  title
736
- `,Ut=`
792
+ `,Tt=`
737
793
  author {
738
794
  ${z}
739
795
  }
@@ -750,7 +806,7 @@ id
750
806
  iid
751
807
  labels {
752
808
  nodes {
753
- ${Nt}
809
+ ${Bt}
754
810
  }
755
811
  }
756
812
  state
@@ -761,9 +817,9 @@ upvotes
761
817
  userNotesCount
762
818
  webUrl
763
819
  milestone {
764
- ${xt}
820
+ ${_t}
765
821
  }
766
- `,un=`
822
+ `,ln=`
767
823
  stages {
768
824
  nodes {
769
825
  jobs {
@@ -779,7 +835,7 @@ stages {
779
835
  name
780
836
  }
781
837
  }
782
- `,Cr=(s,t,e)=>`
838
+ `,Lr=(s,t,e)=>`
783
839
  id
784
840
  state
785
841
  author {
@@ -799,6 +855,7 @@ draft
799
855
  userNotesCount
800
856
  upvotes
801
857
  title
858
+ description
802
859
  webUrl
803
860
  createdAt
804
861
  updatedAt
@@ -823,13 +880,13 @@ reviewers {
823
880
  mergeStatusEnum
824
881
  labels {
825
882
  nodes {
826
- ${Nt}
883
+ ${Bt}
827
884
  }
828
885
  }
829
886
  ${s?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
830
- ${t?`milestone { ${xt} }`:""}
831
- ${e?`headPipeline { ${un} }`:""}
832
- `,J=s=>`${s.namespace}/${s.name}`,ln=s=>`${s.namespace}/${s.name}`,pn=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),Gt=s=>({id:s.id.replace(ne,""),graphQLId:s.id,namespace:Ot(s.fullPath),name:kt(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:pn(s.userPermissions)}),dn=s=>({path:s.path,isDirectory:s.type==="tree"}),cn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Ar=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,M=(s,t,e)=>{let r=Ar(s.avatarUrl,t,e);return{id:s.id.replace(tn,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},_t=s=>({color:s.color,description:s.description,id:s.id.replace(nn,""),graphQLId:s.id,name:s.title}),gn=(s,t)=>s?s==="FAILED"&&t?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[s]:null,mn=(s,t,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:M(s,t,e),state:s.mergeRequestInteraction?.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},Dr=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>mn(i,r,n)):null;return{id:s.id.replace(rn,""),graphQLId:s.id,title:s.title,number:parseInt(s.iid,10),state:cn[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?M(s.author,r,n):null,createdDate:new Date(s.createdAt),isDraft:s.draft,repository:{id:t.id,graphQLId:t.graphQLId,name:t.name,owner:{login:t.namespace},remoteInfo:t.httpsUrl&&t.sshUrl?{cloneUrlHTTPS:t.httpsUrl,cloneUrlSSH:t.sshUrl}:null},headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:s.headPipeline?.stages?.nodes?.flatMap(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:gn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(an,"")}`}))??[])??[]},baseRef:{name:s.targetBranch,oid:s.diffRefs?.baseSha??null},headRef:{name:s.sourceBranch,oid:s.diffRefs?.headSha??null},url:s.webUrl,updatedDate:new Date(s.updatedAt),closedDate:s.mergedAt?new Date(s.mergedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees?.nodes?s.assignees.nodes.map(i=>M(i,r,n)):null,reviews:o,reviewDecision:_(o),additions:s.diffStatsSummary?.additions||0,deletions:s.diffStatsSummary?.deletions||0,fileCount:s.diffStatsSummary?.fileCount||0,commitCount:s.commitCount||0,mergeableState:en[s.mergeStatusEnum],milestone:s.milestone?Bt(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(_t)??[],permissions:null}},Tt=(s,t,e,r)=>({author:M(s.author,e,r),assignees:s.assignees.nodes.map(n=>M(n,e,r)),commentCount:s.userNotesCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:s.description,graphQLId:s.id,id:s.id.replace(sn,""),labels:s.labels?.nodes?.map(_t)??[],number:s.iid,repository:{id:t.id.replace(ne,""),graphQLId:t.id,name:t.name,owner:{login:t.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?Bt(s.milestone,t.webUrl):null}),Bt=(s,t)=>({id:s.id.replace(on,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${t}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),oe=class extends ${getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){let n=(await b(this.config,{query:`
887
+ ${t?`milestone { ${_t} }`:""}
888
+ ${e?`headPipeline { ${ln} }`:""}
889
+ `,J=s=>`${s.namespace}/${s.name}`,pn=s=>`${s.namespace}/${s.name}`,dn=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),Ot=s=>({id:s.id.replace(oe,""),graphQLId:s.id,namespace:xt(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:dn(s.userPermissions)}),cn=s=>({path:s.path,isDirectory:s.type==="tree"}),gn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},$r=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,M=(s,t,e)=>{let r=$r(s.avatarUrl,t,e);return{id:s.id.replace(rn,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},Qt=s=>({color:s.color,description:s.description,id:s.id.replace(on,""),graphQLId:s.id,name:s.title}),mn=(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,hn=(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"}},Ar=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>hn(i,r,n)):null;return{id:s.id.replace(sn,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:gn[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:mn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(un,"")}`}))??[])??[]},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:tn[s.mergeStatusEnum],milestone:s.milestone?jt(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(Qt)??[],permissions:null}},kt=(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(nn,""),labels:s.labels?.nodes?.map(Qt)??[],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(an,""),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:`
833
890
  query getCurrentUser {
834
891
  currentUser {
835
892
  ${z}
@@ -851,7 +908,7 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
851
908
  }
852
909
  }
853
910
  }
854
- `,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Ar(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(t,e={}){let n=(await b(this.config,{query:`
911
+ `,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=$r(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:`
855
912
  query getAccountForEmail($email: String!) {
856
913
  users(search: $email) {
857
914
  nodes {
@@ -889,19 +946,19 @@ query getAccountsForRepo(
889
946
  `,variables:{fullPath:`${r}/${n}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>M(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(t,e={}){let r=J(t),n=await b(this.config,{query:`
890
947
  query getRepo($fullPath: ID!) {
891
948
  project(fullPath: $fullPath) {
892
- ${$t}
949
+ ${Gt}
893
950
  }
894
951
  }
895
- `,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:Gt(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(J).map((u,l)=>`
952
+ `,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(J).map((u,l)=>`
896
953
  getRepo_${l}: project(fullPath: "${u}") {
897
- ${$t}
954
+ ${Gt}
898
955
  }
899
956
  `).join(`
900
957
  `),o=await b(this.config,{query:`
901
958
  query batchGetRepos {
902
959
  ${n}
903
960
  }
904
- `},e);if(!o.body.data)throw new Error($e(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let c=o.body.data[`getRepo_${l}`];c?i.push(Gt(c)):a.push({input:u})}),{data:i,errors:a}}async getRepos(t,e={}){let r=[];for(let i=0;i<t.length;i+=15)r.push(t.slice(i,i+15));return(await Promise.all(r.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(t,e={}){let r=await b(this.config,{query:`
961
+ `},e);if(!o.body.data)throw new Error(Ue(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(Ot(d)):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:`
905
962
  query getReposForCurrentUser($after: String) {
906
963
  projects(membership: true first: 100 after: $after) {
907
964
  pageInfo {
@@ -909,11 +966,11 @@ query getReposForCurrentUser($after: String) {
909
966
  hasNextPage
910
967
  }
911
968
  nodes {
912
- ${$t}
969
+ ${Gt}
913
970
  }
914
971
  }
915
972
  }
916
- `,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error($e(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(Gt)}}async getRefs(t,e,r={}){let n=J(e.repo),o=new URL(`${Le(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",v.toString());let i=await this.config.request({url:o.toString(),headers:h(r.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(u=>({name:u.name,commit:{oid:u.commit.id,authoredDate:new Date(u.commit.authored_date),committedDate:new Date(u.commit.committed_date)}}))}}async getBranches(t,e={}){return this.getRefs("branches",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getBlame(t,e={}){let r=J(t.repo),n=new URL(`${Le(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/blame`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:h(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(t,e={}){let r="";t.repo?.id?r=`projectId:"${t.repo.id}"`:t.repo?.namespace&&t.repo?.name&&(r=`projectPath:"${t.repo.namespace}/${t.repo.name}"`);let n=Zs[t.association],o=await b(this.config,{query:`
973
+ `,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(Ue(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(Ot)}}async getRefs(t,e,r={}){let n=J(e.repo),o=new URL(`${$e(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",q.toString());let i=await this.config.request({url:o.toString(),headers:h(r.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(u=>({name:u.name,commit:{oid:u.commit.id,authoredDate:new Date(u.commit.authored_date),committedDate:new Date(u.commit.committed_date)}}))}}async getBranches(t,e={}){return this.getRefs("branches",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getBlame(t,e={}){let r=J(t.repo),n=new URL(`${$e(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=en[t.association],o=await b(this.config,{query:`
917
974
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
918
975
  user(username: $username) {
919
976
  ${n}(state:opened first:100 after:$cursor labels: $labelNames${r?` ${r}`:""}) {
@@ -922,12 +979,12 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
922
979
  hasNextPage
923
980
  }
924
981
  nodes {
925
- ${Cr(!0,!0,!0)}
982
+ ${Lr(!0,!0,!0)}
926
983
  }
927
984
  }
928
985
  }
929
986
  }
930
- `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!o.body.data)throw new Error($e(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[n];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:i.nodes?.filter(a=>t.includeFromArchivedRepos||!a.project.archived).map(a=>Dr(a,Sr(a.project),Sr(a.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[]}}async getPullRequestsAssociatedWithUser(t,e={}){let[r,n,o]=t.cursor?.split(";")||[void 0,void 0,void 0],i=r?.split("-")||[],a=n?.split("-")||[],u=o?.split("-")||[],l=[],c=[],p=[],d=0;do{let E=t.repos&&t.repos[d];i[d]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:i[d],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...E&&{repo:E}},e)),a[d]==="null"?c.push(null):c.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[d],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...E&&{repo:E}},e)),u[d]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:u[d],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...E&&{repo:E}},e)),d++}while(d<(t.repos?.length||0));let g=[l,c,p].flat(),m=await Promise.all(g),y={},R=[],T=E=>{y[E.id]||(y[E.id]=!0,R.push(E))},pe=!1,os=m.map((E,ar)=>{let de="";return E&&E.data.forEach(T),E?.pageInfo.hasNextPage?(pe=!0,de+=`${E.pageInfo.endCursor||"null"}`):de+="null",t.repos?.length&&(ar+1)%t.repos.length!==0?de+="-":ar+1<m.length&&(de+=";"),de}).join("");return{pageInfo:{hasNextPage:pe,endCursor:os},data:R}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=t||{},u={},l=[],c=[],p=(d,g,m)=>{l.push(`$${d}: ${m}`),c.push(`${d}: $${d}`),u[d]=g};return e&&p("updatedBefore",e,"Time"),n&&p("authorUsername",n,"String"),o&&p("assigneeUsername",o[0],"String"),i&&p("labelName",i,"[String]"),r!=null&&p("draft",r,"Boolean"),a&&p("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:c}}async getPullRequestsForRepoBase(t,e={},r){let{cursor:n,repo:o}=t||{},i=J(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),c={fullPath:i,...a},p=await b(this.config,{query:`
987
+ `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!o.body.data)throw new Error(Ue(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[n];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:i.nodes?.filter(a=>t.includeFromArchivedRepos||!a.project.archived).map(a=>Ar(a,Dr(a.project),Dr(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=[],d=[],p=[],c=0;do{let v=t.repos&&t.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:i[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...v&&{repo:v}},e)),a[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...v&&{repo:v}},e)),u[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...v&&{repo:v}},e)),c++}while(c<(t.repos?.length||0));let g=[l,d,p].flat(),m=await Promise.all(g),y={},R=[],S=v=>{y[v.id]||(y[v.id]=!0,R.push(v))},K=!1,Ie=m.map((v,lr)=>{let de="";return v&&v.data.forEach(S),v?.pageInfo.hasNextPage?(K=!0,de+=`${v.pageInfo.endCursor||"null"}`):de+="null",t.repos?.length&&(lr+1)%t.repos.length!==0?de+="-":lr+1<m.length&&(de+=";"),de}).join("");return{pageInfo:{hasNextPage:K,endCursor:Ie},data:R}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=t||{},u={},l=[],d=[],p=(c,g,m)=>{l.push(`$${c}: ${m}`),d.push(`${c}: $${c}`),u[c]=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:d}}async getPullRequestsForRepoBase(t,e={},r){let{cursor:n,repo:o}=t||{},i=J(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(t),d={fullPath:i,...a},p=await b(this.config,{query:`
931
988
  query getPullRequestsForRepo(
932
989
  $fullPath: ID!
933
990
  $after: String
@@ -952,12 +1009,12 @@ query getPullRequestsForRepo(
952
1009
  hasNextPage
953
1010
  }
954
1011
  nodes {
955
- ${Cr(!1,!0,!0)}
1012
+ ${Lr(!1,!0,!0)}
956
1013
  }
957
1014
  }
958
1015
  }
959
1016
  }
960
- `,variables:{...c,after:n}},e),d=[],g=p.body.data?.project;if(!r&&g?.archived)return{pageInfo:null,data:[]};let m=Ue(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(R=>{d.push(Dr(R,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.pageInfo,data:d}}async getPullRequestsForRepo(t,e={}){return this.getPullRequestsForRepoBase(t,e,!1)}async getPullRequestsForRepos(t,e={}){let{repos:r,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=t;return{data:(await Promise.all(r.map(p=>this.getPullRequestsForRepoBase({repo:p,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,t.includeFromArchivedRepos??!1)))).flatMap(p=>p.data)}}async closePullRequest(t,e={}){let{pullRequest:r}=t,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
1017
+ `,variables:{...d,after:n}},e),c=[],g=p.body.data?.project;if(!r&&g?.archived)return{pageInfo:null,data:[]};let m=Ge(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(R=>{c.push(Ar(R,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.pageInfo,data:c}}async getPullRequestsForRepo(t,e={}){return this.getPullRequestsForRepoBase(t,e,!1)}async getPullRequestsForRepos(t,e={}){let{repos:r,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=t;return{data:(await Promise.all(r.map(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!) {
961
1018
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
962
1019
  errors,
963
1020
  mergeRequest {
@@ -1022,18 +1079,18 @@ query getPullRequestsForRepo(
1022
1079
  id
1023
1080
  }
1024
1081
  }
1025
- }`;if(!(await b(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(t,e={}){let r=ln(t),n=await b(this.config,{query:`
1082
+ }`;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=pn(t),n=await b(this.config,{query:`
1026
1083
  query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1027
1084
  project(fullPath: $projectId) {
1028
1085
  id
1029
1086
  fullPath
1030
1087
  webUrl
1031
1088
  issue(iid: $issueNumber) {
1032
- ${Ut}
1089
+ ${Tt}
1033
1090
  }
1034
1091
  }
1035
1092
  }
1036
- `,variables:{issueNumber:t.number,projectId:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${t.number} not found`);return{data:Tt(n.body.data.project.issue,Ue(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(t){let{updatedBefore:e,authorLogin:r,assigneeLogins:n,labelNames:o}=t||{},i={},a=[],u=[],l=(c,p,d)=>{a.push(`$${c}: ${d}`),u.push(`${c}: $${c}`),i[c]=p};return e&&l("updatedBefore",e,"Time"),r&&l("authorUsername",r,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(t,e={}){let{cursor:r,repo:n}=t||{},o=J(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:o,...i},c=`
1093
+ `,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,Ge(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(t){let{updatedBefore:e,authorLogin:r,assigneeLogins:n,labelNames:o}=t||{},i={},a=[],u=[],l=(d,p,c)=>{a.push(`$${d}: ${c}`),u.push(`${d}: $${d}`),i[d]=p};return e&&l("updatedBefore",e,"Time"),r&&l("authorUsername",r,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(t,e={}){let{cursor:r,repo:n}=t||{},o=J(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(t),l={fullPath:o,...i},d=`
1037
1094
  query GetIssuesFromProject(
1038
1095
  $fullPath: ID!
1039
1096
  $after: String
@@ -1053,7 +1110,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1053
1110
  ${u.length?u.join(" "):""}
1054
1111
  ) {
1055
1112
  nodes {
1056
- ${Ut}
1113
+ ${Tt}
1057
1114
  }
1058
1115
  pageInfo {
1059
1116
  endCursor
@@ -1061,7 +1118,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1061
1118
  }
1062
1119
  }
1063
1120
  }
1064
- }`,p=await b(this.config,{query:c,variables:{...l,after:r}},e),d=[],g=p.body.data?.project,m=Ue(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(R=>{d.push(Tt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:d.sort((R,T)=>(R.updatedDate||R.createdDate).getTime()-(T.updatedDate||T.createdDate).getTime())}}async getIssuesForRepos(t,e={}){let{cursor:r}=t||{},n=t.repoIds.map(g=>g.toString().startsWith(ne)?g:`${ne}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(t),u={projectIds:n,...o},l=`
1121
+ }`,p=await b(this.config,{query:d,variables:{...l,after:r}},e),c=[],g=p.body.data?.project,m=Ge(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(R=>{c.push(kt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:c.sort((R,S)=>(R.updatedDate||R.createdDate).getTime()-(S.updatedDate||S.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=`
1065
1122
  query GetIssuesFromProject(
1066
1123
  $projectIds: [ID!]
1067
1124
  $after: String
@@ -1087,12 +1144,12 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1087
1144
  ${a.length?a.join(" "):""}
1088
1145
  ) {
1089
1146
  nodes {
1090
- ${Ut}
1147
+ ${Tt}
1091
1148
  }
1092
1149
  }
1093
1150
  }
1094
1151
  }
1095
- }`,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=Ue(g);(g.issues?.nodes||[]).forEach(R=>p.push(Tt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:c.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:p.sort((g,m)=>(g.updatedDate||g.createdDate).getTime()-(m.updatedDate||m.createdDate).getTime())}}async setIssueState(t,e={}){let{issue:r,state:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1152
+ }`,d=await b(this.config,{query:l,variables:{...u,after:r}},e),p=[];return(d.body.data?.projects?.nodes||[]).forEach(g=>{if(!t.includeFromArchivedRepos&&g.archived)return;let m=Ge(g);(g.issues?.nodes||[]).forEach(R=>p.push(kt(R,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:d.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!) {
1096
1153
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1097
1154
  issue {
1098
1155
  id
@@ -1132,7 +1189,7 @@ query getLabelsForRepo(
1132
1189
  webUrl
1133
1190
  milestones(after: $after) {
1134
1191
  nodes {
1135
- ${xt}
1192
+ ${_t}
1136
1193
  }
1137
1194
  pageInfo {
1138
1195
  endCursor
@@ -1141,7 +1198,7 @@ query getLabelsForRepo(
1141
1198
  }
1142
1199
  }
1143
1200
  }
1144
- `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>Bt(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await b(this.config,{query:`
1201
+ `,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:`
1145
1202
  query getLabelsForRepo(
1146
1203
  $fullPath: ID!
1147
1204
  $after: String
@@ -1151,7 +1208,7 @@ query getLabelsForRepo(
1151
1208
  ) {
1152
1209
  labels(after: $after) {
1153
1210
  nodes {
1154
- ${Nt}
1211
+ ${Bt}
1155
1212
  }
1156
1213
  pageInfo {
1157
1214
  endCursor
@@ -1160,8 +1217,8 @@ query getLabelsForRepo(
1160
1217
  }
1161
1218
  }
1162
1219
  }
1163
- `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(_t)??[]}}async getTreeForRepo(t,e={}){let r=J(t.repo),n=new URL(t.cursor??`${Le(this.config,e)}/projects/${encodeURIComponent(r)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",t.branch);let o=await this.config.request({url:n.toString(),headers:h(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(dn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var hn="https://api.atlassian.com/ex/jira",Ge=100,Qt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Lr="/rest/api/2/search/jql",$r="/rest/api/2/search",jt=(s,t,e,r)=>{let n=s.fields.assignee,o=!r,i=(s.fields[t?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:s.id,commentCount:s.fields.comment.comments.length,number:s.key,title:s.fields.summary,url:e?`${e}/browse/${s.key}`:null,closedDate:null,createdDate:new Date(s.fields.created),author:Te(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[Te(n,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:r??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:yn(s.fields.status),statusTransitions:s.transitions?.map(fn)??[],components:s.fields.components?.map(In)??[],type:s.fields.issuetype.name,upvoteCount:s.fields.votes?.votes||0,labels:s.fields.labels?.map(a=>({color:null,description:null,id:null,name:a}))??[],sprints:i.map(bn),fixVersions:s.fields.fixVersions.map(Pn)}},fn=s=>{let t;switch(s.to.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:t}}},In=s=>({description:s.description??null,id:s.id,name:s.name}),Rn=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,Te=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:Rn(s,t,e)}),yn=s=>{let t;switch(s.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:t}},bn=s=>({id:s.id.toString(),name:s.name,isActive:s.state==="active",startDate:s.startDate?new Date(s.startDate):null,endDate:s.endDate?new Date(s.endDate):null,completedDate:s.completeDate?new Date(s.completeDate):null}),Pn=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),V=(s,t,e)=>e?`${t.baseUrl||hn}/${e}`:`${t?.baseUrl||s.baseUrl}`,Oe=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${V(s,e,r)}/rest/api/2/field`,headers:h(e.token||s.token)})).body},ke=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${V(s,r,o)}/rest/api/2/issue/${n}?fields=${Qt.join(",")}&expand=transitions`,headers:h(r.token||s.token)});return{data:jt(a.body,i,e,o)}},xe=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1164
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(T=>u.push(`labels = "${T}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,c=!o,p=c?$r:Lr,d=new URL(`${V(s,r,o)}${p}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",Ge.toString()),d.searchParams.set("fields",Qt.join(",")),d.searchParams.set("expand","transitions"),n&&(c?d.searchParams.set("startAt",n):d.searchParams.set("nextPageToken",n));let g=await s.request({url:d.toString(),headers:h(r.token||s.token)}),m=g.body.issues.map(T=>jt(T,a,e,o)),y=!1,R="";return c?(y=m.length==Ge,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},Ur=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=[...Qt],l=a?.Sprint;l&&u.push(l);let c=!o,p=c?$r:Lr,d=new URL(`${V(s,r,o)}${p}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",Ge.toString()),d.searchParams.set("fields",u.join(",")),d.searchParams.set("expand","transitions"),n&&(c?d.searchParams.set("startAt",n):d.searchParams.set("nextPageToken",n));let g=await s.request({url:d.toString(),headers:h(r.token||s.token)}),m=g.body.issues.map(T=>jt(T,a,e,o)),y=!1,R="";return c?(y=m.length==Ge,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},Ne=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:c,fields:p}=t||{},d=[`project = "${l}"`,"statusCategory != Done"];return o&&d.push(`creator in ("${o}")`),n&&n.length!==0&&d.push(`assignee in ("${n.join('", "')}")`),i&&d.push(`comment ~ "${i}"`),a&&a.forEach(g=>d.push(`labels = "${g}"`)),Ur(s,{resourceId:c,jql:d,cursor:u,fields:p},e,r)},_e=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:c,fields:p}=t||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),Ur(s,{resourceId:c,jql:g,fields:p,cursor:u},e,r)},Be=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${V(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...h(e.token||s.token),"Content-Type":"application/json"}})},Qe=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${V(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...h(e.token||s.token),"Content-Type":"application/json"}})},je=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${V(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...h(e.token||s.token),"Content-Type":"application/json"}})},Fe=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${V(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:h(e.token||s.token)})).body}};var he="https://api.atlassian.com/ex/jira",Ft=100,ie=class extends O{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Oe(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||he}/${e.resourceId}/rest/api/2/myself`,headers:h(r.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:h(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||he}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Ft.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:h(r.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,r={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await cr(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},r))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||he}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Ft.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:h(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(c=>c.accountType!=="app"&&c.active).map(c=>Te(c,a,!1))}}async getComponentsForJiraProject(e,r={}){return await Fe(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await ke(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Ne(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await _e(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await xe(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await je(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${r.baseUrl||he}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...h(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await Qe(this.config,e,r)}async setIssueLabels(e,r={}){await Be(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||he}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Ft.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:h(r.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var ae=class extends ${constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await Oe(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:h(e?.token||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:h(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await ke(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Ne(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await _e(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await xe(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await je(this.config,e,r)}async setIssueLabels(e,r={}){await Be(this.config,e,r)}async setIssueComponents(e,r={}){await Qe(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:h(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await Fe(this.config,e,r)}};var Mt=100,ze=class{constructor(){this.set=new Set;this.arr=[]}push(...t){let e=t.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}},W=async(s,t,e,r)=>{let n=t.token||s.token;if(!n)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},zt=s=>s?s instanceof Date?s:new Date(s):null,wn=`
1220
+ `,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(Qt)??[]}}async getTreeForRepo(t,e={}){let r=J(t.repo),n=new URL(t.cursor??`${$e(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(cn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}};var fn="https://api.atlassian.com/ex/jira",Te=100,Ft=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Ur="/rest/api/2/search/jql",Gr="/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:Oe(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[Oe(n,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:r??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:bn(s.fields.status),statusTransitions:s.transitions?.map(In)??[],components:s.fields.components?.map(Rn)??[],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(Pn),fixVersions:s.fields.fixVersions.map(wn)}},In=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}}},Rn=s=>({description:s.description??null,id:s.id,name:s.name}),yn=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,Oe=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:yn(s,t,e)}),bn=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}},Pn=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}),wn=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),V=(s,t,e)=>e?`${t.baseUrl||fn}/${e}`:`${t?.baseUrl||s.baseUrl}`,ke=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${V(s,e,r)}/rest/api/2/field`,headers:h(e.token||s.token)})).body},xe=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${V(s,r,o)}/rest/api/2/issue/${n}?fields=${Ft.join(",")}&expand=transitions`,headers:h(r.token||s.token)});return{data:zt(a.body,i,e,o)}},Ne=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1221
+ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(S=>u.push(`labels = "${S}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,d=!o,p=d?Gr:Ur,c=new URL(`${V(s,r,o)}${p}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",Te.toString()),c.searchParams.set("fields",Ft.join(",")),c.searchParams.set("expand","transitions"),n&&(d?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:h(r.token||s.token)}),m=g.body.issues.map(S=>zt(S,a,e,o)),y=!1,R="";return d?(y=m.length==Te,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},Tr=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 d=!o,p=d?Gr:Ur,c=new URL(`${V(s,r,o)}${p}`);c.searchParams.set("jql",i.join(" AND ")),c.searchParams.set("maxResults",Te.toString()),c.searchParams.set("fields",u.join(",")),c.searchParams.set("expand","transitions"),n&&(d?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:h(r.token||s.token)}),m=g.body.issues.map(S=>zt(S,a,e,o)),y=!1,R="";return d?(y=m.length==Te,R=(parseInt(n??"0",10)+m.length).toString()):(y=!!g.body.nextPageToken,R=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:y,endCursor:R}}},_e=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:d,fields:p}=t||{},c=[`project = "${l}"`,"statusCategory != Done"];return o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(g=>c.push(`labels = "${g}"`)),Tr(s,{resourceId:d,jql:c,cursor:u,fields:p},e,r)},Be=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:d,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}"`)),Tr(s,{resourceId:d,jql:g,fields:p,cursor:u},e,r)},Qe=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${V(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...h(e.token||s.token),"Content-Type":"application/json"}})},je=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${V(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...h(e.token||s.token),"Content-Type":"application/json"}})},Fe=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${V(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...h(e.token||s.token),"Content-Type":"application/json"}})},ze=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${V(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:h(e.token||s.token)})).body}};var he="https://api.atlassian.com/ex/jira",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 ke(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||he}/${e.resourceId}/rest/api/2/myself`,headers:h(r.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:h(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||he}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",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||he}/${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(d=>d.accountType!=="app"&&d.active).map(d=>Oe(d,a,!1))}}async getComponentsForJiraProject(e,r={}){return await ze(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await xe(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await _e(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Be(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await Ne(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await Fe(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${r.baseUrl||he}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...h(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await je(this.config,e,r)}async setIssueLabels(e,r={}){await Qe(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||he}/${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 ke(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.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 xe(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await _e(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Be(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await Ne(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await Fe(this.config,e,r)}async setIssueLabels(e,r={}){await Qe(this.config,e,r)}async setIssueComponents(e,r={}){await je(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.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 ze(this.config,e,r)}};var Ht=100,Me=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,vn=`
1165
1222
  id
1166
1223
  name
1167
1224
  description
@@ -1169,11 +1226,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1169
1226
  startDate
1170
1227
  targetDate
1171
1228
  url
1172
- `,Gr=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:zt(s.startDate),targetDate:zt(s.targetDate),url:s.url}),Tr=async(s,t,e)=>{let r=`
1229
+ `,Or=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}),kr=async(s,t,e)=>{let r=`
1173
1230
  query GetProjects($first: Int!, $after: String) {
1174
1231
  projects(first: $first, after: $after) {
1175
1232
  nodes {
1176
- ${wn}
1233
+ ${vn}
1177
1234
  }
1178
1235
  pageInfo {
1179
1236
  hasNextPage
@@ -1181,7 +1238,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1181
1238
  }
1182
1239
  }
1183
1240
  }
1184
- `;return(await W(s,t,r,{first:Mt,after:e})).projects},vn=`
1241
+ `;return(await W(s,t,r,{first:Ht,after:e})).projects},qn=`
1185
1242
  id
1186
1243
  name
1187
1244
  number
@@ -1189,11 +1246,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1189
1246
  startsAt
1190
1247
  endsAt
1191
1248
  completedAt
1192
- `,Or=s=>({id:s.id,name:s.name??`Cycle ${s.number}`,number:s.number,description:s.description??null,startsAt:new Date(s.startsAt),endsAt:new Date(s.endsAt),completedAt:zt(s.completedAt),url:""}),kr=async(s,t,e)=>{let r=`
1249
+ `,xr=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:""}),Nr=async(s,t,e)=>{let r=`
1193
1250
  query GetCycles($first: Int!, $after: String) {
1194
1251
  cycles(first: $first, after: $after) {
1195
1252
  nodes {
1196
- ${vn}
1253
+ ${qn}
1197
1254
  }
1198
1255
  pageInfo {
1199
1256
  hasNextPage
@@ -1201,12 +1258,12 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1201
1258
  }
1202
1259
  }
1203
1260
  }
1204
- `;return(await W(s,t,r,{first:Mt,after:e})).cycles},En=`
1261
+ `;return(await W(s,t,r,{first:Ht,after:e})).cycles},En=`
1205
1262
  id
1206
1263
  name
1207
1264
  color
1208
1265
  description
1209
- `,xr=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),Nr=async(s,t,e)=>{let r=`
1266
+ `,_r=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),Br=async(s,t,e)=>{let r=`
1210
1267
  query GetLabels($first: Int!, $after: String) {
1211
1268
  projectLabels(first: $first, after: $after) {
1212
1269
  nodes {
@@ -1218,36 +1275,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1218
1275
  }
1219
1276
  }
1220
1277
  }
1221
- `;return(await W(s,t,r,{first:Mt,after:e})).projectLabels};var fe=(i=>(i[i.None=0]="None",i[i.Assignee=1]="Assignee",i[i.Creator=2]="Creator",i[i.Mention=3]="Mention",i[i.MentionInDescription=4]="MentionInDescription",i[i.MentionInComments=5]="MentionInComments",i))(fe||{});function _r(s,t){return s?`${fe[s]}:${t||""}`:t??null}function Br(s){if(!s)return{category:0};let[t,e]=s.split(":");return t in fe?{category:fe[t],cursor:e||void 0}:{category:0,cursor:s}}var Qr=100;function We(s){return s?s instanceof Date?s:new Date(s):null}var zr=`
1278
+ `;return(await W(s,t,r,{first:Ht,after:e})).projectLabels};var fe=(i=>(i[i.None=0]="None",i[i.Assignee=1]="Assignee",i[i.Creator=2]="Creator",i[i.Mention=3]="Mention",i[i.MentionInDescription=4]="MentionInDescription",i[i.MentionInComments=5]="MentionInComments",i))(fe||{});function Qr(s,t){return s?`${fe[s]}:${t||""}`:t??null}function jr(s){if(!s)return{category:0};let[t,e]=s.split(":");return t in fe?{category:fe[t],cursor:e||void 0}:{category:0,cursor:s}}var Fr=100;function He(s){return s?s instanceof Date?s:new Date(s):null}var Wr=`
1222
1279
  id
1223
1280
  name
1224
1281
  key
1225
1282
  icon
1226
- `;function qn(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var jr=`
1283
+ `;function Sn(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var zr=`
1227
1284
  id
1228
1285
  name
1229
1286
  avatarUrl
1230
- `;function Fr(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var Sn=`
1287
+ `;function Mr(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var Cn=`
1231
1288
  id
1232
1289
  name
1233
- `;function Cn(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var Dn=`
1290
+ `;function Dn(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var Ln=`
1234
1291
  id
1235
1292
  sortOrder
1236
1293
  name
1237
1294
  description
1238
1295
  status
1239
1296
  targetDate
1240
- `;function An(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:We(s.targetDate)}:null}function Ln(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var $n=`
1297
+ `;function An(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:He(s.targetDate)}:null}function $n(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Un=`
1241
1298
  id
1242
1299
  name
1243
1300
  color
1244
1301
  type
1245
- `;function Un(s){return s?{id:s.id,name:s.name,color:s.color,category:Ln(s.type)}:null}var Ht=`
1302
+ `;function Gn(s){return s?{id:s.id,name:s.name,color:s.color,category:$n(s.type)}:null}var Vt=`
1246
1303
  creator {
1247
- ${jr}
1304
+ ${zr}
1248
1305
  }
1249
1306
  assignee {
1250
- ${jr}
1307
+ ${zr}
1251
1308
  }
1252
1309
  archivedAt
1253
1310
  createdAt
@@ -1255,32 +1312,32 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1255
1312
  id
1256
1313
  identifier
1257
1314
  project {
1258
- ${Sn}
1315
+ ${Cn}
1259
1316
  }
1260
1317
  team {
1261
- ${zr}
1318
+ ${Wr}
1262
1319
  }
1263
1320
  state {
1264
- ${$n}
1321
+ ${Un}
1265
1322
  }
1266
1323
  title
1267
1324
  updatedAt
1268
1325
  url
1269
1326
  projectMilestone {
1270
- ${Dn}
1327
+ ${Ln}
1271
1328
  }
1272
- `;async function Wt(s){return{author:Fr(await s.creator),assignees:[Fr(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:We(s.archivedAt),createdDate:We(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:Cn(await s.project,await s.team),state:Un(await s.state),title:s.title,type:null,updatedDate:We(s.updatedAt),upvoteCount:null,url:s.url,milestone:An(await s.projectMilestone)}}var Me=`
1329
+ `;async function Jt(s){return{author:Mr(await s.creator),assignees:[Mr(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:He(s.archivedAt),createdDate:He(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:Dn(await s.project,await s.team),state:Gn(await s.state),title:s.title,type:null,updatedDate:He(s.updatedAt),upvoteCount:null,url:s.url,milestone:An(await s.projectMilestone)}}var We=`
1273
1330
  nodes {
1274
- ${Ht}
1331
+ ${Vt}
1275
1332
  }
1276
1333
  pageInfo {
1277
1334
  hasNextPage
1278
1335
  endCursor
1279
1336
  }
1280
- `,ue=class extends O{async fetchIssue(t,e){let r=`
1337
+ `,le=class extends O{async fetchIssue(t,e){let r=`
1281
1338
  query GetIssue($identifier: String!) {
1282
1339
  issue(id: $identifier) {
1283
- ${Ht}
1340
+ ${Vt}
1284
1341
  }
1285
1342
  }
1286
1343
  `;return(await W(this.config,e,r,{identifier:t})).issue}async fetchOrganization(t){let e=`
@@ -1295,7 +1352,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1295
1352
  query GetTeams {
1296
1353
  teams {
1297
1354
  nodes {
1298
- ${zr}
1355
+ ${Wr}
1299
1356
  }
1300
1357
  }
1301
1358
  }
@@ -1308,23 +1365,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1308
1365
  displayName
1309
1366
  }
1310
1367
  }
1311
- `;return(await W(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await Wt(r)}}async getLinearOrganization(t={}){let e=await this.fetchOrganization(t);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(t={}){return{data:(await this.fetchTeams(t)).nodes.map(qn)}}async getProjects(t={},e={}){let r=await Tr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Gr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await kr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Or),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await Nr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(xr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCurrentUser(t={}){return{data:await this.fetchViewer(t)}}async getIssuesForCurrentUser(t,e={}){let{cursor:r}=t,{category:n,cursor:o}=Br(r),i=await this.fetchViewer(e),a,u,l=new ze,c=async(p,d)=>{if(u||n>p)return;let g=await d(Math.max(Qr-l.length,1),n===p?o:void 0);if(!g)return;let m=await ht(g.nodes.map(Wt));l.push(...m),g.pageInfo.hasNextPage&&(a=p,u=g.pageInfo.endCursor)};return await c(1,async(p,d)=>(await this.rawRequest(e,`
1368
+ `;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(Sn)}}async getProjects(t={},e={}){let r=await kr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Or),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await Nr(this.config,e,t.cursor??void 0);return{data:r.nodes.map(xr),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await Br(this.config,e,t.cursor??void 0);return{data:r.nodes.map(_r),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}=jr(r),i=await this.fetchViewer(e),a,u,l=new Me,d=async(p,c)=>{if(u||n>p)return;let g=await c(Math.max(Fr-l.length,1),n===p?o:void 0);if(!g)return;let m=await It(g.nodes.map(Jt));l.push(...m),g.pageInfo.hasNextPage&&(a=p,u=g.pageInfo.endCursor)};return await d(1,async(p,c)=>(await this.rawRequest(e,`
1312
1369
  query GetAssignedIssues($first: Int!, $after: String) {
1313
1370
  viewer {
1314
1371
  issues: assignedIssues(first: $first, after: $after) {
1315
- ${Me}
1372
+ ${We}
1316
1373
  }
1317
1374
  }
1318
1375
  }
1319
- `,{first:p,after:d})).data?.viewer?.issues),await c(2,async(p,d)=>(await this.rawRequest(e,`
1376
+ `,{first:p,after:c})).data?.viewer?.issues),await d(2,async(p,c)=>(await this.rawRequest(e,`
1320
1377
  query GetCreatedIssues($first: Int!, $after: String) {
1321
1378
  viewer {
1322
1379
  issues: createdIssues(first: $first, after: $after) {
1323
- ${Me}
1380
+ ${We}
1324
1381
  }
1325
1382
  }
1326
1383
  }
1327
- `,{first:p,after:d})).data?.viewer?.issues),await c(4,async(p,d)=>(await this.rawRequest(e,`
1384
+ `,{first:p,after:c})).data?.viewer?.issues),await d(4,async(p,c)=>(await this.rawRequest(e,`
1328
1385
  query GetMentionedIssues($first: Int!, $after: String) {
1329
1386
  issues(
1330
1387
  first: $first
@@ -1345,10 +1402,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1345
1402
  }]
1346
1403
  }
1347
1404
  ){
1348
- ${Me}
1405
+ ${We}
1349
1406
  }
1350
1407
  }
1351
- `,{first:p,after:d})).data?.issues),await c(5,async(p,d)=>{let m=(await this.rawRequest(e,`
1408
+ `,{first:p,after:c})).data?.issues),await d(5,async(p,c)=>{let m=(await this.rawRequest(e,`
1352
1409
  query GetCommentedIssues($first: Int!, $after: String) {
1353
1410
  comments(
1354
1411
  first: $first
@@ -1371,7 +1428,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1371
1428
  ){
1372
1429
  nodes {
1373
1430
  issue {
1374
- ${Ht}
1431
+ ${Vt}
1375
1432
  }
1376
1433
  }
1377
1434
  pageInfo {
@@ -1380,10 +1437,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1380
1437
  }
1381
1438
  }
1382
1439
  }
1383
- `,{first:p,after:d})).data?.comments;return m?{nodes:m.nodes.map(R=>R.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:_r(a,u)}}}async getIssues(t,e={}){let{teams:r,projects:n,labels:o,cursor:i}=t,a=[];if(r&&r.length>0){let g=r.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(n&&n.length>0){let g=n.map(m=>`"${m}"`).join(", ");a.push(`project: { id: { in: [${g}] } }`)}if(o&&o.length>0){let g=o.map(m=>`"${m}"`).join(", ");a.push(`labels: { name: { in: [${g}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",l=`
1440
+ `,{first:p,after:c})).data?.comments;return m?{nodes:m.nodes.map(R=>R.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:Qr(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=`
1384
1441
  query GetIssues($first: Int!, $after: String) {
1385
1442
  issues(first: $first, after: $after${u?", ":""}${u}) {
1386
- ${Me}
1443
+ ${We}
1387
1444
  }
1388
1445
  }
1389
- `,p=(await this.rawRequest(e,l,{first:Qr,after:i})).data?.issues;return p?{data:await ht(p.nodes.map(Wt)),pageInfo:{hasNextPage:p.pageInfo.hasNextPage,endCursor:p.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var B="https://api.trello.com",Gn=1e3,Tn=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),On=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},le=class extends O{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||B}/1/members/me?key=${t.appKey}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||B}/1/members/me/boards?fields=name&key=${t.appKey}&token=${e.token||this.config.token}&filter=open`,headers:h(e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||B}/1/boards/${n}/lists?key=${r}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||B}/1/members/${n}/?key=${r}&token=${e.token||this.config.token}`});return{data:Tn(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||B}/1/boards/${n}/members?key=${r}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(d=>r.push(`label:"${d}"`));let c=`${i?`${i}`:""}${r.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||B}/1/search?key=${n}&query=${c}&cards_limit=${Gn}&token=${e.token||this.config.token}&card_members=true`,headers:h(e.token||this.config.token)})).body.cards.map(d=>On(d,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||B}/1/cards/${e.id}?key=${t}&token=${n.token||this.config.token}&${r}`,headers:h(n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:o}=t;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:o}=t,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(t,e={}){let{appKey:r,issue:n,labels:o}=t,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||B}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(i)}`,headers:h(e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(t,e={}){let{appKey:r,issue:n,archived:o}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||B}/1/cards/${n.id}?key=${r}&token=${e.token||this.config.token}&closed=${o}`,headers:h(e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||B}/1/boards/${n}/labels?key=${r}&token=${e.token||this.config.token}`,headers:h(e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var He={};x(He,{default:()=>kn});var kn={};var Je={};x(Je,{default:()=>xn});var xn={};var it={};x(it,{decode:()=>Jt,decodeV0:()=>Qn,encode:()=>Bn,validate:()=>_n});var A=(e=>(e.Zero="0",e.One="1",e))(A||{}),L=(e=>(e.PullRequest="pr",e.Issue="issue",e))(L||{}),D=(d=>(d.Azure="azure",d.AzureDevOpsServer="azureDevOpsServer",d.Github="github",d.GithubEnterprise="githubEnterprise",d.Gitlab="gitlab",d.GitlabSelfHosted="gitlabSelfHosted",d.Bitbucket="bitbucket",d.BitbucketServer="bitbucketServer",d.Jira="jira",d.JiraServer="jiraServer",d.Linear="linear",d.Trello="trello",d))(D||{});var Ve=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var Ke=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var Xe=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var Ye=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var Ze=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var et=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var tt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var rt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var st=class{constructor(){}validate(t){if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.projectId||!t.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider=="jira"?(e.push(""),e.push(t.resourceId)):(e.push(t.domain),e.push("")),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:t[4]==""?null:t[4],accountOrOrgId:null,organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var nt=class{constructor(){}validate(t){if(!t.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.accountOrOrgId||!t.projectId||!t.entityId)throw new Error("Missing required fields for Trello issue uniqueId");let e=[];return e.push("trello"),e.push("issue"),e.push("1"),e.push(""),e.push(t.accountOrOrgId),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:t[4],organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var ot=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new Ke:new Ve;case"bitbucket":case"bitbucketServer":return t==="pr"?new Ye:new Xe;case"github":case"githubEnterprise":return t==="pr"?new et:new Ze;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new rt:new tt;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new st;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new nt;default:throw new Error("unknown provider")}},Nn=s=>{if(!s.entityType)throw new Error("entityType is required");if(!s.provider)throw new Error("provider is required");if(!s.entityId)throw new Error("entityID is required")},_n=s=>{if(s.version==="0"){Nn(s);return}ot(s.provider,s.entityType).validate(s)},Bn=s=>ot(s.provider,s.entityType).encode(s),Jt=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return ot(t[0],t[1]).decode(t)},Qn=(s,t,e)=>{if(!e)throw new Error("entityID is required");try{let r=JSON.parse(e);if(!r||!r.length)throw new Error("Invalid pull request uniqueId");let n=[s,t,"0",...r];return ot(s,t).decode(n)}catch{return{provider:s,entityType:t,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var at={};x(at,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>Kr,CHANGES_REQUESTED_BUCKET_ID:()=>tr,CONFLICTS_ACTION_CATEGORY:()=>Jr,CONFLICTS_BUCKET_ID:()=>Zt,DRAFT_ACTION_CATEGORY:()=>Zr,DRAFT_BUCKET_ID:()=>nr,FAILING_CI_ACTION_CATEGORY:()=>Hr,FAILING_CI_BUCKET_ID:()=>Yt,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Vr,NEEDS_MY_REVIEW_BUCKET_ID:()=>er,OTHER_ACTION_CATEGORY:()=>es,OTHER_BUCKET_ID:()=>or,PINNED_BUCKET_ID:()=>Vt,READY_TO_MERGE_ACTION_CATEGORY:()=>Mr,READY_TO_MERGE_BUCKET_ID:()=>Kt,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>Xr,REVIEWER_COMMENTED_BUCKET_ID:()=>rr,SNOOZED_BUCKET_ID:()=>ir,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Wr,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Xt,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>Yr,WAITING_FOR_REVIEW_BUCKET_ID:()=>sr,getActionablePullRequests:()=>ts,groupPullRequestsByAssignee:()=>zn,groupPullRequestsByAuthor:()=>Mn,groupPullRequestsByGitKrakenTeam:()=>Vn,groupPullRequestsByRepo:()=>Fn,groupPullRequestsByReviewer:()=>Wn,groupPullRequestsByWorkspace:()=>Jn,groupPullRequestsIntoBuckets:()=>jn});var G=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Vt="pinned",Kt="readyToMerge",Xt="unassignedReviewers",Yt="failingCI",Zt="conflicts",er="needsMyReview",tr="changesRequested",rr="reviewerCommented",sr="waitingForReview",nr="draft",or="other",ir="snoozed",Mr="readyToMerge",Wr="unassignedReviewers",Hr="failingCI",Jr="conflicts",Vr="needsMyReview",Kr="changesRequested",Xr="reviewerCommented",Yr="waitingForReview",Zr="draft",es="other",ts=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:es,priority:1e3,viewer:{canMerge:!1,isAuthor:!1,isAssignee:!1,isReviewer:!1,shouldMerge:!1,shouldAssignReviewer:!1,waitingOnReviews:!1,shouldReview:!1},failingCI:!1,hasConflicts:!1,changeRequestReviewCount:0,codeSuggestionsCount:0,commentReviewCount:0,approvalReviewCount:0}};t&&(o.viewer.isAuthor=r.author?.id===t.id,o.viewer.isAssignee=r.assignees?.some(u=>u.id===t.id)??!1,o.viewer.isReviewer=r.reviews?.some(u=>u.reviewer.id===t.id)??!1),o.viewer.canMerge=r.permissions?.canMerge??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=r.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=r.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=r.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=r.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(u=>u.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(u=>u.type==="snooze")&&(o.viewer.snoozed=!0));let a=e?.codeSuggestionsCountByPrUuid?.[r.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!t||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&r.mergeableState==="MERGEABLE"&&(!r.reviewDecision||r.reviewDecision==="APPROVED")&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=Mr),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=Zr),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=Yr,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=Xr),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Hr),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=Jr),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=Kr),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=Wr,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=Vr,o.viewer.shouldReview=!0),o}),jn=(s,t,e)=>{let r={pinned:G(Vt,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:G(Kt,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:G(Xt,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:G(Yt,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:G(Zt,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:G(er,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:G(tr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:G(rr,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:G(sr,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:G(nr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:G(or,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:G(ir,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=ts(s,t,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){r[ir].pullRequests.push(i);return}a.viewer.pinned&&r[Vt].pullRequests.push(i),(!t||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(!i.reviewDecision||i.reviewDecision==="APPROVED")&&(r[Kt].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[Xt].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[Yt].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[Zt].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[er].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[tr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[rr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[sr].pullRequests.push(i),u=!1),a.isDraft&&(r[nr].pullRequests.push(i),u=!1),u&&r[or].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},Fn=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),X(t)},zn=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Ie(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),X(e)},Mn=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Ie(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),X(e)},Wn=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Ie(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),X(e)},Hn=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],Jn=(s,t)=>{let e="internal-no-workspace",r={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(t.length){let n=t.reduce((o,i)=>(Hn(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Jt(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,c=u.reduce((p,d)=>n[d]?p.concat(n[d]):p,[]);c?.length&&c.forEach(p=>{l=!0;let d=p.id;r[d]?r[d].pullRequests.push(o):r[d]={name:p.name,priority:0,pullRequests:[o],id:d,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return X(r)},Vn=(s,t,e,r)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(i=>{let a=!1,u=new Set;u.add(i.author?.id),i.assignees?.forEach(l=>u.add(l.id)),i.reviews?.forEach(l=>u.add(l.reviewer.id)),r.forEach(l=>{if(l.members?.some(p=>{let d=t[p.id]?.[e]?.providerID;return d&&u.has(d)})){a=!0;let p=l.id;o[p]?o[p].pullRequests.push(i):o[p]={name:l.name,priority:0,pullRequests:[i],id:p,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,X(o)};var ut={};x(ut,{getPullRequestRank:()=>Kn});var Kn=(s,t,e)=>{let r=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===t&&(n=i.state),i.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":i.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),s.author?.id===t?r+=1e3:s.assignees?.find(i=>i.id===t)?r+=900:n==="REVIEW_REQUESTED"?r+=800:e&&(r+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:o=="CHANGES_REQUESTED"&&(r+=70),r};var lt={};x(lt,{default:()=>Xn});var Xn={};var pt={};x(pt,{default:()=>Yn});var Yn={};var dt={};x(dt,{default:()=>Zn});var Zn={};var rs=s=>{let t={request:s?.request};return{azureDevOps:new Z({...t,...s?.azureDevOps}),bitbucket:new ee({...t,...s?.bitbucket}),bitbucketServer:new te({...t,...s?.bitbucketServer}),github:new se({...t,...s?.github}),gitlab:new oe({...t,...s?.gitlab}),jira:new ie({...t,...s?.jira}),jiraServer:new ae({...t,...s?.jiraServer}),linear:new ue({...t,...s?.linear}),trello:new le({...t,...s?.trello})}};var ss=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(ss||{});var ns=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(ns||{});var eo=rs;var to={azureDevOps:He,bitbucket:Je,bitbucketServer:we,github:ut,gitlab:lt,gitProvider:at,jira:pt,trello:dt,entityIdentifier:it};
1446
+ `,p=(await this.rawRequest(e,l,{first:Fr,after:i})).data?.issues;return p?{data:await It(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",Tn=1e3,On=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),kn=(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:On(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(c=>r.push(`label:"${c}"`));let d=`${i?`${i}`:""}${r.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||B}/1/search?key=${n}&query=${d}&cards_limit=${Tn}&token=${e.token||this.config.token}&card_members=true`,headers:h(e.token||this.config.token)})).body.cards.map(c=>kn(c,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 Je={};x(Je,{default:()=>xn});var xn={};var Ve={};x(Ve,{default:()=>Nn});var Nn={};var at={};x(at,{decode:()=>Kt,decodeV0:()=>jn,encode:()=>Qn,validate:()=>Bn});var A=(e=>(e.Zero="0",e.One="1",e))(A||{}),$=(e=>(e.PullRequest="pr",e.Issue="issue",e))($||{}),L=(c=>(c.Azure="azure",c.AzureDevOpsServer="azureDevOpsServer",c.Github="github",c.GithubEnterprise="githubEnterprise",c.Gitlab="gitlab",c.GitlabSelfHosted="gitlabSelfHosted",c.Bitbucket="bitbucket",c.BitbucketServer="bitbucketServer",c.Jira="jira",c.JiraServer="jiraServer",c.Linear="linear",c.Trello="trello",c))(L||{});var Ke=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.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 Xe=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 Ye=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 Ze=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 et=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github 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 tt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for 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 rt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab 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 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 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 nt=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 ot=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 it=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new Xe:new Ke;case"bitbucket":case"bitbucketServer":return t==="pr"?new Ze:new Ye;case"github":case"githubEnterprise":return t==="pr"?new tt:new et;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new st:new rt;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new nt;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new ot;default:throw new Error("unknown provider")}},_n=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")},Bn=s=>{if(s.version==="0"){_n(s);return}it(s.provider,s.entityType).validate(s)},Qn=s=>it(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 it(t[0],t[1]).decode(t)},jn=(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 it(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 ut={};x(ut,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>Yr,CHANGES_REQUESTED_BUCKET_ID:()=>sr,CONFLICTS_ACTION_CATEGORY:()=>Kr,CONFLICTS_BUCKET_ID:()=>tr,DRAFT_ACTION_CATEGORY:()=>ts,DRAFT_BUCKET_ID:()=>ir,FAILING_CI_ACTION_CATEGORY:()=>Vr,FAILING_CI_BUCKET_ID:()=>er,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Xr,NEEDS_MY_REVIEW_BUCKET_ID:()=>rr,OTHER_ACTION_CATEGORY:()=>rs,OTHER_BUCKET_ID:()=>ar,PINNED_BUCKET_ID:()=>Xt,READY_TO_MERGE_ACTION_CATEGORY:()=>Hr,READY_TO_MERGE_BUCKET_ID:()=>Yt,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>Zr,REVIEWER_COMMENTED_BUCKET_ID:()=>nr,SNOOZED_BUCKET_ID:()=>ur,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Jr,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Zt,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>es,WAITING_FOR_REVIEW_BUCKET_ID:()=>or,getActionablePullRequests:()=>ss,groupPullRequestsByAssignee:()=>Mn,groupPullRequestsByAuthor:()=>Wn,groupPullRequestsByGitKrakenTeam:()=>Kn,groupPullRequestsByRepo:()=>zn,groupPullRequestsByReviewer:()=>Hn,groupPullRequestsByWorkspace:()=>Vn,groupPullRequestsIntoBuckets:()=>Fn});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",Hr="readyToMerge",Jr="unassignedReviewers",Vr="failingCI",Kr="conflicts",Xr="needsMyReview",Yr="changesRequested",Zr="reviewerCommented",es="waitingForReview",ts="draft",rs="other",ss=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:rs,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=Hr),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=ts),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=es,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=Zr),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Vr),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=Kr),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=Yr),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=Jr,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=Xr,o.viewer.shouldReview=!0),o}),Fn=(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=ss(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},zn=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)},Mn=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Re(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Y(e)},Wn=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Re(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),Y(e)},Hn=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Re(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),Y(e)},Jn=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],Vn=(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)=>(Jn(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,d=u.reduce((p,c)=>n[c]?p.concat(n[c]):p,[]);d?.length&&d.forEach(p=>{l=!0;let c=p.id;r[c]?r[c].pullRequests.push(o):r[c]={name:p.name,priority:0,pullRequests:[o],id:c,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return Y(r)},Kn=(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 c=t[p.id]?.[e]?.providerID;return c&&u.has(c)})){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 lt={};x(lt,{getPullRequestRank:()=>Xn});var Xn=(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 pt={};x(pt,{default:()=>Yn});var Yn={};var dt={};x(dt,{default:()=>Zn});var Zn={};var ct={};x(ct,{default:()=>eo});var eo={};var ns=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 os=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(os||{});var is=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(is||{});var to=ns;var ro={azureDevOps:Je,bitbucket:Ve,bitbucketServer:ve,github:lt,gitlab:pt,gitProvider:ut,jira:dt,trello:ct,entityIdentifier:at};