@gitkraken/provider-apis 0.28.3 → 0.28.5

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.
@@ -1,4 +1,4 @@
1
- "use strict";var Wt=Object.create;var le=Object.defineProperty;var Ht=Object.getOwnPropertyDescriptor;var Jt=Object.getOwnPropertyNames;var Kt=Object.getPrototypeOf,Vt=Object.prototype.hasOwnProperty;var Xt=(r,n)=>{for(var e in n)le(r,e,{get:n[e],enumerable:!0})},gt=(r,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Jt(n))!Vt.call(r,s)&&s!==e&&le(r,s,{get:()=>n[s],enumerable:!(t=Ht(n,s))||t.enumerable});return r};var Zt=(r,n,e)=>(e=r!=null?Wt(Kt(r)):{},gt(n||!r||!r.__esModule?le(e,"default",{value:r,enumerable:!0}):e,r)),Yt=r=>gt(le({},"__esModule",{value:!0}),r);var ls={};Xt(ls,{AzureDevOps:()=>K,Bitbucket:()=>V,BitbucketServer:()=>X,EntityIdentifierProviderType:()=>Mt,EntityType:()=>jt,EntityVersion:()=>Bt,GitBuildStatusStage:()=>mt,GitBuildStatusState:()=>pe,GitDiffLineType:()=>xe,GitHub:()=>ee,GitHubIssueCloseReason:()=>zt,GitIssueState:()=>he,GitLab:()=>re,GitMergeStrategy:()=>J,GitPullRequestMergeableState:()=>H,GitPullRequestReviewState:()=>B,GitPullRequestState:()=>W,GraphQLErrors:()=>b,Jira:()=>se,JiraServer:()=>ne,PullRequestAsyncStatus:()=>_t,Trello:()=>oe,default:()=>us,isFetch:()=>de});module.exports=Yt(ls);var mt=(s=>(s.Build="build",s.Production="production",s.Staging="staging",s.Test="test",s))(mt||{}),pe=(p=>(p.ActionRequired="ACTION_REQUIRED",p.Cancelled="CANCELLED",p.Error="ERROR",p.Failed="FAILED",p.Pending="PENDING",p.Running="RUNNING",p.Skipped="SKIPPED",p.Success="SUCCESS",p.Warning="WARNING",p.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",p))(pe||{}),J=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(J||{}),W=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(W||{}),B=(s=>(s.Approved="APPROVED",s.ChangesRequested="CHANGES_REQUESTED",s.Commented="COMMENTED",s.ReviewRequested="REVIEW_REQUESTED",s))(B||{}),H=(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))(H||{}),xe=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(xe||{});var ht={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},x=r=>!r||r.length===0?null:r.reduce((n,e)=>ht[e.state]>ht[n]?e.state:n,"APPROVED");var C=100;var ft=Zt(require("node-fetch")),It=globalThis.fetch||ft.default;var er=async r=>{let n=r.headers.get("content-type")||"",e=null;if(n.startsWith("application/json")){let s=await r.text();e=s.trim().length>0?JSON.parse(s):null}else if(n.startsWith("text/")||n==="")e=await r.text();else if(n.startsWith("application/vnd.github.raw+json"))e=await r.arrayBuffer();else throw new Error(`Unsupported content-type: ${n}`);let t={body:e,headers:Object.fromEntries(r.headers.entries()),status:r.status,statusText:r.statusText};if(!r.ok){let s=new Error(r.statusText);throw Object.assign(s,{response:t}),s}return t},ke=r=>async({url:n,...e})=>{let t=await r(n,e);return er(t)};var de=(r,n=!1)=>r.name==="fetch"||n;var T=class{constructor(n){let e=(n==null?void 0:n.request)||It;this.config={...n,request:de(e,n==null?void 0:n.forceIsFetch)?ke(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&de(n.request,(n==null?void 0:n.forceIsFetch)??this.config.forceIsFetch)?ke(n.request):this.config.request}}},k=class extends T{};var R=(r,n)=>{let e={};return r&&(e.Authorization=`${n?"Basic":"Bearer"} ${r}`),e},Rt=r=>r?r.reduce((n,e)=>(n[e]=!0,n),{}):void 0,j=(r,n,e)=>!r||n.some(t=>r[t])?e:"",bt=async r=>{var s,o,a;let n=[],e=!0,t;for(;e;){let i=await r(t);n=n.concat(i.data),e=!!((s=i==null?void 0:i.pageInfo)!=null&&s.hasNextPage),t=((o=i==null?void 0:i.pageInfo)==null?void 0:o.endCursor)||((a=i==null?void 0:i.pageInfo)==null?void 0:a.nextPage)}return n};var S=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT),yt=r=>r.url.replace("/_apis/git/repositories/","/_git/").replace(`/${r.repository.project.id}/`,`/${encodeURIComponent(r.repository.project.name)}/`).replace(`/${r.repository.id}/`,`/${encodeURIComponent(r.repository.name)}/`).replace("/pullRequests/","/pullrequest/");var Pt="https://app.vssps.visualstudio.com/_apis",q="https://dev.azure.com",tr={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},rr={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},Ne=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),ge=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,sr=r=>{switch(r){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},ce=(r,n)=>{var s;let e=[],t=[];return n.reviewers.forEach(o=>{let a={reviewer:Ne(o),state:rr[o.vote??0]||"REVIEW_REQUESTED"};o.isRequired&&e.push(a),t.push(a)}),{id:n.pullRequestId.toString(),title:n.title,number:n.codeReviewId,state:tr[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:Ne(n.createdBy),createdDate:new Date(n.creationDate),updatedDate:new Date(n.closedDate||n.creationDate),closedDate:n.closedDate?new Date(n.closedDate):null,mergedDate:n.closedDate&&n.status==="completed"?new Date(n.closedDate):null,repository:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:ge(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:ge(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:yt(n),assignees:n.reviewers.map(Ne),reviews:t,reviewDecision:x(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:n.forkSource?{id:n.forkSource.repository.id,name:n.forkSource.repository.name,project:void 0,owner:{login:r},remoteInfo:null}:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:null},mergeableState:sr(n.mergeStatus),labels:((s=n.labels)==null?void 0:s.map(o=>({color:null,description:null,id:o.id,name:o.name})))??[],permissions:null}},wt=(r,n)=>({id:n.id,name:n.name,namespace:r,project:n.project.name,projectId:n.project.id,webUrl:n.webUrl,httpsUrl:n.remoteUrl,sshUrl:n.sshUrl,defaultBranch:n.defaultBranch?{name:ge(n.defaultBranch)}:null,permissions:null}),nr=(r,n,e,t)=>{var l,p,d,c,g,m;let s=e.fields,o=s["System.AssignedTo"],a=s["System.State"],i=s["System.WorkItemType"],u;return a&&i&&(u=(l=t[i])==null?void 0:l[a]),{id:e.id.toString(),number:e.id.toString(),title:s["System.Title"],commentCount:s["System.CommentCount"],author:{avatarUrl:((d=(p=s["System.CreatedBy"]._links)==null?void 0:p.avatar)==null?void 0:d.href)??null,email:null,id:s["System.CreatedBy"].id,name:s["System.CreatedBy"].uniqueName??null,username:s["System.CreatedBy"].displayName??null,url:null},closedDate:s["Microsoft.VSTS.Common.ClosedDate"]?new Date(s["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(s["System.CreatedDate"]),updatedDate:new Date(s["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:((g=(c=o._links)==null?void 0:c.avatar)==null?void 0:g.href)??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:s["System.Description"]??null,state:{name:(u==null?void 0:u.title)||a,color:null},type:s["System.WorkItemType"],repository:null,project:{namespace:r,name:n,resourceId:null,key:null,id:null},upvoteCount:0,labels:((m=e.fields["System.Tags"])==null?void 0:m.split(";").map(h=>({color:null,description:null,id:null,name:h.trim()})))??[]}},K=class extends T{async getCurrentUser(n={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let t=await this.config.request({url:`${Pt}/profile/profiles/me`,headers:S(this.config,e)});return{data:{id:t.body.id,name:t.body.displayName,username:t.body.displayName,email:t.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(n,e={}){let s=(await this.config.request({url:`${q}/${encodeURIComponent(n.namespace)}/_apis/ConnectionData`,headers:S(this.config,e)})).body.authorizedUser;if(s.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:s.id,name:s.providerDisplayName,username:s.providerDisplayName,email:s.properties.Account.$value,avatarUrl:null}}}async getUserForCommit(n,e={}){if(!n.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=(await this.config.request({url:`${q}/${encodeURIComponent(n.repo.namespace)}/${encodeURIComponent(n.repo.project)}/_apis/git/repositories/${encodeURIComponent(n.repo.name)}/commits/${n.oid}`,headers:S(this.config,e)})).body.author;return{data:{name:s.name,email:s.email,avatarUrl:s.imageUrl}}}async getOrgsForUser(n,e={}){return{data:(await this.config.request({url:`${Pt}/accounts?memberId=${n.userId}&api-version=6.0`,headers:S(this.config,e)})).body.value.map(s=>({id:s.accountId,name:s.accountName}))}}async getAzureProjects(n,e={}){let t=new URL(`${q}/${encodeURIComponent(n.namespace)}/_apis/projects`);t.searchParams.set("$top",C.toString()),n.cursor&&t.searchParams.set("$skip",n.cursor);let s=await this.config.request({url:t.toString(),headers:S(this.config,e)}),o=s.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:s.body.value.map(a=>({id:a.id,name:a.name,namespace:n.namespace}))}}async getAzureProjectScopeDescriptor(n,e={}){let{namespace:t,projectId:s}=n;return{data:{scope:(await this.config.request({url:`https://vssps.dev.azure.com/${encodeURIComponent(t)}/_apis/graph/descriptors/${s}?api-version=6.0`,headers:S(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(n,e={}){let{namespace:t,projectScopeDescriptor:s,cursor:o}=n,a=new URL(`https://vssps.dev.azure.com/${encodeURIComponent(t)}/_apis/graph/users`);s&&a.searchParams.set("scopeDescriptor",s),o&&a.searchParams.set("continuationToken",o);let i=await this.config.request({url:a.toString(),headers:S(this.config,e)}),u=i.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:i.body.value.map(l=>{var p,d,c,g;return{avatarUrl:((d=(p=l._links)==null?void 0:p.avatar)==null?void 0:d.href)??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:((g=(c=l._links)==null?void 0:c.storageKey)==null?void 0:g.href)??null,username:l.displayName??null}})}}async getAccountFromAzureGraphAccount(n,e={}){let{azureGraphAccount:t}=n;if(!t.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let s=await this.config.request({url:t.storageKeyURL,headers:S(this.config,e)});return{data:{avatarUrl:t.avatarUrl,email:t.email,id:s.body.value,name:t.name,username:t.username,url:null}}}async getAccountsFromAzureGraphAccounts(n,e={}){let t=[];for(let s of n.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:s},e);t.push(o.data)}return{data:t}}async getRepo(n,e={}){if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let t=await this.config.request({url:`${q}/${encodeURIComponent(n.namespace)}/${encodeURIComponent(n.project)}/_apis/git/repositories/${encodeURIComponent(n.name)}`,headers:S(this.config,e)});return{data:wt(n.namespace,t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let a=await this.getRepo(o,e);t.push(a.data)}catch(a){s.push({input:o,error:a})}})),{data:t,errors:s}}async getReposForAzureProject(n,e={}){if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${q}/${encodeURIComponent(n.namespace)}/${encodeURIComponent(n.project)}/_apis/git/repositories`,headers:S(this.config,e)})).body.value.map(s=>wt(n.namespace,s))}}async getRefs(n,e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=new URL(`${q}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);s.searchParams.set("filter",n),s.searchParams.set("$top",C.toString()),e.cursor&&s.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:s.toString(),headers:S(this.config,t)}),a=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:o.body.value.map(i=>({name:ge(i.name),commit:{oid:i.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(n,e={}){return this.getRefs("heads",n,e)}async getTags(n,e={}){return this.getRefs("tags",n,e)}async getPullRequestsForRepoBase(n,e={},t=100){let{page:s,repo:o,assigneeLogins:a,authorLogin:i}=n||{},u=s||1;if(!o.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return a&&a.length&&(l+=`&searchCriteria.reviewerId=${a[0]}`),i&&(l+=`&searchCriteria.creatorId=${i}`),await this.config.request({url:`${e.baseUrl||q}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${t}&%24skip=${(u-1)*t}`,headers:S(this.config,e)})}async getPullRequestsForRepo(n,e={}){let s=n.page||1,o=await this.getPullRequestsForRepoBase(n,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:s+1},data:o.body.value.map(a=>ce(n.repo.namespace,a))}}async getPullRequestsForRepos(n,e={}){if(!n.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:t}=n||{},s=[];return await Promise.all(t.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...n},e)).body.value.forEach(i=>{s.push(ce(o.namespace,i))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:s}}async getPullRequestsForProjectBase(n,e={},t=100){let{namespace:s,project:o,page:a,assigneeLogins:i,authorLogin:u,repo:l}=n;if(l!=null&&l.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let p=a||1,d=new URL(`${e.baseUrl||q}/${encodeURIComponent(s)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",t.toString()),d.searchParams.set("$skip",((p-1)*t).toString()),l!=null&&l.id&&(l==null?void 0:l.project)===o&&d.searchParams.set("searchCriteria.repositoryId",l.id),i&&i.length&&d.searchParams.set("searchCriteria.reviewerId",i[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers:S(this.config,e)})}async getPullRequestsForProject(n,e={}){let s=n.page||1,o=await this.getPullRequestsForProjectBase(n,e,100);return{pageInfo:{hasNextPage:(o==null?void 0:o.body.value.length)===100,nextPage:s+1},data:(o==null?void 0:o.body.value.map(a=>ce(n.namespace,a)))||[]}}async getPullRequestsForProjects(n,e={}){let{projects:t}=n||{},s=[];return await Promise.all(t.map(async o=>{try{if(!n.repo||n.repo.project&&n.repo.project===o.project){let a=await this.getPullRequestsForProjectBase({...o,...n},e);a==null||a.body.value.forEach(i=>{s.push(ce(o.namespace,i))})}}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:s}}async getAzurePullRequestLastMergeStatus(n,e={}){if(!n.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:t,project:s,name:o},pullRequestId:a}=n,i=await this.config.request({url:`${e.baseUrl||q}/${encodeURIComponent(t)}/${encodeURIComponent(s||"")}/_apis/git/repositories/${o}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...S(this.config,e)}});if(!i.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:i.body.mergeStatus}}async updatePullRequest(n,e,t){return await this.config.request({method:"PATCH",url:`${t.baseUrl||q}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}?api-version=6.0`,body:e,headers:{...S(this.config,t),"Content-Type":"application/json"}})}async closePullRequest(n,e={}){let{pullRequest:t}=n,s={status:"abandoned"};if(!(await this.updatePullRequest(t,JSON.stringify(s),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){var u;let{pullRequest:t,mergeStrategy:s}=n,o;switch(s){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 a={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:(u=t.headRef)==null?void 0:u.oid},status:"completed"};if(!(await this.updatePullRequest(t,JSON.stringify(a),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(n,e={}){let{pullRequest:t,label:s}=n;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o={name:s.name};if(!(await this.config.request({method:"POST",url:`${e.baseUrl||q}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels?api-version=6.0`,body:JSON.stringify(o),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(n,e={}){let{pullRequest:t,label:s}=n;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${e.baseUrl||q}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels/${encodeURIComponent(s.name)}?api-version=6.0`,headers:{...S(this.config,e)}})}async setPullRequestLabels(n,e={}){let{pullRequest:t,labels:s}=n;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=t.labels;if(!o)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of s)o.find(i=>i.id===a.id)||await this.addPullRequestLabel({pullRequest:t,label:a},e);for(let a of o)s.find(i=>a.id===i.id)||await this.removePullRequestLabel({pullRequest:t,label:a},e)}async setPullRequestAsDraft(n,e={}){let{pullRequest:t,isDraft:s}=n,o={isDraft:s};if(!(await this.updatePullRequest(t,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(n,e={}){let{pullRequest:t,reviewer:s,isRequired:o}=n,a={id:s.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||q}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${s.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(n,e={}){let{pullRequest:t,reviewer:s}=n;await this.config.request({method:"DELETE",url:`${e.baseUrl||q}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${s.id}?api-version=6.0`,headers:{...S(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n;for(let o of s)t.assignees.find(a=>a.id===o.id)||await this.addPullRequestReviewer({pullRequest:t,reviewer:o,isRequired:!0},e);for(let o of t.assignees)s.find(a=>o.id===a.id)||await this.removePullRequestReviewer({pullRequest:t,reviewer:o},e)}async getIssuesForAzureProject(n,e={}){let{page:t,assigneeLogins:s,authorLogin:o,mentionLogin:a,labelNames:i,statusByWorkItemIdByStatusId:u}=n||{},l=t||1,p=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&d.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),s&&s[0]&&d.push(`[System.AssignedTo] = '${s[0].replace("'","''")}'`),a&&d.push("[System.Id] IN (@recentMentions)"),i&&i.forEach(I=>d.push(`[System.Tags] Contains '${I}'`));let c=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${e.baseUrl||q}/${encodeURIComponent(n.namespace)}/${encodeURIComponent(n.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...S(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(I=>I.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let h=await this.config.request({url:`${e.baseUrl||q}/${encodeURIComponent(n.namespace)}/${encodeURIComponent(n.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...S(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:h.body.value.map(I=>nr(n.namespace,n.project,I,u||{}))}}async getPermissionsForRepos(n,e={}){let{namespace:t,repos:s}=n,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=p=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${p.projectId}/${p.id}`;return Object.keys(o).map(g=>({securityNamespaceId:d,token:c,permissions:g}))},i={alwaysAllowAdministrators:!1,evaluations:s.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${e.baseUrl||q}/${encodeURIComponent(t)}/_apis/security/permissionevaluationbatch?api-version=7.1`,body:JSON.stringify(i),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,h=o[d.permissions];for(let I of h)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][I]=!1);return p},{})}}async decorateReposWithPermissions(n,e={}){let{namespace:t,repos:s}=n,o=await this.getPermissionsForRepos({namespace:t,repos:s},e);return{data:s.map(a=>({...a,permissions:o.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(n,e,t={}){return await this.config.request({method:"PATCH",url:`${t.baseUrl||q}/${encodeURIComponent(n.project.namespace)}/${encodeURIComponent(n.project.name)}/_apis/wit/workitems/${n.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...S(this.config,t),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(n,e={}){var i;let{issue:t,status:s}=n,o=[{op:"add",path:"/fields/System.State",value:s.name}];if(!((i=(await this.updateIssue(t,o,e)).body.fields)!=null&&i["System.State"]))throw new Error("Could not set issue status")}async setIssueAssignee(n,e={}){var i;let{issue:t,assignee:s}=n,o=[{op:"add",path:"/fields/System.AssignedTo",value:(s==null?void 0:s.name)??""}];if(!((i=(await this.updateIssue(t,o,e)).body.fields)!=null&&i["System.State"]))throw new Error("Could not set issue assignee")}async setIssueLabels(n,e={}){var u;let{issue:t,labels:s}=n,a=[{op:"replace",path:"/fields/System.Tags",value:s.map(l=>l.name).join(";")}];if(!((u=(await this.updateIssue(t,a,e)).body.fields)!=null&&u["System.Tags"]))throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(n,e={}){if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:t,project:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||q}/${encodeURIComponent(t)}/${encodeURIComponent(s||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...S(this.config,e)}})).body.value}}async getLabelsForProject(n,e={}){let{namespace:t,project:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||q}/${encodeURIComponent(t)}/${encodeURIComponent(s||"")}/_apis/wit/tags?api-version=6.0`,headers:{...S(this.config,e)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}};var D=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT);var L="https://api.bitbucket.org/2.0",or={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},me=r=>({id:r.uuid,name:r.display_name||r.nickname,username:r.nickname||r.display_name,email:null,avatarUrl:r.links.avatar.href,url:r.links.html.href}),St=r=>{let n=r.links.clone,e=n==null?void 0:n.find(s=>s.name==="ssh"),t=n==null?void 0:n.find(s=>s.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},vt=r=>{var n,e;return{id:r.uuid,namespace:r.workspace.slug,name:r.slug,webUrl:r.links.html.href,httpsUrl:((n=r.links.clone.find(t=>t.name==="https"))==null?void 0:n.href)??null,sshUrl:((e=r.links.clone.find(t=>t.name==="ssh"))==null?void 0:e.href)??null,defaultBranch:{name:r.mainbranch.name},permissions:null}},Fe=r=>{var t;let n=r.id,e=((t=r.participants)==null?void 0:t.map(s=>{let o="REVIEW_REQUESTED";return s.approved?o="APPROVED":s.state==="changes_requested"?o="CHANGES_REQUESTED":s.participated_on!==null&&(o="COMMENTED"),{reviewer:me(s.user),state:o}}))??[];return{id:n.toString(),title:r.title,number:n,state:or[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:me(r.author),createdDate:new Date(r.created_on),updatedDate:new Date(r.updated_on),closedDate:null,mergedDate:null,repository:{id:r.destination.repository.uuid,name:r.destination.repository.name,owner:{login:r.destination.repository.full_name.split("/")[0]},remoteInfo:St(r.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:r.destination.branch.name,oid:r.destination.commit.hash},headRef:{name:r.source.branch.name,oid:r.source.commit.hash},url:r.links.html.href,assignees:null,reviews:e,reviewDecision:x(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:r.source.repository.uuid,name:r.source.repository.name,owner:{login:r.source.repository.full_name.split("/")[0]},remoteInfo:St(r.source.repository)},mergeableState:"UNKNOWN",permissions:null}},ar=r=>{switch(r){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}}},V=class extends T{async refreshToken(n){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 ${n.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${n.refreshToken}`})).body}}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${L}/user`,headers:D(this.config,e)});return{data:me(t.body)}}async getUserForCommit(n,e={}){var a;let s=(await this.config.request({url:`${L}/repositories/${n.repo.namespace}/${n.repo.name}/commit/${n.oid}`,headers:D(this.config,e)})).body.author,o=s.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:((a=s.user)==null?void 0:a.links.avatar.href)||null}}}async getRepo(n,e={}){let t=await this.config.request({url:`${L}/repositories/${n.namespace}/${n.name}`,headers:D(this.config,e)});return{data:vt(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let a=await this.getRepo(o,e);t.push(a.data)}catch(a){s.push({input:o,error:a})}})),{data:t,errors:s}}async getReposForCurrentUser(n,e={}){let t=new URL(`${L}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",C.toString()),n.cursor&&t.searchParams.set("after",n.cursor);let s=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!s.body.next,a=null;return s.body.next&&(a=new URL(s.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:a},data:s.body.values.map(vt)}}async getBranches(n,e={}){var a;let t=new URL(`${L}/repositories/${n.repo.namespace}/${n.repo.name}/refs/branches`);t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen",C.toString());let s=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>{let u=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:u,committedDate:u}}})}}async getTags(n,e={}){let t=new URL(`${L}/repositories/${n.repo.namespace}/${n.repo.name}/refs/tags`);t.searchParams.set("pagelen",C.toString()),n.cursor&&t.searchParams.set("page",n.cursor);let s=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!s.body.next,a=null;return s.body.next&&(a=new URL(s.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:a},data:s.body.values.map(i=>{let u=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForUser(n,e={}){var a;let t=new URL(`${L}/user/permissions/workspaces`);t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen","50");let s=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(n,e={}){var a;let t=new URL(`${L}/workspaces/${n.workspaceSlug}/pullrequests/${n.userId}`);if(t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen","50"),n.repos&&n.repos.length>0){let i=`state = "open" AND (${n.repos.map(u=>`source.repository.full_name = "${u.namespace}/${u.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let s=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(Fe)}}async getPullRequestsForRepoBase(n,e={}){var a;let t=new URL(`${L}/repositories/${encodeURI(n.repo.namespace)}/${encodeURI(n.repo.name)}/pullrequests?state=OPEN`),s=[];n.reviewerId&&s.push(`reviewers.uuid="${n.reviewerId}"`),n.authorLogin&&s.push(`author.uuid="${n.authorLogin}"`);let o='state="OPEN"';return s.length&&(o+=` AND (${s.join(n.useOrFilter?" OR ":" AND ")})`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:D(this.config,e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);s.body.values.forEach(a=>{t.push(Fe(a))});let o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async s=>{try{(await this.getPullRequestsForRepoBase({repo:s,...n},e)).body.values.forEach(a=>{t.push(Fe(a))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(n,e={}){var a;let t=new URL(`${L}/workspaces/${encodeURI(n.workspace)}/members`);t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>me(i.user))}}async getReposPermissionsForCurrentUser(n,e={}){var a;let t=new URL(`${L}/user/permissions/repositories`);t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.reduce((i,u)=>({...i,[u.repository.uuid]:ar(u.permission)}),{})}}async decorateReposWithPermissions(n,e={}){let t={},s=1;do{let o=await this.getReposPermissionsForCurrentUser({page:s},e);t={...o.data,...t},s=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(s!==null);return{data:n.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(n,e={}){let{pullRequest:t}=n;if(!(await this.config.request({method:"POST",url:`${L}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:D(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:s}=n,o;switch(s){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let a={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${L}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(a),headers:{...D(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n,o={reviewers:s.map(i=>{if(i.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:i.username}})};if(!(await this.config.request({method:"PUT",url:`${L}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...D(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var _e=r=>({name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrl??null,id:r.id.toString(),username:r.name,url:r.links.self[0].href}),Qe=r=>{var u,l,p,d,c,g;let n={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=r.reviewers.map(m=>({reviewer:_e(m.user),state:e[m.status]})),s=((u=r.toRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:u.href)??null,o=((l=r.toRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:l.href)??null;o||(o=((p=r.toRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:p.href)??null);let a=((d=r.fromRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:d.href)??null,i=((c=r.fromRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:c.href)??null;return i||(i=((g=r.fromRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:g.href)??null),{id:r.id.toString(),number:r.id,title:r.title,url:r.links.self[0].href,state:n[r.state],isDraft:!1,createdDate:new Date(r.createdDate),updatedDate:new Date(r.updatedDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.state=="MERGED"&&r.closedDate?new Date(r.closedDate):null,baseRef:{name:r.toRef.displayId,oid:r.toRef.latestCommit},headRef:{name:r.fromRef.displayId,oid:r.fromRef.latestCommit},commentCount:r.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:_e(r.author.user),assignees:null,reviews:t,reviewDecision:x(t),repository:{id:r.toRef.repository.id.toString(),name:r.toRef.repository.name,owner:{login:r.toRef.repository.project.key},remoteInfo:o&&s?{cloneUrlHTTPS:o,cloneUrlSSH:s}:null},headRepository:{id:r.fromRef.repository.id.toString(),name:r.fromRef.repository.name,owner:{login:r.fromRef.repository.project.key},remoteInfo:i&&a?{cloneUrlHTTPS:i,cloneUrlSSH:a}:null},headCommit:null,mergeableState:"UNKNOWN",permissions:null,version:r.version}},qt=r=>{var n,e,t;return{id:r.id.toString(),namespace:r.project.key,name:r.slug,webUrl:((n=r.links.self[0])==null?void 0:n.href)??null,httpsUrl:((e=r.links.clone.find(s=>s.name==="https"||s.name==="http"))==null?void 0:e.href)??null,sshUrl:((t=r.links.clone.find(s=>s.name==="ssh"))==null?void 0:t.href)??null,defaultBranch:null,permissions:null}},X=class extends k{getBaseUrl(n){let e=n.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(n){return R(n.token||this.config.token)}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":s,"x-ausername":o}}=t,a=s?parseInt(s,10):null,i=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>a?a===d:i===c||i===p||i===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:_e(l)}}async getRepo(n,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${n.namespace}/repos/${n.name}`,headers:this.getRequestHeaders(e)});return{data:qt(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let a=await this.getRepo(o,e);t.push(a.data)}catch(a){s.push({input:o,error:a})}})),{data:t,errors:s}}async getReposForCurrentUser(n,e={}){let t=n.page??0,s=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!s.body.isLastPage,nextPage:s.body.nextPageStart},data:s.body.values.map(qt)}}async getPullRequestsForRepoBase(n,e={}){var s;let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.repo.namespace)}/repos/${encodeURI(n.repo.name)}/pull-requests?state=OPEN`);return t.searchParams.set("start",((s=n.page)==null?void 0:s.toString())||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);s.body.values.forEach(a=>{if(n.authorLogin&&a.author.user.name!==n.authorLogin)return null;t.push(Qe(a))});let o=s.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.start+s.body.values.length:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async s=>{try{(await this.getPullRequestsForRepoBase({repo:s,...n},e)).body.values.forEach(a=>{if(n.authorLogin&&a.author.user.name!==n.authorLogin)return null;t.push(Qe(a))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(n,e={}){var a;let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",((a=n.page)==null?void 0:a.toString())||"0"),t.searchParams.set("limit","50");let s=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=s.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.start+s.body.values.length:null},data:s.body.values.map(Qe)}}async closePullRequest(n,e={}){let{pullRequest:t}=n;if(t.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/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategyId:s}=n;if(n.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.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/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:s,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(n={}){let e=await this.config.request({url:`${this.getBaseUrl(n)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(n),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:s.map(i=>{if(i.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:i.username}}}),version:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var At=require("js-base64");var he=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(he||{});var b=class extends Error{constructor(e,t){let s=t==null?void 0:t.map(a=>`'${a.message}'`).join(", "),o=s?`${e}: ${s}`:e;super(o);this.graphQLErrors=t??[]}};var ir={AS_CODE_OWNER:[3,0,0],CHECK_RUN:[3,0,0],PR_ISSUE_FULL_DATABASE_ID:[3,12,0],LATEST_REVIEWS:[3,0,0],VIEWER_CAN_MERGE_AS_ADMIN:[3,5,0]},Et=15,Ct=100,U=r=>!!r,Z=(r,n)=>{let e=ir[n];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},Ie="https://api.github.com",ur=`${Ie}/graphql`,Re=`
1
+ "use strict";var Wt=Object.create;var le=Object.defineProperty;var Ht=Object.getOwnPropertyDescriptor;var Jt=Object.getOwnPropertyNames;var Vt=Object.getPrototypeOf,Kt=Object.prototype.hasOwnProperty;var Xt=(r,n)=>{for(var e in n)le(r,e,{get:n[e],enumerable:!0})},gt=(r,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of Jt(n))!Kt.call(r,s)&&s!==e&&le(r,s,{get:()=>n[s],enumerable:!(t=Ht(n,s))||t.enumerable});return r};var Zt=(r,n,e)=>(e=r!=null?Wt(Vt(r)):{},gt(n||!r||!r.__esModule?le(e,"default",{value:r,enumerable:!0}):e,r)),Yt=r=>gt(le({},"__esModule",{value:!0}),r);var ls={};Xt(ls,{AzureDevOps:()=>K,Bitbucket:()=>X,BitbucketServer:()=>Z,EntityIdentifierProviderType:()=>Mt,EntityType:()=>Bt,EntityVersion:()=>jt,GitBuildStatusStage:()=>mt,GitBuildStatusState:()=>pe,GitDiffLineType:()=>xe,GitHub:()=>ee,GitHubIssueCloseReason:()=>zt,GitIssueState:()=>he,GitLab:()=>re,GitMergeStrategy:()=>V,GitPullRequestMergeableState:()=>J,GitPullRequestReviewState:()=>B,GitPullRequestState:()=>H,GraphQLErrors:()=>b,Jira:()=>se,JiraServer:()=>ne,PullRequestAsyncStatus:()=>Qt,Trello:()=>oe,default:()=>us,isFetch:()=>de});module.exports=Yt(ls);var mt=(s=>(s.Build="build",s.Production="production",s.Staging="staging",s.Test="test",s))(mt||{}),pe=(p=>(p.ActionRequired="ACTION_REQUIRED",p.Cancelled="CANCELLED",p.Error="ERROR",p.Failed="FAILED",p.Pending="PENDING",p.Running="RUNNING",p.Skipped="SKIPPED",p.Success="SUCCESS",p.Warning="WARNING",p.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",p))(pe||{}),V=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(V||{}),H=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(H||{}),B=(s=>(s.Approved="APPROVED",s.ChangesRequested="CHANGES_REQUESTED",s.Commented="COMMENTED",s.ReviewRequested="REVIEW_REQUESTED",s))(B||{}),J=(u=>(u.Behind="BEHIND",u.Blocked="BLOCKED",u.Conflicts="CONFLICTS",u.FailingChecks="FAILING_CHECKS",u.Mergeable="MERGEABLE",u.Unknown="UNKNOWN",u.UnknownAndBlocked="UNKNOWN_AND_BLOCKED",u.Unstable="UNSTABLE",u))(J||{}),xe=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(xe||{});var ht={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},x=r=>!r||r.length===0?null:r.reduce((n,e)=>ht[e.state]>ht[n]?e.state:n,"APPROVED");var C=100;var ft=Zt(require("node-fetch")),It=globalThis.fetch||ft.default;var er=async r=>{let n=r.headers.get("content-type")||"",e=null;if(n.startsWith("application/json")){let s=await r.text();e=s.trim().length>0?JSON.parse(s):null}else if(n.startsWith("text/")||n==="")e=await r.text();else if(n.startsWith("application/vnd.github.raw+json"))e=await r.arrayBuffer();else throw new Error(`Unsupported content-type: ${n}`);let t={body:e,headers:Object.fromEntries(r.headers.entries()),status:r.status,statusText:r.statusText};if(!r.ok){let s=new Error(r.statusText);throw Object.assign(s,{response:t}),s}return t},ke=r=>async({url:n,...e})=>{let t=await r(n,e);return er(t)};var de=(r,n=!1)=>r.name==="fetch"||n;var T=class{constructor(n){let e=(n==null?void 0:n.request)||It;this.config={...n,request:de(e,n==null?void 0:n.forceIsFetch)?ke(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&de(n.request,(n==null?void 0:n.forceIsFetch)??this.config.forceIsFetch)?ke(n.request):this.config.request}}},k=class extends T{};var R=(r,n)=>{let e={};return r&&(e.Authorization=`${n?"Basic":"Bearer"} ${r}`),e},Rt=r=>r?r.reduce((n,e)=>(n[e]=!0,n),{}):void 0,M=(r,n,e)=>!r||n.some(t=>r[t])?e:"",bt=async r=>{var s,o,a;let n=[],e=!0,t;for(;e;){let i=await r(t);n=n.concat(i.data),e=!!((s=i==null?void 0:i.pageInfo)!=null&&s.hasNextPage),t=((o=i==null?void 0:i.pageInfo)==null?void 0:o.endCursor)||((a=i==null?void 0:i.pageInfo)==null?void 0:a.nextPage)}return n};var S=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT),yt=r=>r.url.replace("/_apis/git/repositories/","/_git/").replace(`/${r.repository.project.id}/`,`/${encodeURIComponent(r.repository.project.name)}/`).replace(`/${r.repository.id}/`,`/${encodeURIComponent(r.repository.name)}/`).replace("/pullRequests/","/pullrequest/");var Pt="https://app.vssps.visualstudio.com/_apis",E="https://dev.azure.com",tr={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},rr={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},Ne=r=>({id:r.id,name:r.displayName??null,username:(r.uniqueName||r.displayName)??null,email:null,avatarUrl:r.imageUrl??null,url:null}),ge=r=>r.startsWith("refs/heads/")?r.replace("refs/heads/",""):r,sr=r=>{switch(r){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},ce=(r,n)=>{var s;let e=[],t=[];return n.reviewers.forEach(o=>{let a={reviewer:Ne(o),state:rr[o.vote??0]||"REVIEW_REQUESTED"};o.isRequired&&e.push(a),t.push(a)}),{id:n.pullRequestId.toString(),title:n.title,number:n.codeReviewId,state:tr[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:Ne(n.createdBy),createdDate:new Date(n.creationDate),updatedDate:new Date(n.closedDate||n.creationDate),closedDate:n.closedDate?new Date(n.closedDate):null,mergedDate:n.closedDate&&n.status==="completed"?new Date(n.closedDate):null,repository:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:ge(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:ge(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:yt(n),assignees:n.reviewers.map(Ne),reviews:t,reviewDecision:x(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:n.forkSource?{id:n.forkSource.repository.id,name:n.forkSource.repository.name,project:void 0,owner:{login:r},remoteInfo:null}:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:r},remoteInfo:null},mergeableState:sr(n.mergeStatus),labels:((s=n.labels)==null?void 0:s.map(o=>({color:null,description:null,id:o.id,name:o.name})))??[],permissions:null}},wt=(r,n)=>({id:n.id,name:n.name,namespace:r,project:n.project.name,projectId:n.project.id,webUrl:n.webUrl,httpsUrl:n.remoteUrl,sshUrl:n.sshUrl,defaultBranch:n.defaultBranch?{name:ge(n.defaultBranch)}:null,permissions:null}),nr=(r,n,e,t)=>{var l,p,d,c,g,m;let s=e.fields,o=s["System.AssignedTo"],a=s["System.State"],i=s["System.WorkItemType"],u;return a&&i&&(u=(l=t[i])==null?void 0:l[a]),{id:e.id.toString(),number:e.id.toString(),title:s["System.Title"],commentCount:s["System.CommentCount"],author:{avatarUrl:((d=(p=s["System.CreatedBy"]._links)==null?void 0:p.avatar)==null?void 0:d.href)??null,email:null,id:s["System.CreatedBy"].id,name:s["System.CreatedBy"].uniqueName??null,username:s["System.CreatedBy"].displayName??null,url:null},closedDate:s["Microsoft.VSTS.Common.ClosedDate"]?new Date(s["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(s["System.CreatedDate"]),updatedDate:new Date(s["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:((g=(c=o._links)==null?void 0:c.avatar)==null?void 0:g.href)??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:s["System.Description"]??null,state:{name:(u==null?void 0:u.title)||a,color:null},type:s["System.WorkItemType"],repository:null,project:{namespace:r,name:n,resourceId:null,key:null,id:null},upvoteCount:0,labels:((m=e.fields["System.Tags"])==null?void 0:m.split(";").map(I=>({color:null,description:null,id:null,name:I.trim()})))??[]}},K=class extends T{async getCurrentUser(n={},e={}){if(e.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let t=await this.config.request({url:`${Pt}/profile/profiles/me`,headers:S(this.config,e)});return{data:{id:t.body.id,name:t.body.displayName,username:t.body.displayName,email:t.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(n,e={}){let s=(await this.config.request({url:`${E}/${encodeURIComponent(n.namespace)}/_apis/ConnectionData`,headers:S(this.config,e)})).body.authorizedUser;if(s.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:s.id,name:s.providerDisplayName,username:s.providerDisplayName,email:s.properties.Account.$value,avatarUrl:null}}}async getUserForCommit(n,e={}){if(!n.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=(await this.config.request({url:`${E}/${encodeURIComponent(n.repo.namespace)}/${encodeURIComponent(n.repo.project)}/_apis/git/repositories/${encodeURIComponent(n.repo.name)}/commits/${n.oid}`,headers:S(this.config,e)})).body.author;return{data:{name:s.name,email:s.email,avatarUrl:s.imageUrl}}}async getOrgsForUser(n,e={}){return{data:(await this.config.request({url:`${Pt}/accounts?memberId=${n.userId}&api-version=6.0`,headers:S(this.config,e)})).body.value.map(s=>({id:s.accountId,name:s.accountName}))}}async getAzureProjects(n,e={}){let t=new URL(`${E}/${encodeURIComponent(n.namespace)}/_apis/projects`);t.searchParams.set("$top",C.toString()),n.cursor&&t.searchParams.set("$skip",n.cursor);let s=await this.config.request({url:t.toString(),headers:S(this.config,e)}),o=s.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!o,endCursor:o||null},data:s.body.value.map(a=>({id:a.id,name:a.name,namespace:n.namespace}))}}async getAzureProjectScopeDescriptor(n,e={}){let{namespace:t,projectId:s}=n;return{data:{scope:(await this.config.request({url:`https://vssps.dev.azure.com/${encodeURIComponent(t)}/_apis/graph/descriptors/${s}?api-version=6.0`,headers:S(this.config,e)})).body.value}}}async getAzureGraphAccountsForAzureProject(n,e={}){let{namespace:t,projectScopeDescriptor:s,cursor:o}=n,a=new URL(`https://vssps.dev.azure.com/${encodeURIComponent(t)}/_apis/graph/users`);s&&a.searchParams.set("scopeDescriptor",s),o&&a.searchParams.set("continuationToken",o);let i=await this.config.request({url:a.toString(),headers:S(this.config,e)}),u=i.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:u||null,hasNextPage:!!u},data:i.body.value.map(l=>{var p,d,c,g;return{avatarUrl:((d=(p=l._links)==null?void 0:p.avatar)==null?void 0:d.href)??null,descriptor:l.descriptor??null,email:l.mailAddress??null,name:l.displayName??null,storageKeyURL:((g=(c=l._links)==null?void 0:c.storageKey)==null?void 0:g.href)??null,username:l.displayName??null}})}}async getAccountFromAzureGraphAccount(n,e={}){let{azureGraphAccount:t}=n;if(!t.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let s=await this.config.request({url:t.storageKeyURL,headers:S(this.config,e)});return{data:{avatarUrl:t.avatarUrl,email:t.email,id:s.body.value,name:t.name,username:t.username,url:null}}}async getAccountsFromAzureGraphAccounts(n,e={}){let t=[];for(let s of n.azureGraphAccounts){let o=await this.getAccountFromAzureGraphAccount({azureGraphAccount:s},e);t.push(o.data)}return{data:t}}async getRepo(n,e={}){if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let t=await this.config.request({url:`${E}/${encodeURIComponent(n.namespace)}/${encodeURIComponent(n.project)}/_apis/git/repositories/${encodeURIComponent(n.name)}`,headers:S(this.config,e)});return{data:wt(n.namespace,t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let a=await this.getRepo(o,e);t.push(a.data)}catch(a){s.push({input:o,error:a})}})),{data:t,errors:s}}async getReposForAzureProject(n,e={}){if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${E}/${encodeURIComponent(n.namespace)}/${encodeURIComponent(n.project)}/_apis/git/repositories`,headers:S(this.config,e)})).body.value.map(s=>wt(n.namespace,s))}}async getRefs(n,e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let s=new URL(`${E}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/refs`);s.searchParams.set("filter",n),s.searchParams.set("$top",C.toString()),e.cursor&&s.searchParams.set("continuationToken",e.cursor);let o=await this.config.request({url:s.toString(),headers:S(this.config,t)}),a=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:o.body.value.map(i=>({name:ge(i.name),commit:{oid:i.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(n,e={}){return this.getRefs("heads",n,e)}async getTags(n,e={}){return this.getRefs("tags",n,e)}async getPullRequestsForRepoBase(n,e={},t=100){let{page:s,repo:o,assigneeLogins:a,authorLogin:i}=n||{},u=s||1;if(!o.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let l="searchCriteria.status=1";return a&&a.length&&(l+=`&searchCriteria.reviewerId=${a[0]}`),i&&(l+=`&searchCriteria.creatorId=${i}`),await this.config.request({url:`${e.baseUrl||E}/${encodeURIComponent(o.namespace)}/${encodeURIComponent(o.project||"")}/_apis/git/repositories/${encodeURIComponent(o.name)}/pullRequests?${l}&%24top=${t}&%24skip=${(u-1)*t}`,headers:S(this.config,e)})}async getPullRequestsForRepo(n,e={}){let s=n.page||1,o=await this.getPullRequestsForRepoBase(n,e,100);return{pageInfo:{hasNextPage:o.body.value.length===100,nextPage:s+1},data:o.body.value.map(a=>ce(n.repo.namespace,a))}}async getPullRequestsForRepos(n,e={}){if(!n.repos.every(o=>o.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:t}=n||{},s=[];return await Promise.all(t.map(async o=>{try{(await this.getPullRequestsForRepoBase({repo:o,...n},e)).body.value.forEach(i=>{s.push(ce(o.namespace,i))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:s}}async getPullRequestsForProjectBase(n,e={},t=100){let{namespace:s,project:o,page:a,assigneeLogins:i,authorLogin:u,repo:l}=n;if(l!=null&&l.project&&l.project!==o)throw new Error("Could not fetch pull requests, project mismatch");let p=a||1,d=new URL(`${e.baseUrl||E}/${encodeURIComponent(s)}/${encodeURIComponent(o)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",t.toString()),d.searchParams.set("$skip",((p-1)*t).toString()),l!=null&&l.id&&(l==null?void 0:l.project)===o&&d.searchParams.set("searchCriteria.repositoryId",l.id),i&&i.length&&d.searchParams.set("searchCriteria.reviewerId",i[0]),u&&d.searchParams.set("searchCriteria.creatorId",u),await this.config.request({url:d.toString(),headers:S(this.config,e)})}async getPullRequestsForProject(n,e={}){let s=n.page||1,o=await this.getPullRequestsForProjectBase(n,e,100);return{pageInfo:{hasNextPage:(o==null?void 0:o.body.value.length)===100,nextPage:s+1},data:(o==null?void 0:o.body.value.map(a=>ce(n.namespace,a)))||[]}}async getPullRequestsForProjects(n,e={}){let{projects:t}=n||{},s=[];return await Promise.all(t.map(async o=>{try{if(!n.repo||n.repo.project&&n.repo.project===o.project){let a=await this.getPullRequestsForProjectBase({...o,...n},e);a==null||a.body.value.forEach(i=>{s.push(ce(o.namespace,i))})}}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:s}}async getAzurePullRequestLastMergeStatus(n,e={}){if(!n.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:t,project:s,name:o},pullRequestId:a}=n,i=await this.config.request({url:`${e.baseUrl||E}/${encodeURIComponent(t)}/${encodeURIComponent(s||"")}/_apis/git/repositories/${o}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...S(this.config,e)}});if(!i.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:i.body.mergeStatus}}async updatePullRequest(n,e,t){return await this.config.request({method:"PATCH",url:`${t.baseUrl||E}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}?api-version=6.0`,body:e,headers:{...S(this.config,t),"Content-Type":"application/json"}})}async closePullRequest(n,e={}){let{pullRequest:t}=n,s={status:"abandoned"};if(!(await this.updatePullRequest(t,JSON.stringify(s),e)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){var u;let{pullRequest:t,mergeStrategy:s}=n,o;switch(s){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 a={completionOptions:{mergeStrategy:o},lastMergeSourceCommit:{commitId:(u=t.headRef)==null?void 0:u.oid},status:"completed"};if(!(await this.updatePullRequest(t,JSON.stringify(a),e)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(n,e={}){let{pullRequest:t,label:s}=n;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o={name:s.name};if(!(await this.config.request({method:"POST",url:`${e.baseUrl||E}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels?api-version=6.0`,body:JSON.stringify(o),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(n,e={}){let{pullRequest:t,label:s}=n;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${e.baseUrl||E}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/labels/${encodeURIComponent(s.name)}?api-version=6.0`,headers:{...S(this.config,e)}})}async setPullRequestLabels(n,e={}){let{pullRequest:t,labels:s}=n;if(!t.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=t.labels;if(!o)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of s)o.find(i=>i.id===a.id)||await this.addPullRequestLabel({pullRequest:t,label:a},e);for(let a of o)s.find(i=>a.id===i.id)||await this.removePullRequestLabel({pullRequest:t,label:a},e)}async setPullRequestAsDraft(n,e={}){let{pullRequest:t,isDraft:s}=n,o={isDraft:s};if(!(await this.updatePullRequest(t,JSON.stringify(o),e)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(n,e={}){let{pullRequest:t,reviewer:s,isRequired:o}=n,a={id:s.id,isRequired:o};if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||E}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${s.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(n,e={}){let{pullRequest:t,reviewer:s}=n;await this.config.request({method:"DELETE",url:`${e.baseUrl||E}/${encodeURIComponent(t.repository.owner.login)}/${encodeURIComponent(t.repository.project)}/_apis/git/repositories/${t.repository.name}/pullrequests/${t.id}/reviewers/${s.id}?api-version=6.0`,headers:{...S(this.config,e),Accept:"application/json"}})}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n;for(let o of s)t.assignees.find(a=>a.id===o.id)||await this.addPullRequestReviewer({pullRequest:t,reviewer:o,isRequired:!0},e);for(let o of t.assignees)s.find(a=>o.id===a.id)||await this.removePullRequestReviewer({pullRequest:t,reviewer:o},e)}async getIssuesForAzureProject(n,e={}){let{page:t,assigneeLogins:s,authorLogin:o,mentionLogin:a,labelNames:i,statusByWorkItemIdByStatusId:u}=n||{},l=t||1,p=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];o&&d.push(`[System.CreatedBy] = '${o.replace("'","''")}'`),s&&s[0]&&d.push(`[System.AssignedTo] = '${s[0].replace("'","''")}'`),a&&d.push("[System.Id] IN (@recentMentions)"),i&&i.forEach(h=>d.push(`[System.Tags] Contains '${h}'`));let c=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${e.baseUrl||E}/${encodeURIComponent(n.namespace)}/${encodeURIComponent(n.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:c}),method:"POST",headers:{...S(this.config,e),"Content-Type":"application/json"}}),m=g.body.workItems.slice((l-1)*p,p*l).map(h=>h.id);if(m.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let I=await this.config.request({url:`${e.baseUrl||E}/${encodeURIComponent(n.namespace)}/${encodeURIComponent(n.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:m,$expand:"Links"}),method:"POST",headers:{...S(this.config,e),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:g.body.workItems.length>p*l,nextPage:l+1},data:I.body.value.map(h=>nr(n.namespace,n.project,h,u||{}))}}async getPermissionsForRepos(n,e={}){let{namespace:t,repos:s}=n,o={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=p=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",c=`repoV2/${p.projectId}/${p.id}`;return Object.keys(o).map(g=>({securityNamespaceId:d,token:c,permissions:g}))},i={alwaysAllowAdministrators:!1,evaluations:s.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${e.baseUrl||E}/${encodeURIComponent(t)}/_apis/security/permissionevaluationbatch?api-version=7.1`,body:JSON.stringify(i),headers:{...S(this.config,e),"Content-Type":"application/json"}})).body.evaluations.reduce((p,d)=>{let[,c,g]=d.token.split("/"),m=`${c}/${g}`,I=o[d.permissions];for(let h of I)p[m]===void 0&&(p[m]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(p[m][h]=!1);return p},{})}}async decorateReposWithPermissions(n,e={}){let{namespace:t,repos:s}=n,o=await this.getPermissionsForRepos({namespace:t,repos:s},e);return{data:s.map(a=>({...a,permissions:o.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(n,e,t={}){return await this.config.request({method:"PATCH",url:`${t.baseUrl||E}/${encodeURIComponent(n.project.namespace)}/${encodeURIComponent(n.project.name)}/_apis/wit/workitems/${n.id}?api-version=6.0`,body:JSON.stringify(e),headers:{...S(this.config,t),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(n,e={}){var i;let{issue:t,status:s}=n,o=[{op:"add",path:"/fields/System.State",value:s.name}];if(!((i=(await this.updateIssue(t,o,e)).body.fields)!=null&&i["System.State"]))throw new Error("Could not set issue status")}async setIssueAssignee(n,e={}){var i;let{issue:t,assignee:s}=n,o=[{op:"add",path:"/fields/System.AssignedTo",value:(s==null?void 0:s.name)??""}];if(!((i=(await this.updateIssue(t,o,e)).body.fields)!=null&&i["System.State"]))throw new Error("Could not set issue assignee")}async setIssueLabels(n,e={}){var u;let{issue:t,labels:s}=n,a=[{op:"replace",path:"/fields/System.Tags",value:s.map(l=>l.name).join(";")}];if(!((u=(await this.updateIssue(t,a,e)).body.fields)!=null&&u["System.Tags"]))throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(n,e={}){if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:t,project:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||E}/${encodeURIComponent(t)}/${encodeURIComponent(s||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...S(this.config,e)}})).body.value}}async getLabelsForProject(n,e={}){let{namespace:t,project:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||E}/${encodeURIComponent(t)}/${encodeURIComponent(s||"")}/_apis/wit/tags?api-version=6.0`,headers:{...S(this.config,e)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}};var L=(r,n={})=>R(n.token||r.token,n.isPAT||r.isPAT);var U="https://api.bitbucket.org/2.0",or={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},me=r=>({id:r.uuid,name:r.display_name||r.nickname,username:r.nickname||r.display_name,email:null,avatarUrl:r.links.avatar.href,url:r.links.html.href}),St=r=>{let n=r.links.clone,e=n==null?void 0:n.find(s=>s.name==="ssh"),t=n==null?void 0:n.find(s=>s.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},vt=r=>{var n,e;return{id:r.uuid,namespace:r.workspace.slug,name:r.slug,webUrl:r.links.html.href,httpsUrl:((n=r.links.clone.find(t=>t.name==="https"))==null?void 0:n.href)??null,sshUrl:((e=r.links.clone.find(t=>t.name==="ssh"))==null?void 0:e.href)??null,defaultBranch:{name:r.mainbranch.name},permissions:null}},Fe=r=>{var t;let n=r.id,e=((t=r.participants)==null?void 0:t.map(s=>{let o="REVIEW_REQUESTED";return s.approved?o="APPROVED":s.state==="changes_requested"?o="CHANGES_REQUESTED":s.participated_on!==null&&(o="COMMENTED"),{reviewer:me(s.user),state:o}}))??[];return{id:n.toString(),title:r.title,number:n,state:or[r.state],isDraft:!1,commentCount:r.comment_count,upvoteCount:null,author:me(r.author),createdDate:new Date(r.created_on),updatedDate:new Date(r.updated_on),closedDate:null,mergedDate:null,repository:{id:r.destination.repository.uuid,name:r.destination.repository.name,owner:{login:r.destination.repository.full_name.split("/")[0]},remoteInfo:St(r.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:r.destination.branch.name,oid:r.destination.commit.hash},headRef:{name:r.source.branch.name,oid:r.source.commit.hash},url:r.links.html.href,assignees:null,reviews:e,reviewDecision:x(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:r.source.repository.uuid,name:r.source.repository.name,owner:{login:r.source.repository.full_name.split("/")[0]},remoteInfo:St(r.source.repository)},mergeableState:"MERGEABLE",permissions:null}},ar=r=>{switch(r){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}}},X=class extends T{async refreshToken(n){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 ${n.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${n.refreshToken}`})).body}}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${U}/user`,headers:L(this.config,e)});return{data:me(t.body)}}async getUserForCommit(n,e={}){var a;let s=(await this.config.request({url:`${U}/repositories/${n.repo.namespace}/${n.repo.name}/commit/${n.oid}`,headers:L(this.config,e)})).body.author,o=s.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:((a=s.user)==null?void 0:a.links.avatar.href)||null}}}async getRepo(n,e={}){let t=await this.config.request({url:`${U}/repositories/${n.namespace}/${n.name}`,headers:L(this.config,e)});return{data:vt(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let a=await this.getRepo(o,e);t.push(a.data)}catch(a){s.push({input:o,error:a})}})),{data:t,errors:s}}async getReposForCurrentUser(n,e={}){let t=new URL(`${U}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",C.toString()),n.cursor&&t.searchParams.set("after",n.cursor);let s=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!s.body.next,a=null;return s.body.next&&(a=new URL(s.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:a},data:s.body.values.map(vt)}}async getBranches(n,e={}){var a;let t=new URL(`${U}/repositories/${n.repo.namespace}/${n.repo.name}/refs/branches`);t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen",C.toString());let s=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>{let u=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:u,committedDate:u}}})}}async getTags(n,e={}){let t=new URL(`${U}/repositories/${n.repo.namespace}/${n.repo.name}/refs/tags`);t.searchParams.set("pagelen",C.toString()),n.cursor&&t.searchParams.set("page",n.cursor);let s=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!s.body.next,a=null;return s.body.next&&(a=new URL(s.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:a},data:s.body.values.map(i=>{let u=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForUser(n,e={}){var a;let t=new URL(`${U}/user/permissions/workspaces`);t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen","50");let s=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(n,e={}){var a;let t=new URL(`${U}/workspaces/${n.workspaceSlug}/pullrequests/${n.userId}`);if(t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen","50"),n.repos&&n.repos.length>0){let i=`state = "open" AND (${n.repos.map(u=>`source.repository.full_name = "${u.namespace}/${u.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let s=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(Fe)}}async getPullRequestsForRepoBase(n,e={}){var a;let t=new URL(`${U}/repositories/${encodeURI(n.repo.namespace)}/${encodeURI(n.repo.name)}/pullrequests?state=OPEN`),s=[];n.reviewerId&&s.push(`reviewers.uuid="${n.reviewerId}"`),n.authorLogin&&s.push(`author.uuid="${n.authorLogin}"`);let o='state="OPEN"';return s.length&&(o+=` AND (${s.join(n.useOrFilter?" OR ":" AND ")})`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:L(this.config,e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);s.body.values.forEach(a=>{t.push(Fe(a))});let o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async s=>{try{(await this.getPullRequestsForRepoBase({repo:s,...n},e)).body.values.forEach(a=>{t.push(Fe(a))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(n,e={}){var a;let t=new URL(`${U}/workspaces/${encodeURI(n.workspace)}/members`);t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.map(i=>me(i.user))}}async getReposPermissionsForCurrentUser(n,e={}){var a;let t=new URL(`${U}/user/permissions/repositories`);t.searchParams.set("page",((a=n.page)==null?void 0:a.toString())||"1"),t.searchParams.set("pagelen","100");let s=await this.config.request({url:t.toString(),headers:L(this.config,e)}),o=!!s.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.page+1:null},data:s.body.values.reduce((i,u)=>({...i,[u.repository.uuid]:ar(u.permission)}),{})}}async decorateReposWithPermissions(n,e={}){let t={},s=1;do{let o=await this.getReposPermissionsForCurrentUser({page:s},e);t={...o.data,...t},s=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(s!==null);return{data:n.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(n,e={}){let{pullRequest:t}=n;if(!(await this.config.request({method:"POST",url:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:L(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:s}=n,o;switch(s){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let a={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(a),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n,o={reviewers:s.map(i=>{if(i.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:i.username}})};if(!(await this.config.request({method:"PUT",url:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...L(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var Qe=r=>({name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrl??null,id:r.id.toString(),username:r.name,url:r.links.self[0].href}),_e=r=>{var u,l,p,d,c,g;let n={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=r.reviewers.map(m=>({reviewer:Qe(m.user),state:e[m.status]})),s=((u=r.toRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:u.href)??null,o=((l=r.toRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:l.href)??null;o||(o=((p=r.toRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:p.href)??null);let a=((d=r.fromRef.repository.links.clone.find(m=>m.name==="ssh"))==null?void 0:d.href)??null,i=((c=r.fromRef.repository.links.clone.find(m=>m.name==="https"))==null?void 0:c.href)??null;return i||(i=((g=r.fromRef.repository.links.clone.find(m=>m.name==="http"))==null?void 0:g.href)??null),{id:r.id.toString(),number:r.id,title:r.title,url:r.links.self[0].href,state:n[r.state],isDraft:!1,createdDate:new Date(r.createdDate),updatedDate:new Date(r.updatedDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.state=="MERGED"&&r.closedDate?new Date(r.closedDate):null,baseRef:{name:r.toRef.displayId,oid:r.toRef.latestCommit},headRef:{name:r.fromRef.displayId,oid:r.fromRef.latestCommit},commentCount:r.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Qe(r.author.user),assignees:null,reviews:t,reviewDecision:x(t),repository:{id:r.toRef.repository.id.toString(),name:r.toRef.repository.name,owner:{login:r.toRef.repository.project.key},remoteInfo:o&&s?{cloneUrlHTTPS:o,cloneUrlSSH:s}:null},headRepository:{id:r.fromRef.repository.id.toString(),name:r.fromRef.repository.name,owner:{login:r.fromRef.repository.project.key},remoteInfo:i&&a?{cloneUrlHTTPS:i,cloneUrlSSH:a}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:r.version}},Et=r=>{var n,e,t;return{id:r.id.toString(),namespace:r.project.key,name:r.slug,webUrl:((n=r.links.self[0])==null?void 0:n.href)??null,httpsUrl:((e=r.links.clone.find(s=>s.name==="https"||s.name==="http"))==null?void 0:e.href)??null,sshUrl:((t=r.links.clone.find(s=>s.name==="ssh"))==null?void 0:t.href)??null,defaultBranch:null,permissions:null}},Z=class extends k{getBaseUrl(n){let e=n.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(n){return R(n.token||this.config.token)}async getCurrentUser(n={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":s,"x-ausername":o}}=t,a=s?parseInt(s,10):null,i=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>a?a===d:i===c||i===p||i===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Qe(l)}}async getRepo(n,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${n.namespace}/repos/${n.name}`,headers:this.getRequestHeaders(e)});return{data:Et(t.body)}}async getRepos(n,e={}){let t=[],s=[];return await Promise.all(n.map(async o=>{try{let a=await this.getRepo(o,e);t.push(a.data)}catch(a){s.push({input:o,error:a})}})),{data:t,errors:s}}async getReposForCurrentUser(n,e={}){let t=n.page??0,s=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!s.body.isLastPage,nextPage:s.body.nextPageStart},data:s.body.values.map(Et)}}async getPullRequestsForRepoBase(n,e={}){var s;let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.repo.namespace)}/repos/${encodeURI(n.repo.name)}/pull-requests?state=OPEN`);return t.searchParams.set("start",((s=n.page)==null?void 0:s.toString())||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(n,e={}){let t=[],s=await this.getPullRequestsForRepoBase(n,e);s.body.values.forEach(a=>{if(n.authorLogin&&a.author.user.name!==n.authorLogin)return null;t.push(_e(a))});let o=s.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.start+s.body.values.length:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async s=>{try{(await this.getPullRequestsForRepoBase({repo:s,...n},e)).body.values.forEach(a=>{if(n.authorLogin&&a.author.user.name!==n.authorLogin)return null;t.push(_e(a))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(n,e={}){var a;let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",((a=n.page)==null?void 0:a.toString())||"0"),t.searchParams.set("limit","50");let s=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=s.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?s.body.start+s.body.values.length:null},data:s.body.values.map(_e)}}async closePullRequest(n,e={}){let{pullRequest:t}=n;if(t.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/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategyId:s}=n;if(n.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.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/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:s,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(n={}){let e=await this.config.request({url:`${this.getBaseUrl(n)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(n),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:s}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:s.map(i=>{if(i.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:i.username}}}),version:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var At=require("js-base64");var he=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(he||{});var b=class extends Error{constructor(e,t){let s=t==null?void 0:t.map(a=>`'${a.message}'`).join(", "),o=s?`${e}: ${s}`:e;super(o);this.graphQLErrors=t??[]}};var ir={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]},qt=15,Ct=100,$=r=>!!r,F=(r,n)=>{let e=ir[n];for(let t=0;t<3;t++){if(r[t]>e[t])return!0;if(r[t]<e[t])return!1}return!0},Ie="https://api.github.com",ur=`${Ie}/graphql`,Re=`
2
2
  description
3
3
  dueOn
4
4
  id
@@ -20,15 +20,15 @@ color
20
20
  description
21
21
  id
22
22
  name
23
- `,Dt=r=>{if(r.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.")},pr=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Dt(e),fe.test(e)&&(e=e.replace(fe,"")),`${e}/api/graphql`):ur},Y=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Dt(e),fe.test(e)&&(e=e.replace(fe,"")),`${e}/api/v3`):Ie},y=(r,n,e)=>{let t=R(e.token||r.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",r.request({url:pr(r,e),method:"POST",headers:t,body:JSON.stringify(n)})},dr={user:!0,"user:email":!0,"read:user":!0},F=r=>r.some(n=>dr[n]),A=(r=!1,n=!1,e)=>`
23
+ `,Dt=r=>{if(r.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.")},pr=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Dt(e),fe.test(e)&&(e=e.replace(fe,"")),`${e}/api/graphql`):ur},Y=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Dt(e),fe.test(e)&&(e=e.replace(fe,"")),`${e}/api/v3`):Ie},y=(r,n,e)=>{let t=R(e.token||r.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",r.request({url:pr(r,e),method:"POST",headers:t,body:JSON.stringify(n)})},dr={user:!0,"user:email":!0,"read:user":!0},_=r=>r.some(n=>dr[n]),A=(r=!1,n=!1,e)=>`
24
24
  __typename
25
- ${j(e,["graphQLId"],"id")}
26
- ${j(e,["id"],"databaseId")}
27
- ${j(e,["name"],"name")}
28
- ${j(e,["name","username"],"login")}
29
- ${n?j(e,["email"],"email"):""}
30
- ${j(e,["avatarUrl"],`avatarUrl${r?"(size: $avatarSize)":""}`)}
31
- ${j(e,["url"],"url")}
25
+ ${M(e,["graphQLId"],"id")}
26
+ ${M(e,["id"],"databaseId")}
27
+ ${M(e,["name"],"name")}
28
+ ${M(e,["name","username"],"login")}
29
+ ${n?M(e,["email"],"email"):""}
30
+ ${M(e,["avatarUrl"],`avatarUrl${r?"(size: $avatarSize)":""}`)}
31
+ ${M(e,["url"],"url")}
32
32
  `,cr=(r=!1)=>`
33
33
  latestReviews(first: 100) {
34
34
  nodes {
@@ -37,7 +37,7 @@ latestReviews(first: 100) {
37
37
  ${A(!1,r)}
38
38
  }
39
39
  ... on EnterpriseUserAccount {
40
- ${Be(!1)}
40
+ ${je(!1)}
41
41
  }
42
42
  }
43
43
  state
@@ -50,7 +50,7 @@ databaseId
50
50
  login
51
51
  avatarUrl${r?"(size: $avatarSize)":""}
52
52
  url
53
- `,Be=(r=!1)=>`
53
+ `,je=(r=!1)=>`
54
54
  __typename
55
55
  id
56
56
  login
@@ -58,7 +58,7 @@ avatarUrl${r?"(size: $avatarSize)":""}
58
58
  url
59
59
  `,ye=(r,n=!1,e)=>`
60
60
  id
61
- ${!e||Z(e,"PR_ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
61
+ ${!e||F(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
62
62
  number
63
63
  title
64
64
  state
@@ -70,7 +70,7 @@ author {
70
70
  ${Lt(!1)}
71
71
  }
72
72
  ... on EnterpriseUserAccount {
73
- ${Be(!1)}
73
+ ${je(!1)}
74
74
  }
75
75
  }
76
76
  commits(last: 1) {
@@ -83,7 +83,7 @@ commits(last: 1) {
83
83
  contexts(first: 100) {
84
84
  totalCount
85
85
  nodes {
86
- ${!e||Z(e,"CHECK_RUN")?lr:""}
86
+ ${!e||F(e,"CHECK_RUN")?lr:""}
87
87
  ... on StatusContext {
88
88
  context
89
89
  createdAt
@@ -150,7 +150,7 @@ assignees(first: 100) {
150
150
  }
151
151
  reviewRequests(first: 100) {
152
152
  nodes {
153
- ${!e||Z(e,"AS_CODE_OWNER")?"asCodeOwner":""}
153
+ ${!e||F(e,"AS_CODE_OWNER")?"asCodeOwner":""}
154
154
  requestedReviewer {
155
155
  ... on User {
156
156
  ${A(!1,n)}
@@ -158,7 +158,7 @@ reviewRequests(first: 100) {
158
158
  }
159
159
  }
160
160
  }
161
- ${!e||Z(e,"LATEST_REVIEWS")?cr(n):""}
161
+ ${!e||F(e,"LATEST_REVIEWS")?cr(n):""}
162
162
  additions
163
163
  deletions
164
164
  changedFiles
@@ -172,10 +172,10 @@ labels(first: 100) {
172
172
  ${be}
173
173
  }
174
174
  }
175
- ${!e||Z(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
175
+ ${!e||F(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
176
176
  `,gr=(r=!1,n)=>`
177
177
  id
178
- ${!n||Z(n,"PR_ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
178
+ ${!n||F(n,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
179
179
  title
180
180
  author {
181
181
  ... on User {
@@ -185,7 +185,7 @@ author {
185
185
  ${Lt(!1)}
186
186
  }
187
187
  ... on EnterpriseUserAccount {
188
- ${Be(!1)}
188
+ ${je(!1)}
189
189
  }
190
190
  }
191
191
  closedAt
@@ -221,7 +221,7 @@ labels(first: 100) {
221
221
  ${be}
222
222
  }
223
223
  }
224
- `,mr={"-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"},hr=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),je=r=>{let n=[];return(r.match(hr)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let s=t.split(":")[0];mr[s]&&n.push(t)}}),n},Me=(r,n,e,t)=>{let s=r==="issue";return{query:`
224
+ `,mr={"-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"},hr=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Be=r=>{let n=[];return(r.match(hr)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let s=t.split(":")[0];mr[s]&&n.push(t)}}),n},Me=(r,n,e,t)=>{let s=r==="issue";return{query:`
225
225
  query SearchIssuesOrPullRequests($query: String! $after: String) {
226
226
  search(type:ISSUE query:$query first: ${t.maxPageSize} after:$after) {
227
227
  pageInfo {
@@ -238,10 +238,10 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
238
238
  \
239
239
  +`,Ut=(r,n,e,t)=>{let s=Ir.exec(r);if(!s||!s[0]||!s[1])return[];let o=parseInt(s[1],10),a=parseInt(s[2],10),i=r.replace(Rr,`
240
240
  +`).split(`
241
- `).slice(1),u=o-1,l=a-1,p=i.map(g=>{let m,h;switch(g[0]){case"-":{m="DELETED",u+=1,h=`${g.slice(1)}
242
- `;break}case"+":{m="ADDED",l+=1,h=`${g.slice(1)}
243
- `;break}default:m="UNMODIFIED",l+=1,u+=1,h=`${g}
244
- `}return{line:h,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=n;if(d!==null&&c!==null&&t!==null&&d<c){let g=0,m=p.length,h=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let I=0;I<p.length;I++){let f=p[I][h];f===d?g=I:f===c&&(m=I)}p=p.slice(g,m+1)}return p};var ze=`
241
+ `).slice(1),u=o-1,l=a-1,p=i.map(g=>{let m,I;switch(g[0]){case"-":{m="DELETED",u+=1,I=`${g.slice(1)}
242
+ `;break}case"+":{m="ADDED",l+=1,I=`${g.slice(1)}
243
+ `;break}default:m="UNMODIFIED",l+=1,u+=1,I=`${g}
244
+ `}return{line:I,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=n;if(d!==null&&c!==null&&t!==null&&d<c){let g=0,m=p.length,I=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let h=0;h<p.length;h++){let f=p[h][I];f===d?g=h:f===c&&(m=h)}p=p.slice(g,m+1)}return p};var ze=`
245
245
  id
246
246
  databaseId
247
247
  owner {
@@ -254,10 +254,10 @@ defaultBranchRef {
254
254
  name
255
255
  }
256
256
  viewerPermission
257
- `,Je={__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"},br={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},yr={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Pr={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},wr={OPEN:"OPEN",CLOSED:"CLOSED"},Sr=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Ke=r=>({color:`#${r.color}`,description:r.description,graphQLId:r.id,id:null,name:r.name}),vr=r=>({canCreateWebhook:r==="ADMIN",canPush:r==="ADMIN"||r==="MAINTAIN"||r==="WRITE",isAdmin:r==="ADMIN"}),We=r=>({id:r.databaseId.toString(),graphQLId:r.id,namespace:r.owner.login,name:r.name,webUrl:r.url,httpsUrl:r.url.endsWith(".git")?r.url:`${r.url}.git`,sshUrl:r.sshUrl,defaultBranch:r.defaultBranchRef,permissions:vr(r.viewerPermission)}),qr=r=>({canCreateWebhook:r.admin,canPush:r.admin||r.maintain||r.push,isAdmin:r.admin}),$t=r=>({id:r.id.toString(),graphQLId:r.node_id,namespace:r.owner.login,name:r.name,webUrl:r.html_url,httpsUrl:r.clone_url,sshUrl:r.ssh_url,defaultBranch:{name:r.default_branch},permissions:qr(r.permissions)}),Er=r=>({path:r.path,isDirectory:r.type==="tree"}),Cr={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Dr={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},O=(r,n=Dr)=>{let e={};return n.id&&(e.id="databaseId"in r?r.databaseId.toString():r.id),n.graphQLId&&(e.graphQLId=r.id),n.name&&(e.name=r.name??r.login),n.username&&(e.username=r.login),n.email&&(e.email=r.email??null),n.avatarUrl&&(e.avatarUrl=r.avatarUrl),n.url&&(e.url=r.url),e},Lr=(r,n)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return r!=="COMPLETED"?e[r]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[n]},Ur=r=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[r],He=r=>{var a,i,u,l,p,d,c,g,m,h,I,w;let n=null;r.author?n=r.author:n=Je;let e=(((a=r.reviewRequests)==null?void 0:a.nodes)||[]).filter(U).filter(f=>!f.asCodeOwner),t=(i=r.headRepository)==null?void 0:i.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let s=(u=r.repository)==null?void 0:u.url;s&&!s.endsWith(".git")&&(s=`${s}.git`);let o=e.filter(f=>f.requestedReviewer&&"__typename"in f.requestedReviewer).map(f=>({reviewer:O(f.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((((l=r.latestReviews)==null?void 0:l.nodes)||[]).filter(U).map(f=>{let v=Je;return f.author&&f.author.__typename&&(v=f.author),{reviewer:O(v),state:br[f.state]}}));return{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,title:r.title,number:r.number,state:Cr[r.state],commentCount:r.comments.totalCount,upvoteCount:r.reactions.totalCount,author:n&&n.__typename?O(n):null,createdDate:new Date(r.createdAt),isDraft:r.isDraft,repository:{id:r.repository.databaseId,graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login},remoteInfo:{cloneUrlHTTPS:s,cloneUrlSSH:r.repository.sshUrl}},headRepository:r.headRepository?{id:r.headRepository.databaseId,graphQLId:r.headRepository.id,name:r.headRepository.name,owner:{login:r.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:r.headRepository.sshUrl}}:null,headCommit:{buildStatuses:((g=(c=(d=(p=r.commits.nodes)==null?void 0:p.filter(U)[0])==null?void 0:d.commit.statusCheckRollup)==null?void 0:c.contexts.nodes)==null?void 0:g.filter(U).map(f=>"context"in f?{completedAt:null,description:f.description,name:f.context,state:Ur(f.state),startedAt:new Date(f.createdAt),stage:null,url:f.targetUrl}:{completedAt:f.completedAt?new Date(f.completedAt):null,description:null,name:f.name,state:Lr(f.status,f.conclusion),startedAt:f.startedAt?new Date(f.startedAt):null,stage:null,url:f.permalink}))??[]},headRef:r.headRef?{name:r.headRef.name,oid:((m=r.headRef.target)==null?void 0:m.oid)??null}:null,baseRef:r.baseRef?{name:r.baseRef.name,oid:((h=r.baseRef.target)==null?void 0:h.oid)??null}:null,url:r.url,updatedDate:new Date(r.updatedAt),closedDate:r.closedAt?new Date(r.closedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees.nodes?r.assignees.nodes.filter(U).map(f=>O(f)):null,reviews:o,reviewDecision:x(o),additions:r.additions,deletions:r.deletions,fileCount:r.changedFiles,commitCount:r.commits.totalCount,mergeableState:Pr[r.mergeStateStatus]??yr[r.mergeable],milestone:r.milestone?Ve(r.milestone):null,labels:((w=(I=r.labels)==null?void 0:I.nodes)==null?void 0:w.filter(U).map(Ke))??[],permissions:{canMerge:Sr.includes(r.repository.viewerPermission),canMergeAndBypassProtections:r.viewerCanMergeAsAdmin??!1}}},$r=r=>{var h,I;let{comments:n,isOutdated:e,isResolved:t,originalLine:s,originalStartLine:o,startDiffSide:a}=r,i=(h=n.nodes)==null?void 0:h[0];if(!i)return null;let{author:u,body:l,databaseId:p,id:d,path:c,publishedAt:g,url:m}=i;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:g?new Date(g):null,diffLines:Ut(i.diffHunk,s,o,a),id:p,isOutdated:e,isResolved:t,graphQLId:d,filename:c,replies:((I=n.nodes)==null?void 0:I.filter(U).slice(1).map(Ar))??[],url:m}},Ar=r=>({author:r.author?{avatarUrl:r.author.avatarUrl,email:null,name:r.author.login}:null,body:r.body,createdAt:r.publishedAt?new Date(r.publishedAt):null,graphQLId:r.id,id:r.databaseId,url:r.url}),Gr=r=>{var e,t,s;let n=null;return r.author?n=r.author:n=Je,{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,number:r.number,title:r.title,author:n&&n.__typename?O(n):null,commentCount:r.comments.totalCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:null,state:{name:wr[r.state],color:null},type:null,repository:{id:r.repository.databaseId,graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login}},url:r.url,updatedDate:new Date(r.updatedAt),assignees:((e=r.assignees.nodes)==null?void 0:e.filter(U).map(o=>O(o)))??[],upvoteCount:r.reactions.totalCount,milestone:r.milestone?Ve(r.milestone):null,labels:((s=(t=r.labels)==null?void 0:t.nodes)==null?void 0:s.filter(U).map(Ke))??[]}},Ve=r=>({id:r.number.toString(),graphQLId:r.id.toString(),number:r.number,title:r.title,description:r.description,isOpen:r.state=="OPEN",url:r.url,startDate:null,dueDate:r.dueOn?new Date(r.dueOn):null}),ee=class extends k{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let s=this._scopesCache[t];if(!s){let a=(await y(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];s=a?a.split(", "):[],this._scopesCache[t]=s}return s}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let s=this._enterpriseVersionsCache[t];if(!s){let o=await this.config.request({url:`${Y(this.config,e)}/meta`,headers:R(e.token||this.config.token)});if(!o.body.installed_version)return null;s=o.body.installed_version.split(".").slice(0,3).map(a=>parseInt(a,10)),this._enterpriseVersionsCache[t]=s}return s}getEnterpriseAvatarUrlIfNeeded(e,t,s){let o=s.baseUrl||this.config.baseUrl;return!o||o.startsWith(Ie)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){var u;if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let s=Rt(e.fields),o=await this.getScopes(t),a=await y(this.config,{query:`
257
+ `,Je={__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"},br={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},yr={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Pr={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},wr={OPEN:"OPEN",CLOSED:"CLOSED"},Sr=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Ve=r=>({color:`#${r.color}`,description:r.description,graphQLId:r.id,id:null,name:r.name}),vr=r=>({canCreateWebhook:r==="ADMIN",canPush:r==="ADMIN"||r==="MAINTAIN"||r==="WRITE",isAdmin:r==="ADMIN"}),We=r=>({id:r.databaseId.toString(),graphQLId:r.id,namespace:r.owner.login,name:r.name,webUrl:r.url,httpsUrl:r.url.endsWith(".git")?r.url:`${r.url}.git`,sshUrl:r.sshUrl,defaultBranch:r.defaultBranchRef,permissions:vr(r.viewerPermission)}),Er=r=>({canCreateWebhook:r.admin,canPush:r.admin||r.maintain||r.push,isAdmin:r.admin}),$t=r=>({id:r.id.toString(),graphQLId:r.node_id,namespace:r.owner.login,name:r.name,webUrl:r.html_url,httpsUrl:r.clone_url,sshUrl:r.ssh_url,defaultBranch:{name:r.default_branch},permissions:Er(r.permissions)}),qr=r=>({path:r.path,isDirectory:r.type==="tree"}),Cr={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Dr={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},O=(r,n=Dr)=>{let e={};return n.id&&(e.id="databaseId"in r?r.databaseId.toString():r.id),n.graphQLId&&(e.graphQLId=r.id),n.name&&(e.name=r.name??r.login),n.username&&(e.username=r.login),n.email&&(e.email=r.email??null),n.avatarUrl&&(e.avatarUrl=r.avatarUrl),n.url&&(e.url=r.url),e},Lr=(r,n)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return r!=="COMPLETED"?e[r]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[n]},Ur=r=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[r],He=r=>{var a,i,u,l,p,d,c,g,m,I,h,P;let n=null;r.author?n=r.author:n=Je;let e=(((a=r.reviewRequests)==null?void 0:a.nodes)||[]).filter($).filter(f=>!f.asCodeOwner),t=(i=r.headRepository)==null?void 0:i.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let s=(u=r.repository)==null?void 0:u.url;s&&!s.endsWith(".git")&&(s=`${s}.git`);let o=e.filter(f=>f.requestedReviewer&&"__typename"in f.requestedReviewer).map(f=>({reviewer:O(f.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((((l=r.latestReviews)==null?void 0:l.nodes)||[]).filter($).map(f=>{let v=Je;return f.author&&f.author.__typename&&(v=f.author),{reviewer:O(v),state:br[f.state]}}));return{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,title:r.title,number:r.number,state:Cr[r.state],commentCount:r.comments.totalCount,upvoteCount:r.reactions.totalCount,author:n&&n.__typename?O(n):null,createdDate:new Date(r.createdAt),isDraft:r.isDraft,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login},remoteInfo:{cloneUrlHTTPS:s,cloneUrlSSH:r.repository.sshUrl}},headRepository:r.headRepository?{id:r.headRepository.databaseId.toString(),graphQLId:r.headRepository.id,name:r.headRepository.name,owner:{login:r.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:r.headRepository.sshUrl}}:null,headCommit:{buildStatuses:((g=(c=(d=(p=r.commits.nodes)==null?void 0:p.filter($)[0])==null?void 0:d.commit.statusCheckRollup)==null?void 0:c.contexts.nodes)==null?void 0:g.filter($).map(f=>"context"in f?{completedAt:null,description:f.description,name:f.context,state:Ur(f.state),startedAt:new Date(f.createdAt),stage:null,url:f.targetUrl}:{completedAt:f.completedAt?new Date(f.completedAt):null,description:null,name:f.name,state:Lr(f.status,f.conclusion),startedAt:f.startedAt?new Date(f.startedAt):null,stage:null,url:f.permalink}))??[]},headRef:r.headRef?{name:r.headRef.name,oid:((m=r.headRef.target)==null?void 0:m.oid)??null}:null,baseRef:r.baseRef?{name:r.baseRef.name,oid:((I=r.baseRef.target)==null?void 0:I.oid)??null}:null,url:r.url,updatedDate:new Date(r.updatedAt),closedDate:r.closedAt?new Date(r.closedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:r.assignees.nodes?r.assignees.nodes.filter($).map(f=>O(f)):null,reviews:o,reviewDecision:x(o),additions:r.additions,deletions:r.deletions,fileCount:r.changedFiles,commitCount:r.commits.totalCount,mergeableState:Pr[r.mergeStateStatus]??yr[r.mergeable],milestone:r.milestone?Ke(r.milestone):null,labels:((P=(h=r.labels)==null?void 0:h.nodes)==null?void 0:P.filter($).map(Ve))??[],permissions:{canMerge:Sr.includes(r.repository.viewerPermission),canMergeAndBypassProtections:r.viewerCanMergeAsAdmin??!1}}},$r=r=>{var h,P;let{comments:n,isOutdated:e,isResolved:t,originalLine:s,originalStartLine:o,startDiffSide:a}=r,i=(h=n.nodes)==null?void 0:h[0];if(!i)return null;let{author:u,body:l,databaseId:p,fullDatabaseId:d,id:c,path:g,publishedAt:m,url:I}=i;return{author:u?{avatarUrl:u.avatarUrl,email:null,name:u.login}:null,body:l,createdAt:m?new Date(m):null,diffLines:Ut(i.diffHunk,s,o,a),id:d??p.toString(),isOutdated:e,isResolved:t,graphQLId:c,filename:g,replies:((P=n.nodes)==null?void 0:P.filter($).slice(1).map(Ar))??[],url:I}},Ar=r=>({author:r.author?{avatarUrl:r.author.avatarUrl,email:null,name:r.author.login}:null,body:r.body,createdAt:r.publishedAt?new Date(r.publishedAt):null,graphQLId:r.id,id:r.fullDatabaseId??r.databaseId.toString(),url:r.url}),Gr=r=>{var e,t,s;let n=null;return r.author?n=r.author:n=Je,{id:r.fullDatabaseId!==void 0?r.fullDatabaseId:r.databaseId.toString(),graphQLId:r.id,number:r.number,title:r.title,author:n&&n.__typename?O(n):null,commentCount:r.comments.totalCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:null,state:{name:wr[r.state],color:null},type:null,repository:{id:r.repository.databaseId.toString(),graphQLId:r.repository.id,name:r.repository.name,owner:{login:r.repository.owner.login}},url:r.url,updatedDate:new Date(r.updatedAt),assignees:((e=r.assignees.nodes)==null?void 0:e.filter($).map(o=>O(o)))??[],upvoteCount:r.reactions.totalCount,milestone:r.milestone?Ke(r.milestone):null,labels:((s=(t=r.labels)==null?void 0:t.nodes)==null?void 0:s.filter($).map(Ve))??[]}},Ke=r=>({id:r.number.toString(),graphQLId:r.id.toString(),number:r.number,title:r.title,description:r.description,isOpen:r.state=="OPEN",url:r.url,startDate:null,dueDate:r.dueOn?new Date(r.dueOn):null}),ee=class extends k{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let s=this._scopesCache[t];if(!s){let a=(await y(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];s=a?a.split(", "):[],this._scopesCache[t]=s}return s}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let s=this._enterpriseVersionsCache[t];if(!s){let o=await this.config.request({url:`${Y(this.config,e)}/meta`,headers:R(e.token||this.config.token)});if(!o.body.installed_version)return null;s=o.body.installed_version.split(".").slice(0,3).map(a=>parseInt(a,10)),this._enterpriseVersionsCache[t]=s}return s}getEnterpriseAvatarUrlIfNeeded(e,t,s){let o=s.baseUrl||this.config.baseUrl;return!o||o.startsWith(Ie)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){var u;if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let s=Rt(e.fields),o=await this.getScopes(t),a=await y(this.config,{query:`
258
258
  query getCurrentUser {
259
259
  viewer {
260
- ${A(!1,F(o),s)}
260
+ ${A(!1,_(o),s)}
261
261
  }
262
262
  }
263
263
  `},t),i=(u=a.body.data)==null?void 0:u.viewer;if(!i)throw new b("Current user not found.",a.body.errors);return{data:O(i,s)}}async getAccountsForRepo(e,t={}){var l,p,d,c,g;let s=await this.getScopes(t),{repo:{namespace:o,name:a},cursor:i}=e,u=await y(this.config,{query:`
@@ -265,7 +265,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
265
265
  repository(owner: $owner, name: $name) {
266
266
  assignableUsers(first: $first, after: $cursor) {
267
267
  nodes {
268
- ${A(!1,F(s))}
268
+ ${A(!1,_(s))}
269
269
  }
270
270
  pageInfo {
271
271
  endCursor
@@ -325,7 +325,7 @@ query getAccountForEmail($query: String! $avatarSize: Int) {
325
325
  search(query: $query, type: USER, first: 1) {
326
326
  nodes {
327
327
  ... on User {
328
- ${A(!0,F(s))}
328
+ ${A(!0,_(s))}
329
329
  }
330
330
  }
331
331
  }
@@ -333,7 +333,7 @@ query getAccountForEmail($query: String! $avatarSize: Int) {
333
333
  `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},t),a=(l=(u=(i=o.body.data)==null?void 0:i.search)==null?void 0:u.nodes)==null?void 0:l[0];if(!a)throw new b("Could not find user via email",o.body.errors);return{data:O({...a,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(a.avatarUrl,a.email,t)})}}async getAccountForUsername(e,t={}){var i;let s=await this.getScopes(t),o=await y(this.config,{query:`
334
334
  query getUserForUsername($login: String! $avatarSize: Int) {
335
335
  user(login: $login) {
336
- ${A(!0,F(s))}
336
+ ${A(!0,_(s))}
337
337
  }
338
338
  }
339
339
  `,variables:{login:e.username,avatarSize:e.avatarSize}},t),a=(i=o.body.data)==null?void 0:i.user;if(!a)throw new b("Could not find user via username",o.body.errors);return{data:O({...a,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(a.avatarUrl,a.email,t)})}}async getOrgsForCurrentUser(e={},t={}){let s=await y(this.config,{query:`
@@ -371,7 +371,7 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
371
371
  }
372
372
  }
373
373
  }
374
- `,variables:{cursor:e.cursor,first:C,login:e.org}},t);if(!((i=(a=s.body.data)==null?void 0:a.viewer.organization)!=null&&i.membersWithRole)&&((u=s.body.errors)!=null&&u.length))throw new b("Could not read the members of the organization",s.body.errors);let o=((p=(l=s.body.data)==null?void 0:l.viewer.organization)==null?void 0:p.membersWithRole.nodes)||[];return{pageInfo:{hasNextPage:((c=(d=s.body.data)==null?void 0:d.viewer.organization)==null?void 0:c.membersWithRole.pageInfo.hasNextPage)??!1,endCursor:((m=(g=s.body.data)==null?void 0:g.viewer.organization)==null?void 0:m.membersWithRole.pageInfo.endCursor)??null},data:o.map(h=>O({...h,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(h.avatarUrl,h.email,t)}))}}async getRepo(e,t={}){var o;let s=await y(this.config,{query:`
374
+ `,variables:{cursor:e.cursor,first:C,login:e.org}},t);if(!((i=(a=s.body.data)==null?void 0:a.viewer.organization)!=null&&i.membersWithRole)&&((u=s.body.errors)!=null&&u.length))throw new b("Could not read the members of the organization",s.body.errors);let o=((p=(l=s.body.data)==null?void 0:l.viewer.organization)==null?void 0:p.membersWithRole.nodes)||[];return{pageInfo:{hasNextPage:((c=(d=s.body.data)==null?void 0:d.viewer.organization)==null?void 0:c.membersWithRole.pageInfo.hasNextPage)??!1,endCursor:((m=(g=s.body.data)==null?void 0:g.viewer.organization)==null?void 0:m.membersWithRole.pageInfo.endCursor)??null},data:o.map(I=>O({...I,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(I.avatarUrl,I.email,t)}))}}async getRepo(e,t={}){var o;let s=await y(this.config,{query:`
375
375
  query getRepo($owner: String!, $name: String!) {
376
376
  repository(owner: $owner, name: $name) {
377
377
  ${ze}
@@ -460,7 +460,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
460
460
  }
461
461
  }
462
462
  }
463
- `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=(i=s.body.data)==null?void 0:i.repository;if(!o)throw new b("Blame repository not found.",s.body.errors);let a=o.object;if(!a||!("blame"in a))throw new b("Ref not found.",s.body.errors);if(a.blame.ranges.length===0)throw new b("File not found.",s.body.errors);return{data:{ranges:a.blame.ranges.map(u=>{var l;return{startingLine:u.startingLine,endingLine:u.endingLine,commit:{oid:u.commit.oid,parentOids:((l=u.commit.parents.nodes)==null?void 0:l.map(p=>p.oid))||[],authoredDate:new Date(u.commit.authoredDate),author:u.commit.author?{name:u.commit.author.name,email:u.commit.author.email,avatarUrl:u.commit.author.avatarUrl}:null,committedDate:new Date(u.commit.committedDate),committer:u.commit.committer?{name:u.commit.committer.name,email:u.commit.committer.email,avatarUrl:u.commit.committer.avatarUrl}:null,message:u.commit.message,fileCount:u.commit.changedFilesIfAvailable,additions:u.commit.additions,deletions:u.commit.deletions}}})}}}async getFileContents(e,t={}){let s=await this.config.request({url:`${Y(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(s.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!s.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${s.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([s.body])}}async searchPullRequests(e,t={}){var p;let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=F(o),i=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Me("pr",c,e.cursor,{maxPageSize:e.maxPageSize??Et,supportsEmail:a,supportsDrafts:d,enterpriseVersion:s,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await y(this.config,i(!0),t);u.body.errors&&Pe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await y(this.config,i(!1),t));let{data:l}=u.body;if(!l)throw new b("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:((p=l.search.nodes)==null?void 0:p.filter(U).map(He))||[]}}async searchIssues(e,t={}){var l;let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=F(o),i=await y(this.config,Me("issue",e.query,e.cursor,{supportsEmail:a,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??Ct,enterpriseVersion:s}),t),{data:u}=i.body;if(!u)throw new b("Could not search issues",i.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:((l=u.search.nodes)==null?void 0:l.filter(U).map(Gr))||[]}}async getPullRequestsAssociatedWithUser(e,t={}){var o;let s=[`involves:${e.username}`];return(o=e.repos)!=null&&o.length&&e.repos.forEach(a=>{s.push(`repo:${a.namespace}/${a.name}`)}),e.labelNames&&e.labelNames.forEach(a=>{s.push(`label:"${a}"`)}),this.searchPullRequests({query:s.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:s,updatedBefore:o,authorLogin:a,repos:i,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=je(l||"");return i.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),s&&s.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),a&&g.push(`author:${a}`),u&&g.push(`review-requested:${u}`),p&&g.push(`mentions:${p}`),d&&d.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c},t)}async getPullRequestForRepo(e,t={}){var d;let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=F(o),i=c=>({query:`query getPullRequest(
463
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=(i=s.body.data)==null?void 0:i.repository;if(!o)throw new b("Blame repository not found.",s.body.errors);let a=o.object;if(!a||!("blame"in a))throw new b("Ref not found.",s.body.errors);if(a.blame.ranges.length===0)throw new b("File not found.",s.body.errors);return{data:{ranges:a.blame.ranges.map(u=>{var l;return{startingLine:u.startingLine,endingLine:u.endingLine,commit:{oid:u.commit.oid,parentOids:((l=u.commit.parents.nodes)==null?void 0:l.map(p=>p.oid))||[],authoredDate:new Date(u.commit.authoredDate),author:u.commit.author?{name:u.commit.author.name,email:u.commit.author.email,avatarUrl:u.commit.author.avatarUrl}:null,committedDate:new Date(u.commit.committedDate),committer:u.commit.committer?{name:u.commit.committer.name,email:u.commit.committer.email,avatarUrl:u.commit.committer.avatarUrl}:null,message:u.commit.message,fileCount:u.commit.changedFilesIfAvailable,additions:u.commit.additions,deletions:u.commit.deletions}}})}}}async getFileContents(e,t={}){let s=await this.config.request({url:`${Y(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...R(t.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(s.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!s.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${s.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([s.body])}}async searchPullRequests(e,t={}){var p;let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=_(o),i=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Me("pr",c,e.cursor,{maxPageSize:e.maxPageSize??qt,supportsEmail:a,supportsDrafts:d,enterpriseVersion:s,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await y(this.config,i(!0),t);u.body.errors&&Pe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await y(this.config,i(!1),t));let{data:l}=u.body;if(!l)throw new b("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:((p=l.search.nodes)==null?void 0:p.filter($).map(He))||[]}}async searchIssues(e,t={}){var l;let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=_(o),i=await y(this.config,Me("issue",e.query,e.cursor,{supportsEmail:a,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??Ct,enterpriseVersion:s}),t),{data:u}=i.body;if(!u)throw new b("Could not search issues",i.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:((l=u.search.nodes)==null?void 0:l.filter($).map(Gr))||[]}}async getPullRequestsAssociatedWithUser(e,t={}){var o;let s=[`involves:${e.username}`];return(o=e.repos)!=null&&o.length&&e.repos.forEach(a=>{s.push(`repo:${a.namespace}/${a.name}`)}),e.labelNames&&e.labelNames.forEach(a=>{s.push(`label:"${a}"`)}),this.searchPullRequests({query:s.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:s,updatedBefore:o,authorLogin:a,repos:i,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:d,maxPageSize:c}=e,g=Be(l||"");return i.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),s&&s.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),a&&g.push(`author:${a}`),u&&g.push(`review-requested:${u}`),p&&g.push(`mentions:${p}`),d&&d.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c},t)}async getPullRequestForRepo(e,t={}){var d;let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=_(o),i=c=>({query:`query getPullRequest(
464
464
  $owner: String!
465
465
  $name: String!
466
466
  $number: Int!
@@ -473,7 +473,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
473
473
  ${ye(c,a,s)}
474
474
  }
475
475
  }
476
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await y(this.config,i(!0),t);u.body.errors&&Pe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await y(this.config,i(!1),t));let{data:l}=u.body;if(!l)throw new b("Could not fetch pull request by number",u.body.errors);let p=(d=u.body.data)==null?void 0:d.repository.pullRequest;return{data:p?He(p):null}}async getPullRequestByGraphQLId(e,t={}){var d;let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=F(o),i=c=>({query:`query getPullRequest(
476
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await y(this.config,i(!0),t);u.body.errors&&Pe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await y(this.config,i(!1),t));let{data:l}=u.body;if(!l)throw new b("Could not fetch pull request by number",u.body.errors);let p=(d=u.body.data)==null?void 0:d.repository.pullRequest;return{data:p?He(p):null}}async getPullRequestByGraphQLId(e,t={}){var d;let s=await this.getEnterpriseVersion(t),o=await this.getScopes(t),a=_(o),i=c=>({query:`query getPullRequest(
477
477
  $graphQLId: ID!
478
478
  ) {
479
479
  node(id: $graphQLId) {
@@ -537,7 +537,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
537
537
  id
538
538
  }
539
539
  }
540
- }`,u=await y(this.config,{query:i,variables:{pullRequestGraphQLId:s.graphQLId,assigneeGraphQLIds:a}},t);if(!((d=(p=(l=u.body.data)==null?void 0:l.updatePullRequest)==null?void 0:p.pullRequest)!=null&&d.id))throw new b("Could not set pull request assignees",u.body.errors)}async getReviewsForPullRequest(e,t={}){var d,c,g,m;let{repo:{namespace:s,name:o},pullRequestId:a}=e,i=`query getPullRequests(
540
+ }`,u=await y(this.config,{query:i,variables:{pullRequestGraphQLId:s.graphQLId,assigneeGraphQLIds:a}},t);if(!((d=(p=(l=u.body.data)==null?void 0:l.updatePullRequest)==null?void 0:p.pullRequest)!=null&&d.id))throw new b("Could not set pull request assignees",u.body.errors)}async getReviewsForPullRequest(e,t={}){var c,g,m,I;let s=await this.getEnterpriseVersion(t),{repo:{namespace:o,name:a},pullRequestId:i}=e,u=`query getPullRequests(
541
541
  $namespace: String!
542
542
  $name: String!
543
543
  $pullRequestId: Int!
@@ -561,7 +561,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
561
561
  login
562
562
  }
563
563
  body
564
- databaseId
564
+ ${!s||F(s,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
565
565
  diffHunk
566
566
  id
567
567
  path
@@ -581,7 +581,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
581
581
  login
582
582
  }
583
583
  body
584
- databaseId
584
+ ${!s||F(s,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
585
585
  id
586
586
  publishedAt
587
587
  url
@@ -589,13 +589,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
589
589
  }
590
590
  }
591
591
  }
592
- }`,u=await y(this.config,{query:i,variables:{namespace:s,name:o,pullRequestId:a}},t),l=((c=(d=u.body.data)==null?void 0:d.repository.pullRequest.reviewThreads.nodes)==null?void 0:c.filter(U).reduce((h,I)=>{var v,G;if(!((G=(v=I.comments.nodes)==null?void 0:v[0])!=null&&G.pullRequestReview))return h;let w=I.comments.nodes[0].pullRequestReview,f=$r(I);return f&&(h[w.id]||(h[w.id]=[]),h[w.id].push(f)),h},{}))??{};return{data:((m=(g=u.body.data)==null?void 0:g.repository.pullRequest.reviews.nodes)==null?void 0:m.filter(U).filter(h=>l[h.id]).map(h=>({author:h.author?{avatarUrl:h.author.avatarUrl,email:null,name:h.author.login}:null,body:h.body,createdAt:h.publishedAt?new Date(h.publishedAt):null,id:h.databaseId,graphQLId:h.id,reviewComments:l[h.id],url:h.url})))??[]}}async getIssuesAssociatedWithUser(e,t={}){var c;let[s,o]=((c=e.cursor)==null?void 0:c.split(";"))||[void 0,void 0],a=[];e.labelNames&&e.labelNames.forEach(g=>{a.push(`label:"${g}"`)});let[i,u]=await Promise.all([s==="null"?null:this.searchIssues({query:`author:${e.username} ${a.join(" ")}`,cursor:s,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${a.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)]),l={},p=[],d=g=>{l[g.id]||(l[g.id]=!0,p.push(g))};return i==null||i.data.forEach(d),u==null||u.data.forEach(d),{pageInfo:{hasNextPage:(i==null?void 0:i.pageInfo.hasNextPage)||(u==null?void 0:u.pageInfo.hasNextPage)||!1,endCursor:`${(i==null?void 0:i.pageInfo.hasNextPage)&&(i==null?void 0:i.pageInfo.endCursor)||"null"};${(u==null?void 0:u.pageInfo.hasNextPage)&&(u==null?void 0:u.pageInfo.endCursor)||"null"}`},data:p}}async setPullRequestLabels(e,t={}){var u,l,p;let{pullRequest:s,labels:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
592
+ }`,l=await y(this.config,{query:u,variables:{namespace:o,name:a,pullRequestId:i}},t),p=((g=(c=l.body.data)==null?void 0:c.repository.pullRequest.reviewThreads.nodes)==null?void 0:g.filter($).reduce((h,P)=>{var G,D;if(!((D=(G=P.comments.nodes)==null?void 0:G[0])!=null&&D.pullRequestReview))return h;let f=P.comments.nodes[0].pullRequestReview,v=$r(P);return v&&(h[f.id]||(h[f.id]=[]),h[f.id].push(v)),h},{}))??{};return{data:((I=(m=l.body.data)==null?void 0:m.repository.pullRequest.reviews.nodes)==null?void 0:I.filter($).filter(h=>p[h.id]).map(h=>({author:h.author?{avatarUrl:h.author.avatarUrl,email:null,name:h.author.login}:null,body:h.body,createdAt:h.publishedAt?new Date(h.publishedAt):null,id:h.fullDatabaseId??h.databaseId.toString(),graphQLId:h.id,reviewComments:p[h.id],url:h.url})))??[]}}async getIssuesAssociatedWithUser(e,t={}){var c;let[s,o]=((c=e.cursor)==null?void 0:c.split(";"))||[void 0,void 0],a=[];e.labelNames&&e.labelNames.forEach(g=>{a.push(`label:"${g}"`)});let[i,u]=await Promise.all([s==="null"?null:this.searchIssues({query:`author:${e.username} ${a.join(" ")}`,cursor:s,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${a.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)]),l={},p=[],d=g=>{l[g.id]||(l[g.id]=!0,p.push(g))};return i==null||i.data.forEach(d),u==null||u.data.forEach(d),{pageInfo:{hasNextPage:(i==null?void 0:i.pageInfo.hasNextPage)||(u==null?void 0:u.pageInfo.hasNextPage)||!1,endCursor:`${(i==null?void 0:i.pageInfo.hasNextPage)&&(i==null?void 0:i.pageInfo.endCursor)||"null"};${(u==null?void 0:u.pageInfo.hasNextPage)&&(u==null?void 0:u.pageInfo.endCursor)||"null"}`},data:p}}async setPullRequestLabels(e,t={}){var u,l,p;let{pullRequest:s,labels:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
593
593
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
594
594
  pullRequest {
595
595
  id
596
596
  }
597
597
  }
598
- }`,i=await y(this.config,{query:a,variables:{pullRequestGraphQLId:s.graphQLId,labelGraphQLIds:o.map(d=>{if(!d.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return d.graphQLId})}},t);if(!((p=(l=(u=i.body.data)==null?void 0:u.updatePullRequest)==null?void 0:l.pullRequest)!=null&&p.id))throw new b("Could not set pull request labels",i.body.errors)}async getIssuesForRepos(e,t={}){let s=je(e.startQuery||""),{cursor:o,assigneeLogins:a,updatedBefore:i,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(d=>{s.push(`repo:${d.namespace}/${d.name}`)}),a&&a.forEach(d=>{s.push(`assignee:${d}`)}),i&&s.push(`updated:<${i}`),u&&s.push(`author:${u}`),l&&s.push(`mentions:${l}`),p&&p.forEach(d=>{s.push(`label:"${d}"`)}),this.searchIssues({query:`sort:updated ${s.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async closeIssueWithReason(e,t={}){var u,l,p;let{issue:s,reason:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
598
+ }`,i=await y(this.config,{query:a,variables:{pullRequestGraphQLId:s.graphQLId,labelGraphQLIds:o.map(d=>{if(!d.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return d.graphQLId})}},t);if(!((p=(l=(u=i.body.data)==null?void 0:u.updatePullRequest)==null?void 0:l.pullRequest)!=null&&p.id))throw new b("Could not set pull request labels",i.body.errors)}async getIssuesForRepos(e,t={}){let s=Be(e.startQuery||""),{cursor:o,assigneeLogins:a,updatedBefore:i,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(d=>{s.push(`repo:${d.namespace}/${d.name}`)}),a&&a.forEach(d=>{s.push(`assignee:${d}`)}),i&&s.push(`updated:<${i}`),u&&s.push(`author:${u}`),l&&s.push(`mentions:${l}`),p&&p.forEach(d=>{s.push(`label:"${d}"`)}),this.searchIssues({query:`sort:updated ${s.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async closeIssueWithReason(e,t={}){var u,l,p;let{issue:s,reason:o}=e;if(!s.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let a=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
599
599
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
600
600
  issue {
601
601
  id
@@ -645,7 +645,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
645
645
  }
646
646
  }
647
647
  }
648
- `,variables:{owner:s,name:o,cursor:a,first:C}},t);if(!i.body.data)throw new b("Could not fetch milestones",i.body.errors);return{pageInfo:((u=i.body.data.repository.milestones)==null?void 0:u.pageInfo)??{endCursor:null,hasNextPage:!1},data:((p=(l=i.body.data.repository.milestones)==null?void 0:l.nodes)==null?void 0:p.map(Ve))??[]}}async getLabelsForRepo(e,t={}){var u,l,p;let{repo:{namespace:s,name:o},cursor:a}=e,i=await y(this.config,{query:`
648
+ `,variables:{owner:s,name:o,cursor:a,first:C}},t);if(!i.body.data)throw new b("Could not fetch milestones",i.body.errors);return{pageInfo:((u=i.body.data.repository.milestones)==null?void 0:u.pageInfo)??{endCursor:null,hasNextPage:!1},data:((p=(l=i.body.data.repository.milestones)==null?void 0:l.nodes)==null?void 0:p.map(Ke))??[]}}async getLabelsForRepo(e,t={}){var u,l,p;let{repo:{namespace:s,name:o},cursor:a}=e,i=await y(this.config,{query:`
649
649
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
650
650
  repository(owner: $owner, name: $name) {
651
651
  labels(first: $first, after: $cursor) {
@@ -659,7 +659,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
659
659
  }
660
660
  }
661
661
  }
662
- `,variables:{owner:s,name:o,cursor:a,first:C}},t);if(!i.body.data)throw new b("Could not fetch labels",i.body.errors);return{pageInfo:((u=i.body.data.repository.labels)==null?void 0:u.pageInfo)??{endCursor:null,hasNextPage:!1},data:((p=(l=i.body.data.repository.labels)==null?void 0:l.nodes)==null?void 0:p.map(Ke))??[]}}async getTreeForRepo(e,t={}){let s=await this.config.request({url:`${Y(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...R(t.token||this.config.token)}});if(!s.body)throw new Error("Could not fetch trees");return{data:s.body.tree.map(Er)}}};var Tr="https://gitlab.com/api/v4",Or="https://gitlab.com/api/graphql",Xe=/\/api\/v\d+$/,Gt=r=>{if(r.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.")},we=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Gt(e),Xe.test(e)||(e=e+"/api/v4"),e):Tr},xr=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Gt(e),Xe.test(e)&&(e=e.replace(Xe,"")),`${e}/api/graphql`):Or},P=(r,n,e)=>{let t=R(e.token||r.token);return r.request({url:xr(r,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(n)})},Se=r=>r==null?void 0:r.map(n=>`"${n.message}"`).join(", ");var rt=r=>r.split("/").slice(0,-1).join("/"),st=r=>r.split("/").at(-1)??"",ve=r=>({id:r.id.replace(te,""),graphQLId:r.id,namespace:rt(r.fullPath),name:st(r.fullPath),webUrl:r.webUrl}),Tt=r=>({id:r.id.replace(te,""),graphQLId:r.id,httpsUrl:r.httpUrlToRepo,namespace:rt(r.fullPath),name:st(r.fullPath),sshUrl:r.sshUrlToRepo,webUrl:r.webUrl}),kr={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Nr={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Fr="gid://gitlab/User/",te="gid://gitlab/Project/",Qr="gid://gitlab/MergeRequest/",_r="gid://gitlab/Issue/",Br="gid://gitlab/ProjectLabel/",jr="gid://gitlab/Milestone/",Mr="gid://gitlab/Ci::Build/",nt=`
662
+ `,variables:{owner:s,name:o,cursor:a,first:C}},t);if(!i.body.data)throw new b("Could not fetch labels",i.body.errors);return{pageInfo:((u=i.body.data.repository.labels)==null?void 0:u.pageInfo)??{endCursor:null,hasNextPage:!1},data:((p=(l=i.body.data.repository.labels)==null?void 0:l.nodes)==null?void 0:p.map(Ve))??[]}}async getTreeForRepo(e,t={}){let s=await this.config.request({url:`${Y(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...R(t.token||this.config.token)}});if(!s.body)throw new Error("Could not fetch trees");return{data:s.body.tree.map(qr)}}};var Tr="https://gitlab.com/api/v4",Or="https://gitlab.com/api/graphql",Xe=/\/api\/v\d+$/,Gt=r=>{if(r.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.")},we=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Gt(e),Xe.test(e)||(e=e+"/api/v4"),e):Tr},xr=(r,n)=>{let e=n.baseUrl||r.baseUrl;return e?(e=e.replace(/\/$/,""),Gt(e),Xe.test(e)&&(e=e.replace(Xe,"")),`${e}/api/graphql`):Or},w=(r,n,e)=>{let t=R(e.token||r.token);return r.request({url:xr(r,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(n)})},Se=r=>r==null?void 0:r.map(n=>`"${n.message}"`).join(", ");var rt=r=>r.split("/").slice(0,-1).join("/"),st=r=>r.split("/").at(-1)??"",ve=r=>({id:r.id.replace(te,""),graphQLId:r.id,namespace:rt(r.fullPath),name:st(r.fullPath),webUrl:r.webUrl}),Tt=r=>({id:r.id.replace(te,""),graphQLId:r.id,httpsUrl:r.httpUrlToRepo,namespace:rt(r.fullPath),name:st(r.fullPath),sshUrl:r.sshUrlToRepo,webUrl:r.webUrl}),kr={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Nr={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Fr="gid://gitlab/User/",te="gid://gitlab/Project/",_r="gid://gitlab/MergeRequest/",Qr="gid://gitlab/Issue/",jr="gid://gitlab/ProjectLabel/",Br="gid://gitlab/Milestone/",Mr="gid://gitlab/Ci::Build/",nt=`
663
663
  description
664
664
  dueDate
665
665
  id
@@ -790,13 +790,13 @@ labels {
790
790
  ${r?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
791
791
  ${n?`milestone { ${nt} }`:""}
792
792
  ${e?`headPipeline { ${zr} }`:""}
793
- `,M=r=>`${r.namespace}/${r.name}`,Wr=r=>`${r.namespace}/${r.name}`,Hr=r=>({canCreateWebhook:r.adminOperations,canPush:r.pushCode,isAdmin:r.adminOperations}),et=r=>{var n;return{id:r.id.replace(te,""),graphQLId:r.id,namespace:rt(r.fullPath),name:st(r.fullPath),webUrl:r.webUrl,httpsUrl:r.httpUrlToRepo,sshUrl:r.sshUrlToRepo,defaultBranch:(n=r.repository)!=null&&n.rootRef?{name:r.repository.rootRef}:null,permissions:Hr(r.userPermissions)}},Jr=r=>({path:r.path,isDirectory:r.type==="tree"}),Kr={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},_=(r,n,e)=>{let t=r.avatarUrl;return!n&&(t!=null&&t.startsWith("/"))?t=`https://gitlab.com${t}`:n&&(t!=null&&t.startsWith("/"))&&e&&(t=`${e.replace(/\/+?$/,"")}${t}`),{id:r.id.replace(Fr,""),graphQLId:r.id,name:r.name,username:r.username,email:r.publicEmail??null,avatarUrl:t,url:r.webUrl}},at=r=>({color:r.color,description:r.description,id:r.id.replace(Br,""),graphQLId:r.id,name:r.title}),Vr=(r,n)=>r?r==="FAILED"&&n?"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"}[r]:null,Xr=(r,n,e)=>{var s;let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:_(r,n,e),state:(s=r.mergeRequestInteraction)!=null&&s.reviewState?t[r.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},xt=(r,n,e,t,s)=>{var a,i,u,l,p,d,c,g,m,h,I,w;let o=(a=r.reviewers)!=null&&a.nodes?r.reviewers.nodes.map(f=>Xr(f,t,s)):null;return{id:r.id.replace(Qr,""),graphQLId:r.id,title:r.title,number:parseInt(r.iid,10),state:Kr[r.state],commentCount:r.userNotesCount||0,upvoteCount:r.upvotes,author:r.author?_(r.author,t,s):null,createdDate:new Date(r.createdAt),isDraft:r.draft,repository:{id:n.id,graphQLId:n.graphQLId,name:n.name,owner:{login:n.namespace},remoteInfo:n.httpsUrl&&n.sshUrl?{cloneUrlHTTPS:n.httpsUrl,cloneUrlSSH:n.sshUrl}:null},headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:((l=(u=(i=r.headPipeline)==null?void 0:i.stages)==null?void 0:u.nodes)==null?void 0:l.flatMap(f=>{var v,G;return((G=(v=f.jobs)==null?void 0:v.nodes)==null?void 0:G.map($=>({completedAt:$.finishedAt?new Date($.finishedAt):null,description:null,name:$.name??null,state:Vr($.status,$.allowFailure),stage:f.name??null,startedAt:new Date($.createdAt),url:`${n.webUrl}/-/jobs/${$.id.replace(Mr,"")}`})))??[]}))??[]},baseRef:{name:r.targetBranch,oid:((p=r.diffRefs)==null?void 0:p.baseSha)??null},headRef:{name:r.sourceBranch,oid:((d=r.diffRefs)==null?void 0:d.headSha)??null},url:r.webUrl,updatedDate:new Date(r.updatedAt),closedDate:r.mergedAt?new Date(r.mergedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:(c=r.assignees)!=null&&c.nodes?r.assignees.nodes.map(f=>_(f,t,s)):null,reviews:o,reviewDecision:x(o),additions:((g=r.diffStatsSummary)==null?void 0:g.additions)||0,deletions:((m=r.diffStatsSummary)==null?void 0:m.deletions)||0,fileCount:((h=r.diffStatsSummary)==null?void 0:h.fileCount)||0,commitCount:r.commitCount||0,mergeableState:Nr[r.mergeStatusEnum],milestone:r.milestone?it(r.milestone,n.webUrl):null,labels:((w=(I=r.labels)==null?void 0:I.nodes)==null?void 0:w.map(at))??[],permissions:null}},tt=(r,n,e,t)=>{var s,o;return{author:_(r.author,e,t),assignees:r.assignees.nodes.map(a=>_(a,e,t)),commentCount:r.userNotesCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:r.description,graphQLId:r.id,id:r.id.replace(_r,""),labels:((o=(s=r.labels)==null?void 0:s.nodes)==null?void 0:o.map(at))??[],number:r.iid,repository:{id:n.id.replace(te,""),graphQLId:n.id,name:n.name,owner:{login:n.namespace}},updatedDate:new Date(r.updatedAt),upvoteCount:r.upvotes,state:{name:r.state,color:null},type:r.type,title:r.title,url:r.webUrl,milestone:r.milestone?it(r.milestone,n.webUrl):null}},it=(r,n)=>({id:r.id.replace(jr,""),graphQLId:r.id,number:parseInt(r.iid,10),title:r.title,description:r.description,isOpen:r.state==="active",url:`${n}/-/${r.webPath.replace(/.+?\/-\//,"")}`,startDate:r.startDate?new Date(r.startDate):null,dueDate:r.dueDate?new Date(r.dueDate):null}),re=class extends k{getIsSelfHosted(n){return!!n.baseUrl||!!this.config.baseUrl}async getCurrentUser(n={},e={}){var o;let s=(o=(await P(this.config,{query:`
793
+ `,z=r=>`${r.namespace}/${r.name}`,Wr=r=>`${r.namespace}/${r.name}`,Hr=r=>({canCreateWebhook:r.adminOperations,canPush:r.pushCode,isAdmin:r.adminOperations}),et=r=>{var n;return{id:r.id.replace(te,""),graphQLId:r.id,namespace:rt(r.fullPath),name:st(r.fullPath),webUrl:r.webUrl,httpsUrl:r.httpUrlToRepo,sshUrl:r.sshUrlToRepo,defaultBranch:(n=r.repository)!=null&&n.rootRef?{name:r.repository.rootRef}:null,permissions:Hr(r.userPermissions)}},Jr=r=>({path:r.path,isDirectory:r.type==="tree"}),Vr={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},j=(r,n,e)=>{let t=r.avatarUrl;return!n&&(t!=null&&t.startsWith("/"))?t=`https://gitlab.com${t}`:n&&(t!=null&&t.startsWith("/"))&&e&&(t=`${e.replace(/\/+?$/,"")}${t}`),{id:r.id.replace(Fr,""),graphQLId:r.id,name:r.name,username:r.username,email:r.publicEmail??null,avatarUrl:t,url:r.webUrl}},at=r=>({color:r.color,description:r.description,id:r.id.replace(jr,""),graphQLId:r.id,name:r.title}),Kr=(r,n)=>r?r==="FAILED"&&n?"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"}[r]:null,Xr=(r,n,e)=>{var s;let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:j(r,n,e),state:(s=r.mergeRequestInteraction)!=null&&s.reviewState?t[r.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},xt=(r,n,e,t,s)=>{var a,i,u,l,p,d,c,g,m,I,h,P;let o=(a=r.reviewers)!=null&&a.nodes?r.reviewers.nodes.map(f=>Xr(f,t,s)):null;return{id:r.id.replace(_r,""),graphQLId:r.id,title:r.title,number:parseInt(r.iid,10),state:Vr[r.state],commentCount:r.userNotesCount||0,upvoteCount:r.upvotes,author:r.author?j(r.author,t,s):null,createdDate:new Date(r.createdAt),isDraft:r.draft,repository:{id:n.id,graphQLId:n.graphQLId,name:n.name,owner:{login:n.namespace},remoteInfo:n.httpsUrl&&n.sshUrl?{cloneUrlHTTPS:n.httpsUrl,cloneUrlSSH:n.sshUrl}:null},headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:((l=(u=(i=r.headPipeline)==null?void 0:i.stages)==null?void 0:u.nodes)==null?void 0:l.flatMap(f=>{var v,G;return((G=(v=f.jobs)==null?void 0:v.nodes)==null?void 0:G.map(D=>({completedAt:D.finishedAt?new Date(D.finishedAt):null,description:null,name:D.name??null,state:Kr(D.status,D.allowFailure),stage:f.name??null,startedAt:new Date(D.createdAt),url:`${n.webUrl}/-/jobs/${D.id.replace(Mr,"")}`})))??[]}))??[]},baseRef:{name:r.targetBranch,oid:((p=r.diffRefs)==null?void 0:p.baseSha)??null},headRef:{name:r.sourceBranch,oid:((d=r.diffRefs)==null?void 0:d.headSha)??null},url:r.webUrl,updatedDate:new Date(r.updatedAt),closedDate:r.mergedAt?new Date(r.mergedAt):null,mergedDate:r.mergedAt?new Date(r.mergedAt):null,assignees:(c=r.assignees)!=null&&c.nodes?r.assignees.nodes.map(f=>j(f,t,s)):null,reviews:o,reviewDecision:x(o),additions:((g=r.diffStatsSummary)==null?void 0:g.additions)||0,deletions:((m=r.diffStatsSummary)==null?void 0:m.deletions)||0,fileCount:((I=r.diffStatsSummary)==null?void 0:I.fileCount)||0,commitCount:r.commitCount||0,mergeableState:Nr[r.mergeStatusEnum],milestone:r.milestone?it(r.milestone,n.webUrl):null,labels:((P=(h=r.labels)==null?void 0:h.nodes)==null?void 0:P.map(at))??[],permissions:null}},tt=(r,n,e,t)=>{var s,o;return{author:j(r.author,e,t),assignees:r.assignees.nodes.map(a=>j(a,e,t)),commentCount:r.userNotesCount,closedDate:r.closedAt?new Date(r.closedAt):null,createdDate:new Date(r.createdAt),description:r.description,graphQLId:r.id,id:r.id.replace(Qr,""),labels:((o=(s=r.labels)==null?void 0:s.nodes)==null?void 0:o.map(at))??[],number:r.iid,repository:{id:n.id.replace(te,""),graphQLId:n.id,name:n.name,owner:{login:n.namespace}},updatedDate:new Date(r.updatedAt),upvoteCount:r.upvotes,state:{name:r.state,color:null},type:r.type,title:r.title,url:r.webUrl,milestone:r.milestone?it(r.milestone,n.webUrl):null}},it=(r,n)=>({id:r.id.replace(Br,""),graphQLId:r.id,number:parseInt(r.iid,10),title:r.title,description:r.description,isOpen:r.state==="active",url:`${n}/-/${r.webPath.replace(/.+?\/-\//,"")}`,startDate:r.startDate?new Date(r.startDate):null,dueDate:r.dueDate?new Date(r.dueDate):null}),re=class extends k{getIsSelfHosted(n){return!!n.baseUrl||!!this.config.baseUrl}async getCurrentUser(n={},e={}){var o;let s=(o=(await w(this.config,{query:`
794
794
  query getCurrentUser {
795
795
  currentUser {
796
796
  ${Q}
797
797
  }
798
798
  }
799
- `},e)).body.data)==null?void 0:o.currentUser;if(!s)throw new Error("Current user not found.");return{data:_(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(n,e={}){var a,i,u,l;let t=M(n.repo),o=(l=(u=(i=(a=(await P(this.config,{query:`
799
+ `},e)).body.data)==null?void 0:o.currentUser;if(!s)throw new Error("Current user not found.");return{data:j(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(n,e={}){var a,i,u,l;let t=z(n.repo),o=(l=(u=(i=(a=(await w(this.config,{query:`
800
800
  query getUserForCommit($fullPath: ID!, $oid: String!) {
801
801
  project(fullPath: $fullPath) {
802
802
  repository {
@@ -810,7 +810,7 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
810
810
  }
811
811
  }
812
812
  }
813
- `,variables:{fullPath:t,oid:n.oid}},e)).body.data)==null?void 0:a.project)==null?void 0:i.repository)==null?void 0:u.tree)==null?void 0:l.lastCommit;if(!o)throw new Error("Commit not found.");return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:o.authorGravatar}}}async getAccountForEmail(n,e={}){var o,a,i;let s=(i=(a=(o=(await P(this.config,{query:`
813
+ `,variables:{fullPath:t,oid:n.oid}},e)).body.data)==null?void 0:a.project)==null?void 0:i.repository)==null?void 0:u.tree)==null?void 0:l.lastCommit;if(!o)throw new Error("Commit not found.");return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:o.authorGravatar}}}async getAccountForEmail(n,e={}){var o,a,i;let s=(i=(a=(o=(await w(this.config,{query:`
814
814
  query getAccountForEmail($email: String!) {
815
815
  users(search: $email) {
816
816
  nodes {
@@ -818,13 +818,13 @@ query getAccountForEmail($email: String!) {
818
818
  }
819
819
  }
820
820
  }
821
- `,variables:{email:n.email}},e)).body.data)==null?void 0:o.users)==null?void 0:a.nodes)==null?void 0:i[0];if(!s)throw new Error("User not found.");return{data:_(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(n,e={}){var o;let s=(o=(await P(this.config,{query:`
821
+ `,variables:{email:n.email}},e)).body.data)==null?void 0:o.users)==null?void 0:a.nodes)==null?void 0:i[0];if(!s)throw new Error("User not found.");return{data:j(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(n,e={}){var o;let s=(o=(await w(this.config,{query:`
822
822
  query getAccountForUsername($username: String!) {
823
823
  user(username: $username) {
824
824
  ${Q}
825
825
  }
826
826
  }
827
- `,variables:{username:n.username}},e)).body.data)==null?void 0:o.user;if(!s)throw new Error("User not found.");return{data:_(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(n,e={}){var u,l,p,d,c,g,m;let{repo:{namespace:t,name:s},cursor:o}=n,a=await P(this.config,{query:`
827
+ `,variables:{username:n.username}},e)).body.data)==null?void 0:o.user;if(!s)throw new Error("User not found.");return{data:j(s,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(n,e={}){var u,l,p,d,c,g,m;let{repo:{namespace:t,name:s},cursor:o}=n,a=await w(this.config,{query:`
828
828
  query getAccountsForRepo(
829
829
  $fullPath: ID!
830
830
  $after: String
@@ -845,22 +845,22 @@ query getAccountsForRepo(
845
845
  }
846
846
  }
847
847
  }
848
- `,variables:{fullPath:`${t}/${s}`,after:o}},e),i=(d=(p=(l=(u=a.body.data)==null?void 0:u.project)==null?void 0:l.projectMembers)==null?void 0:p.nodes)==null?void 0:d.map(h=>h.user).filter(h=>h!==null);return{pageInfo:((m=(g=(c=a.body.data)==null?void 0:c.project)==null?void 0:g.projectMembers)==null?void 0:m.pageInfo)??{endCursor:null,hasNextPage:!1},data:(i==null?void 0:i.map(h=>_(h,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))??[]}}async getRepo(n,e={}){var o;let t=M(n),s=await P(this.config,{query:`
848
+ `,variables:{fullPath:`${t}/${s}`,after:o}},e),i=(d=(p=(l=(u=a.body.data)==null?void 0:u.project)==null?void 0:l.projectMembers)==null?void 0:p.nodes)==null?void 0:d.map(I=>I.user).filter(I=>I!==null);return{pageInfo:((m=(g=(c=a.body.data)==null?void 0:c.project)==null?void 0:g.projectMembers)==null?void 0:m.pageInfo)??{endCursor:null,hasNextPage:!1},data:(i==null?void 0:i.map(I=>j(I,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))??[]}}async getRepo(n,e={}){var o;let t=z(n),s=await w(this.config,{query:`
849
849
  query getRepo($fullPath: ID!) {
850
850
  project(fullPath: $fullPath) {
851
851
  ${Ze}
852
852
  }
853
853
  }
854
- `,variables:{fullPath:t}},e);if(!((o=s.body.data)!=null&&o.project))throw new Error(`Repository ${t} not found`);return{data:et(s.body.data.project)}}async getReposBase(n,e={}){let s=n.map(M).map((u,l)=>`
854
+ `,variables:{fullPath:t}},e);if(!((o=s.body.data)!=null&&o.project))throw new Error(`Repository ${t} not found`);return{data:et(s.body.data.project)}}async getReposBase(n,e={}){let s=n.map(z).map((u,l)=>`
855
855
  getRepo_${l}: project(fullPath: "${u}") {
856
856
  ${Ze}
857
857
  }
858
858
  `).join(`
859
- `),o=await P(this.config,{query:`
859
+ `),o=await w(this.config,{query:`
860
860
  query batchGetRepos {
861
861
  ${s}
862
862
  }
863
- `},e);if(!o.body.data)throw new Error(Se(o.body.errors)||o.statusText||"Unknown error");let a=[],i=[];return n.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?a.push(et(p)):i.push({input:u})}),{data:a,errors:i}}async getRepos(n,e={}){let t=[];for(let a=0;a<n.length;a+=15)t.push(n.slice(a,a+15));return(await Promise.all(t.map(a=>this.getReposBase(a,e)))).reduce((a,i)=>({data:[...a.data,...i.data],errors:[...a.errors,...i.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(n,e={}){var o,a,i,u,l;let t=await P(this.config,{query:`
863
+ `},e);if(!o.body.data)throw new Error(Se(o.body.errors)||o.statusText||"Unknown error");let a=[],i=[];return n.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?a.push(et(p)):i.push({input:u})}),{data:a,errors:i}}async getRepos(n,e={}){let t=[];for(let a=0;a<n.length;a+=15)t.push(n.slice(a,a+15));return(await Promise.all(t.map(a=>this.getReposBase(a,e)))).reduce((a,i)=>({data:[...a.data,...i.data],errors:[...a.errors,...i.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(n,e={}){var o,a,i,u,l;let t=await w(this.config,{query:`
864
864
  query getReposForCurrentUser($after: String) {
865
865
  projects(membership: true first: 100 after: $after) {
866
866
  pageInfo {
@@ -872,7 +872,7 @@ query getReposForCurrentUser($after: String) {
872
872
  }
873
873
  }
874
874
  }
875
- `,variables:{after:n.cursor}},e);if(!((o=t.body.data)!=null&&o.projects))throw new Error(Se(t.body.errors)||t.statusText||"Unknown error");let s=((i=(a=t.body.data)==null?void 0:a.projects)==null?void 0:i.nodes)||[];return{pageInfo:(l=(u=t.body.data)==null?void 0:u.projects)==null?void 0:l.pageInfo,data:s.map(et)}}async getRefs(n,e,t={}){var u;let s=M(e.repo),o=new URL(`${we(this.config,t)}/projects/${encodeURIComponent(s)}/repository/${n}`);o.searchParams.set("page",((u=e.page)==null?void 0:u.toString())||"1"),o.searchParams.set("per_page",C.toString());let a=await this.config.request({url:o.toString(),headers:R(t.token||this.config.token)}),i=a.headers["x-next-page"];return{pageInfo:{hasNextPage:!!i,nextPage:i?parseInt(i,10):null},data:a.body.map(l=>({name:l.name,commit:{oid:l.commit.id,authoredDate:new Date(l.commit.authored_date),committedDate:new Date(l.commit.committed_date)}}))}}async getBranches(n,e={}){return this.getRefs("branches",n,e)}async getTags(n,e={}){return this.getRefs("tags",n,e)}async getBlame(n,e={}){let t=M(n.repo),s=new URL(`${we(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/blame`);s.searchParams.set("ref",n.ref);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)}),a=0;return{data:{ranges:o.body.map(i=>{let u=a+1;return a+=i.lines.length,{startingLine:u,endingLine:a,commit:{oid:i.commit.id,parentOids:i.commit.parent_ids,authoredDate:new Date(i.commit.authored_date),author:{name:i.commit.author_name,email:i.commit.author_email,avatarUrl:null},committedDate:new Date(i.commit.committed_date),committer:{name:i.commit.committer_name,email:i.commit.committer_email,avatarUrl:null},message:i.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(n,e={}){var i,u,l,p;let t="";(i=n.repo)!=null&&i.id?t=`projectId:"${n.repo.id}"`:(u=n.repo)!=null&&u.namespace&&((l=n.repo)!=null&&l.name)&&(t=`projectPath:"${n.repo.namespace}/${n.repo.name}"`);let s=kr[n.association],o=await P(this.config,{query:`
875
+ `,variables:{after:n.cursor}},e);if(!((o=t.body.data)!=null&&o.projects))throw new Error(Se(t.body.errors)||t.statusText||"Unknown error");let s=((i=(a=t.body.data)==null?void 0:a.projects)==null?void 0:i.nodes)||[];return{pageInfo:(l=(u=t.body.data)==null?void 0:u.projects)==null?void 0:l.pageInfo,data:s.map(et)}}async getRefs(n,e,t={}){var u;let s=z(e.repo),o=new URL(`${we(this.config,t)}/projects/${encodeURIComponent(s)}/repository/${n}`);o.searchParams.set("page",((u=e.page)==null?void 0:u.toString())||"1"),o.searchParams.set("per_page",C.toString());let a=await this.config.request({url:o.toString(),headers:R(t.token||this.config.token)}),i=a.headers["x-next-page"];return{pageInfo:{hasNextPage:!!i,nextPage:i?parseInt(i,10):null},data:a.body.map(l=>({name:l.name,commit:{oid:l.commit.id,authoredDate:new Date(l.commit.authored_date),committedDate:new Date(l.commit.committed_date)}}))}}async getBranches(n,e={}){return this.getRefs("branches",n,e)}async getTags(n,e={}){return this.getRefs("tags",n,e)}async getBlame(n,e={}){let t=z(n.repo),s=new URL(`${we(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/blame`);s.searchParams.set("ref",n.ref);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)}),a=0;return{data:{ranges:o.body.map(i=>{let u=a+1;return a+=i.lines.length,{startingLine:u,endingLine:a,commit:{oid:i.commit.id,parentOids:i.commit.parent_ids,authoredDate:new Date(i.commit.authored_date),author:{name:i.commit.author_name,email:i.commit.author_email,avatarUrl:null},committedDate:new Date(i.commit.committed_date),committer:{name:i.commit.committer_name,email:i.commit.committer_email,avatarUrl:null},message:i.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(n,e={}){var i,u,l,p;let t="";(i=n.repo)!=null&&i.id?t=`projectId:"${n.repo.id}"`:(u=n.repo)!=null&&u.namespace&&((l=n.repo)!=null&&l.name)&&(t=`projectPath:"${n.repo.namespace}/${n.repo.name}"`);let s=kr[n.association],o=await w(this.config,{query:`
876
876
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
877
877
  user(username: $username) {
878
878
  ${s}(state:opened first:100 after:$cursor labels: $labelNames${t?` ${t}`:""}) {
@@ -886,7 +886,7 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
886
886
  }
887
887
  }
888
888
  }
889
- `,variables:{username:n.username,cursor:n.cursor,labelNames:n.labelNames}},e);if(!o.body.data)throw new Error(Se(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let a=o.body.data.user[s];if(!a)throw new Error("Unexpected response");return{pageInfo:a.pageInfo,data:((p=a.nodes)==null?void 0:p.filter(d=>n.includeFromArchivedRepos||!d.project.archived).map(d=>xt(d,Tt(d.project),Tt(d.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))||[]}}async getPullRequestsAssociatedWithUser(n,e={}){var $,ue;let[t,s,o]=(($=n.cursor)==null?void 0:$.split(";"))||[void 0,void 0,void 0],a=(t==null?void 0:t.split("-"))||[],i=(s==null?void 0:s.split("-"))||[],u=(o==null?void 0:o.split("-"))||[],l=[],p=[],d=[],c=0;do{let E=n.repos&&n.repos[c];a[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:n.username,association:"authored",cursor:a[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...E&&{repo:E}},e)),i[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:n.username,association:"assigned",cursor:i[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...E&&{repo:E}},e)),u[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:n.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...E&&{repo:E}},e)),c++}while(c<(((ue=n.repos)==null?void 0:ue.length)||0));let g=[l,p,d].flat(),m=await Promise.all(g),h={},I=[],w=E=>{h[E.id]||(h[E.id]=!0,I.push(E))},f=!1,G=m.map((E,dt)=>{var ct;let ae="";return E&&E.data.forEach(w),E!=null&&E.pageInfo.hasNextPage?(f=!0,ae+=`${E.pageInfo.endCursor||"null"}`):ae+="null",(ct=n.repos)!=null&&ct.length&&(dt+1)%n.repos.length!==0?ae+="-":dt+1<m.length&&(ae+=";"),ae}).join("");return{pageInfo:{hasNextPage:f,endCursor:G},data:I}}getVariablesForPullRequests(n){let{updatedBefore:e,isDraft:t,authorLogin:s,assigneeLogins:o,labelNames:a,reviewRequestedLogin:i}=n||{},u={},l=[],p=[],d=(c,g,m)=>{l.push(`$${c}: ${m}`),p.push(`${c}: $${c}`),u[c]=g};return e&&d("updatedBefore",e,"Time"),s&&d("authorUsername",s,"String"),o&&d("assigneeUsername",o[0],"String"),a&&d("labelName",a,"[String]"),t!=null&&d("draft",t,"Boolean"),i&&d("reviewerUsername",i,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(n,e={},t){var I,w,f;let{cursor:s,repo:o}=n||{},a=M(o),{variables:i,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(n),p={fullPath:a,...i},d=await P(this.config,{query:`
889
+ `,variables:{username:n.username,cursor:n.cursor,labelNames:n.labelNames}},e);if(!o.body.data)throw new Error(Se(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let a=o.body.data.user[s];if(!a)throw new Error("Unexpected response");return{pageInfo:a.pageInfo,data:((p=a.nodes)==null?void 0:p.filter(d=>n.includeFromArchivedRepos||!d.project.archived).map(d=>xt(d,Tt(d.project),Tt(d.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))||[]}}async getPullRequestsAssociatedWithUser(n,e={}){var D,ue;let[t,s,o]=((D=n.cursor)==null?void 0:D.split(";"))||[void 0,void 0,void 0],a=(t==null?void 0:t.split("-"))||[],i=(s==null?void 0:s.split("-"))||[],u=(o==null?void 0:o.split("-"))||[],l=[],p=[],d=[],c=0;do{let q=n.repos&&n.repos[c];a[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:n.username,association:"authored",cursor:a[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...q&&{repo:q}},e)),i[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:n.username,association:"assigned",cursor:i[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...q&&{repo:q}},e)),u[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:n.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...q&&{repo:q}},e)),c++}while(c<(((ue=n.repos)==null?void 0:ue.length)||0));let g=[l,p,d].flat(),m=await Promise.all(g),I={},h=[],P=q=>{I[q.id]||(I[q.id]=!0,h.push(q))},f=!1,G=m.map((q,dt)=>{var ct;let ae="";return q&&q.data.forEach(P),q!=null&&q.pageInfo.hasNextPage?(f=!0,ae+=`${q.pageInfo.endCursor||"null"}`):ae+="null",(ct=n.repos)!=null&&ct.length&&(dt+1)%n.repos.length!==0?ae+="-":dt+1<m.length&&(ae+=";"),ae}).join("");return{pageInfo:{hasNextPage:f,endCursor:G},data:h}}getVariablesForPullRequests(n){let{updatedBefore:e,isDraft:t,authorLogin:s,assigneeLogins:o,labelNames:a,reviewRequestedLogin:i}=n||{},u={},l=[],p=[],d=(c,g,m)=>{l.push(`$${c}: ${m}`),p.push(`${c}: $${c}`),u[c]=g};return e&&d("updatedBefore",e,"Time"),s&&d("authorUsername",s,"String"),o&&d("assigneeUsername",o[0],"String"),a&&d("labelName",a,"[String]"),t!=null&&d("draft",t,"Boolean"),i&&d("reviewerUsername",i,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(n,e={},t){var h,P,f;let{cursor:s,repo:o}=n||{},a=z(o),{variables:i,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(n),p={fullPath:a,...i},d=await w(this.config,{query:`
890
890
  query getPullRequestsForRepo(
891
891
  $fullPath: ID!
892
892
  $after: String
@@ -916,14 +916,14 @@ query getPullRequestsForRepo(
916
916
  }
917
917
  }
918
918
  }
919
- `,variables:{...p,after:s}},e),c=[],g=(I=d.body.data)==null?void 0:I.project;if(!t&&(g!=null&&g.archived))return{pageInfo:null,data:[]};let m=ve(g||{id:"",fullPath:"",webUrl:""});return(((w=g==null?void 0:g.mergeRequests)==null?void 0:w.nodes)||[]).forEach(v=>{c.push(xt(v,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:(f=g==null?void 0:g.mergeRequests)==null?void 0:f.pageInfo,data:c}}async getPullRequestsForRepo(n,e={}){return this.getPullRequestsForRepoBase(n,e,!1)}async getPullRequestsForRepos(n,e={}){let{repos:t,assigneeLogins:s,updatedBefore:o,authorLogin:a,labelNames:i,isDraft:u,reviewRequestedLogin:l}=n;return{data:(await Promise.all(t.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:s,updatedBefore:o,authorLogin:a,labelNames:i,isDraft:u,reviewRequestedLogin:l},e,n.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(n,e={}){var i,u,l;let{pullRequest:t}=n,s=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
919
+ `,variables:{...p,after:s}},e),c=[],g=(h=d.body.data)==null?void 0:h.project;if(!t&&(g!=null&&g.archived))return{pageInfo:null,data:[]};let m=ve(g||{id:"",fullPath:"",webUrl:""});return(((P=g==null?void 0:g.mergeRequests)==null?void 0:P.nodes)||[]).forEach(v=>{c.push(xt(v,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:(f=g==null?void 0:g.mergeRequests)==null?void 0:f.pageInfo,data:c}}async getPullRequestsForRepo(n,e={}){return this.getPullRequestsForRepoBase(n,e,!1)}async getPullRequestsForRepos(n,e={}){let{repos:t,assigneeLogins:s,updatedBefore:o,authorLogin:a,labelNames:i,isDraft:u,reviewRequestedLogin:l}=n;return{data:(await Promise.all(t.map(d=>this.getPullRequestsForRepoBase({repo:d,assigneeLogins:s,updatedBefore:o,authorLogin:a,labelNames:i,isDraft:u,reviewRequestedLogin:l},e,n.includeFromArchivedRepos??!1)))).flatMap(d=>d.data)}}async closePullRequest(n,e={}){var i,u,l;let{pullRequest:t}=n,s=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
920
920
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
921
921
  errors,
922
922
  mergeRequest {
923
923
  id
924
924
  }
925
925
  }
926
- }`,a=(i=(await P(this.config,{query:s,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString()}},e)).body.data)==null?void 0:i.mergeRequestUpdate;if(!((u=a==null?void 0:a.mergeRequest)!=null&&u.id)||((l=a==null?void 0:a.errors)==null?void 0:l.length)!==0)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){var u,l,p,d;let{pullRequest:t,mergeStrategy:s}=n;if(!((u=t.headRef)!=null&&u.oid))throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
926
+ }`,a=(i=(await w(this.config,{query:s,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString()}},e)).body.data)==null?void 0:i.mergeRequestUpdate;if(!((u=a==null?void 0:a.mergeRequest)!=null&&u.id)||((l=a==null?void 0:a.errors)==null?void 0:l.length)!==0)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){var u,l,p,d;let{pullRequest:t,mergeStrategy:s}=n;if(!((u=t.headRef)!=null&&u.oid))throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
927
927
  $fullPath: ID!,
928
928
  $pullRequestId: String!,
929
929
  $expectedSourceSha: String!,
@@ -940,48 +940,48 @@ query getPullRequestsForRepo(
940
940
  id
941
941
  }
942
942
  }
943
- }`,i=(l=(await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),expectedSourceSha:t.headRef.oid,squash:s==="SQUASH"}},e)).body.data)==null?void 0:l.mergeRequestAccept;if(!((p=i==null?void 0:i.mergeRequest)!=null&&p.id)||((d=i==null?void 0:i.errors)==null?void 0:d.length)!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(n,e={}){var u,l,p;let{pullRequest:t,milestone:s}=n;if(!t.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
943
+ }`,i=(l=(await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),expectedSourceSha:t.headRef.oid,squash:s==="SQUASH"}},e)).body.data)==null?void 0:l.mergeRequestAccept;if(!((p=i==null?void 0:i.mergeRequest)!=null&&p.id)||((d=i==null?void 0:i.errors)==null?void 0:d.length)!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(n,e={}){var u,l,p;let{pullRequest:t,milestone:s}=n;if(!t.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
944
944
  mergeRequestSetMilestone(input: { projectPath: $fullPath, iid: $pullRequestId, milestoneId: $milestoneGraphQLId }) {
945
945
  errors,
946
946
  mergeRequest {
947
947
  id
948
948
  }
949
949
  }
950
- }`,a=await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),milestoneGraphQLId:s==null?void 0:s.graphQLId}},e),i=(u=a.body.data)==null?void 0:u.mergeRequestSetMilestone;if(!((l=i==null?void 0:i.mergeRequest)!=null&&l.id)||a.body.errors||((p=i==null?void 0:i.errors)==null?void 0:p.length)!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(n,e={}){var u,l,p;let{pullRequest:t,isDraft:s}=n,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
950
+ }`,a=await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),milestoneGraphQLId:s==null?void 0:s.graphQLId}},e),i=(u=a.body.data)==null?void 0:u.mergeRequestSetMilestone;if(!((l=i==null?void 0:i.mergeRequest)!=null&&l.id)||a.body.errors||((p=i==null?void 0:i.errors)==null?void 0:p.length)!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(n,e={}){var u,l,p;let{pullRequest:t,isDraft:s}=n,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
951
951
  mergeRequestSetDraft(input: { projectPath: $fullPath, iid: $pullRequestId, draft: $isDraft }) {
952
952
  errors,
953
953
  mergeRequest {
954
954
  id
955
955
  }
956
956
  }
957
- }`,i=(u=(await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),isDraft:s}},e)).body.data)==null?void 0:u.mergeRequestSetDraft;if(!((l=i==null?void 0:i.mergeRequest)!=null&&l.id)||((p=i==null?void 0:i.errors)==null?void 0:p.length)!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(n,e={}){var l,p,d;let{pullRequest:t,reviewers:s}=n,o=s.map(c=>{if(!c.username)throw new Error('GitLab requires reviewer "username" for this function.');return c.username}),a=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
957
+ }`,i=(u=(await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),isDraft:s}},e)).body.data)==null?void 0:u.mergeRequestSetDraft;if(!((l=i==null?void 0:i.mergeRequest)!=null&&l.id)||((p=i==null?void 0:i.errors)==null?void 0:p.length)!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(n,e={}){var l,p,d;let{pullRequest:t,reviewers:s}=n,o=s.map(c=>{if(!c.username)throw new Error('GitLab requires reviewer "username" for this function.');return c.username}),a=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
958
958
  mergeRequestSetReviewers(input: { projectPath: $fullPath, iid: $pullRequestId, reviewerUsernames: $reviewerUsernames }) {
959
959
  errors,
960
960
  mergeRequest {
961
961
  id
962
962
  }
963
963
  }
964
- }`,u=(l=(await P(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUsernames:o}},e)).body.data)==null?void 0:l.mergeRequestSetReviewers;if(!((p=u==null?void 0:u.mergeRequest)!=null&&p.id)||((d=u==null?void 0:u.errors)==null?void 0:d.length)!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(n,e={}){var u,l,p;let{pullRequest:t,reviewer:s}=n;if(!s.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
964
+ }`,u=(l=(await w(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUsernames:o}},e)).body.data)==null?void 0:l.mergeRequestSetReviewers;if(!((p=u==null?void 0:u.mergeRequest)!=null&&p.id)||((d=u==null?void 0:u.errors)==null?void 0:d.length)!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(n,e={}){var u,l,p;let{pullRequest:t,reviewer:s}=n;if(!s.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
965
965
  mergeRequestReviewerRereview(input: { projectPath: $fullPath, iid: $pullRequestId, userId: $reviewerUserId }) {
966
966
  errors,
967
967
  mergeRequest {
968
968
  id
969
969
  }
970
970
  }
971
- }`,i=(u=(await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUserId:s.graphQLId}},e)).body.data)==null?void 0:u.mergeRequestReviewerRereview;if(!((l=i==null?void 0:i.mergeRequest)!=null&&l.id)||((p=i==null?void 0:i.errors)==null?void 0:p.length)!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(n,e={}){let{pullRequest:t,reviewers:s}=n,o=t.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let a=s.filter(i=>o.find(u=>u.reviewer.graphQLId===i.graphQLId));await Promise.all(a.map(i=>this.reRequestPullRequestReview({pullRequest:t,reviewer:i},e)))}async setPullRequestAssignees(n,e={}){var l,p,d;let{pullRequest:t,assignees:s}=n,o=s.map(c=>{if(!c.username)throw new Error('GitLab requires assignee "username" for this function.');return c.username}),a=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
971
+ }`,i=(u=(await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUserId:s.graphQLId}},e)).body.data)==null?void 0:u.mergeRequestReviewerRereview;if(!((l=i==null?void 0:i.mergeRequest)!=null&&l.id)||((p=i==null?void 0:i.errors)==null?void 0:p.length)!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(n,e={}){let{pullRequest:t,reviewers:s}=n,o=t.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let a=s.filter(i=>o.find(u=>u.reviewer.graphQLId===i.graphQLId));await Promise.all(a.map(i=>this.reRequestPullRequestReview({pullRequest:t,reviewer:i},e)))}async setPullRequestAssignees(n,e={}){var l,p,d;let{pullRequest:t,assignees:s}=n,o=s.map(c=>{if(!c.username)throw new Error('GitLab requires assignee "username" for this function.');return c.username}),a=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
972
972
  mergeRequestSetAssignees(input: { projectPath: $fullPath, iid: $pullRequestId, assigneeUsernames: $assigneeUsernames }) {
973
973
  errors,
974
974
  mergeRequest {
975
975
  id
976
976
  }
977
977
  }
978
- }`,u=(l=(await P(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),assigneeUsernames:o}},e)).body.data)==null?void 0:l.mergeRequestSetAssignees;if(!((p=u==null?void 0:u.mergeRequest)!=null&&p.id)||((d=u==null?void 0:u.errors)==null?void 0:d.length)!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(n,e={}){var u,l,p;let{pullRequest:t,labels:s}=n,o=s.map(d=>{if(!d.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return d.graphQLId}),a=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
978
+ }`,u=(l=(await w(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),assigneeUsernames:o}},e)).body.data)==null?void 0:l.mergeRequestSetAssignees;if(!((p=u==null?void 0:u.mergeRequest)!=null&&p.id)||((d=u==null?void 0:u.errors)==null?void 0:d.length)!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(n,e={}){var u,l,p;let{pullRequest:t,labels:s}=n,o=s.map(d=>{if(!d.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return d.graphQLId}),a=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
979
979
  mergeRequestSetLabels(input: { projectPath: $fullPath, iid: $pullRequestId, labelIds: $labelGraphQLIds }) {
980
980
  mergeRequest {
981
981
  id
982
982
  }
983
983
  }
984
- }`;if(!((p=(l=(u=(await P(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data)==null?void 0:u.mergeRequestSetLabels)==null?void 0:l.mergeRequest)!=null&&p.id))throw new Error("Could not set pull request labels")}async getIssue(n,e={}){var o,a,i;let t=Wr(n),s=await P(this.config,{query:`
984
+ }`;if(!((p=(l=(u=(await w(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data)==null?void 0:u.mergeRequestSetLabels)==null?void 0:l.mergeRequest)!=null&&p.id))throw new Error("Could not set pull request labels")}async getIssue(n,e={}){var o,a,i;let t=Wr(n),s=await w(this.config,{query:`
985
985
  query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
986
986
  project(fullPath: $projectId) {
987
987
  id
@@ -992,7 +992,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
992
992
  }
993
993
  }
994
994
  }
995
- `,variables:{issueNumber:n.number,projectId:t}},e);if(!((o=s.body.data)!=null&&o.project))throw new Error(`Repository ${t} not found`);if(!((i=(a=s.body.data)==null?void 0:a.project)!=null&&i.issue))throw new Error(`Issue ${n.number} not found`);return{data:tt(s.body.data.project.issue,ve(s.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(n){let{updatedBefore:e,authorLogin:t,assigneeLogins:s,labelNames:o}=n||{},a={},i=[],u=[],l=(p,d,c)=>{i.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),a[p]=d};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),s&&l("assigneeUsername",s[0],"String"),o&&l("labelName",o,"[String]"),{variables:a,variableTypes:i,issueArguments:u}}async getIssuesForRepo(n,e={}){var I,w,f;let{cursor:t,repo:s}=n||{},o=M(s),{variables:a,variableTypes:i,issueArguments:u}=this.getVariablesForIssues(n),l={fullPath:o,...a},p=`
995
+ `,variables:{issueNumber:n.number,projectId:t}},e);if(!((o=s.body.data)!=null&&o.project))throw new Error(`Repository ${t} not found`);if(!((i=(a=s.body.data)==null?void 0:a.project)!=null&&i.issue))throw new Error(`Issue ${n.number} not found`);return{data:tt(s.body.data.project.issue,ve(s.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(n){let{updatedBefore:e,authorLogin:t,assigneeLogins:s,labelNames:o}=n||{},a={},i=[],u=[],l=(p,d,c)=>{i.push(`$${p}: ${c}`),u.push(`${p}: $${p}`),a[p]=d};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),s&&l("assigneeUsername",s[0],"String"),o&&l("labelName",o,"[String]"),{variables:a,variableTypes:i,issueArguments:u}}async getIssuesForRepo(n,e={}){var h,P,f;let{cursor:t,repo:s}=n||{},o=z(s),{variables:a,variableTypes:i,issueArguments:u}=this.getVariablesForIssues(n),l={fullPath:o,...a},p=`
996
996
  query GetIssuesFromProject(
997
997
  $fullPath: ID!
998
998
  $after: String
@@ -1020,7 +1020,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1020
1020
  }
1021
1021
  }
1022
1022
  }
1023
- }`,d=await P(this.config,{query:p,variables:{...l,after:t}},e),c=[],g=(I=d.body.data)==null?void 0:I.project,m=ve(g||{id:"",fullPath:"",webUrl:""});return(((w=g==null?void 0:g.issues)==null?void 0:w.nodes)||[]).forEach(v=>{c.push(tt(v,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:((f=g==null?void 0:g.issues)==null?void 0:f.pageInfo)??{endCursor:null,hasNextPage:!1},data:c.sort((v,G)=>(v.updatedDate||v.createdDate).getTime()-(G.updatedDate||G.createdDate).getTime())}}async getIssuesForRepos(n,e={}){var g,m,h,I,w;let{cursor:t}=n||{},s=n.repoIds.map(f=>f.toString().startsWith(te)?f:`${te}${f}`),{variables:o,variableTypes:a,mergeRequestArguments:i}=this.getVariablesForPullRequests(n),u={projectIds:s,...o},l=`
1023
+ }`,d=await w(this.config,{query:p,variables:{...l,after:t}},e),c=[],g=(h=d.body.data)==null?void 0:h.project,m=ve(g||{id:"",fullPath:"",webUrl:""});return(((P=g==null?void 0:g.issues)==null?void 0:P.nodes)||[]).forEach(v=>{c.push(tt(v,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:((f=g==null?void 0:g.issues)==null?void 0:f.pageInfo)??{endCursor:null,hasNextPage:!1},data:c.sort((v,G)=>(v.updatedDate||v.createdDate).getTime()-(G.updatedDate||G.createdDate).getTime())}}async getIssuesForRepos(n,e={}){var g,m,I,h,P;let{cursor:t}=n||{},s=n.repoIds.map(f=>f.toString().startsWith(te)?f:`${te}${f}`),{variables:o,variableTypes:a,mergeRequestArguments:i}=this.getVariablesForPullRequests(n),u={projectIds:s,...o},l=`
1024
1024
  query GetIssuesFromProject(
1025
1025
  $projectIds: [ID!]
1026
1026
  $after: String
@@ -1051,19 +1051,19 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1051
1051
  }
1052
1052
  }
1053
1053
  }
1054
- }`,p=await P(this.config,{query:l,variables:{...u,after:t}},e),d=[];return(((m=(g=p.body.data)==null?void 0:g.projects)==null?void 0:m.nodes)||[]).forEach(f=>{var $;if(!n.includeFromArchivedRepos&&f.archived)return;let v=ve(f);((($=f.issues)==null?void 0:$.nodes)||[]).forEach(ue=>d.push(tt(ue,v,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:((w=(I=(h=p.body)==null?void 0:h.data)==null?void 0:I.projects)==null?void 0:w.pageInfo)??{endCursor:null,hasNextPage:!1},data:d.sort((f,v)=>(f.updatedDate||f.createdDate).getTime()-(v.updatedDate||v.createdDate).getTime())}}async setIssueState(n,e={}){var i,u,l;let{issue:t,state:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1054
+ }`,p=await w(this.config,{query:l,variables:{...u,after:t}},e),d=[];return(((m=(g=p.body.data)==null?void 0:g.projects)==null?void 0:m.nodes)||[]).forEach(f=>{var D;if(!n.includeFromArchivedRepos&&f.archived)return;let v=ve(f);(((D=f.issues)==null?void 0:D.nodes)||[]).forEach(ue=>d.push(tt(ue,v,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:((P=(h=(I=p.body)==null?void 0:I.data)==null?void 0:h.projects)==null?void 0:P.pageInfo)??{endCursor:null,hasNextPage:!1},data:d.sort((f,v)=>(f.updatedDate||f.createdDate).getTime()-(v.updatedDate||v.createdDate).getTime())}}async setIssueState(n,e={}){var i,u,l;let{issue:t,state:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1055
1055
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1056
1056
  issue {
1057
1057
  id
1058
1058
  }
1059
1059
  }
1060
- }`;if(!((l=(u=(i=(await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,status:s==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data)==null?void 0:i.updateIssue)==null?void 0:u.issue)!=null&&l.id))throw new Error("Could not set issue status")}async closeIssue(n,e={}){await this.setIssueState({...n,state:"CLOSED"},e)}async reOpenIssue(n,e={}){await this.setIssueState({...n,state:"OPEN"},e)}async setIssueLabels(n,e={}){var u,l,p;let{issue:t,labels:s}=n;if(!t.repository)throw new Error('GitLab requires a "repository" for this function.');let o=s.map(d=>{if(!d.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return d.graphQLId}),a=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
1060
+ }`;if(!((l=(u=(i=(await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,status:s==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data)==null?void 0:i.updateIssue)==null?void 0:u.issue)!=null&&l.id))throw new Error("Could not set issue status")}async closeIssue(n,e={}){await this.setIssueState({...n,state:"CLOSED"},e)}async reOpenIssue(n,e={}){await this.setIssueState({...n,state:"OPEN"},e)}async setIssueLabels(n,e={}){var u,l,p;let{issue:t,labels:s}=n;if(!t.repository)throw new Error('GitLab requires a "repository" for this function.');let o=s.map(d=>{if(!d.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return d.graphQLId}),a=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
1061
1061
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, labelIds: $labelGraphQLIds }) {
1062
1062
  issue {
1063
1063
  id
1064
1064
  }
1065
1065
  }
1066
- }`;if(!((p=(l=(u=(await P(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,labelGraphQLIds:o}},e)).body.data)==null?void 0:u.updateIssue)==null?void 0:l.issue)!=null&&p.id))throw new Error("Could not set issue labels")}async setIssueMilestone(n,e={}){var u,l,p;let{issue:t,milestone:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1066
+ }`;if(!((p=(l=(u=(await w(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,labelGraphQLIds:o}},e)).body.data)==null?void 0:u.updateIssue)==null?void 0:l.issue)!=null&&p.id))throw new Error("Could not set issue labels")}async setIssueMilestone(n,e={}){var u,l,p;let{issue:t,milestone:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1067
1067
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, milestoneId: $milestoneId }) {
1068
1068
  errors
1069
1069
  issue {
@@ -1073,14 +1073,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1073
1073
  }
1074
1074
  }
1075
1075
  }
1076
- }`,a=await P(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:(s==null?void 0:s.id)??null}},e),i=(u=a.body.data)==null?void 0:u.updateIssue;if(!((l=i==null?void 0:i.issue)!=null&&l.id)||a.body.errors||((p=i==null?void 0:i.errors)==null?void 0:p.length)!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(n,e={}){var l,p,d;let{issue:t,assignees:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=s.map(c=>c.username),a=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1076
+ }`,a=await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:(s==null?void 0:s.id)??null}},e),i=(u=a.body.data)==null?void 0:u.updateIssue;if(!((l=i==null?void 0:i.issue)!=null&&l.id)||a.body.errors||((p=i==null?void 0:i.errors)==null?void 0:p.length)!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(n,e={}){var l,p,d;let{issue:t,assignees:s}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=s.map(c=>c.username),a=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1077
1077
  issueSetAssignees(input: { projectPath: $fullPath, iid: $issueId, assigneeUsernames: $assigneeUsernames }) {
1078
1078
  errors,
1079
1079
  issue {
1080
1080
  id
1081
1081
  }
1082
1082
  }
1083
- }`,u=(l=(await P(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,assigneeUsernames:o}},e)).body.data)==null?void 0:l.issueSetAssignees;if(!((p=u==null?void 0:u.issue)!=null&&p.id)||((d=u==null?void 0:u.errors)==null?void 0:d.length)!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(n,e={}){var i,u,l,p,d,c,g;let{repo:{namespace:t,name:s},cursor:o}=n,a=await P(this.config,{query:`
1083
+ }`,u=(l=(await w(this.config,{query:a,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,assigneeUsernames:o}},e)).body.data)==null?void 0:l.issueSetAssignees;if(!((p=u==null?void 0:u.issue)!=null&&p.id)||((d=u==null?void 0:u.errors)==null?void 0:d.length)!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(n,e={}){var i,u,l,p,d,c,g;let{repo:{namespace:t,name:s},cursor:o}=n,a=await w(this.config,{query:`
1084
1084
  query getLabelsForRepo(
1085
1085
  $fullPath: ID!
1086
1086
  $after: String
@@ -1100,7 +1100,7 @@ query getLabelsForRepo(
1100
1100
  }
1101
1101
  }
1102
1102
  }
1103
- `,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:((l=(u=(i=a.body.data)==null?void 0:i.project)==null?void 0:u.milestones)==null?void 0:l.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=(p=a.body.data)==null?void 0:p.project)==null?void 0:d.milestones)==null?void 0:c.nodes)==null?void 0:g.map(m=>{var h,I;return it(m,((I=(h=a.body.data)==null?void 0:h.project)==null?void 0:I.webUrl)||"")}))??[]}}async getLabelsForRepo(n,e={}){var i,u,l,p,d,c,g;let{repo:{namespace:t,name:s},cursor:o}=n,a=await P(this.config,{query:`
1103
+ `,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:((l=(u=(i=a.body.data)==null?void 0:i.project)==null?void 0:u.milestones)==null?void 0:l.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=(p=a.body.data)==null?void 0:p.project)==null?void 0:d.milestones)==null?void 0:c.nodes)==null?void 0:g.map(m=>{var I,h;return it(m,((h=(I=a.body.data)==null?void 0:I.project)==null?void 0:h.webUrl)||"")}))??[]}}async getLabelsForRepo(n,e={}){var i,u,l,p,d,c,g;let{repo:{namespace:t,name:s},cursor:o}=n,a=await w(this.config,{query:`
1104
1104
  query getLabelsForRepo(
1105
1105
  $fullPath: ID!
1106
1106
  $after: String
@@ -1119,5 +1119,5 @@ query getLabelsForRepo(
1119
1119
  }
1120
1120
  }
1121
1121
  }
1122
- `,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:((l=(u=(i=a.body.data)==null?void 0:i.project)==null?void 0:u.labels)==null?void 0:l.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=(p=a.body.data)==null?void 0:p.project)==null?void 0:d.labels)==null?void 0:c.nodes)==null?void 0:g.map(at))??[]}}async getTreeForRepo(n,e={}){let t=M(n.repo),s=new URL(n.cursor??`${we(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);s.searchParams.set("per_page","10000"),s.searchParams.set("recursive","true"),s.searchParams.set("pagination","keyset"),s.searchParams.set("ref",n.branch);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)}),a=o.headers.link;return{data:o.body.map(Jr),pageInfo:{endCursor:a?a.substring(1,a.indexOf(">")):null,hasNextPage:!!a}}}};var Zr="https://api.atlassian.com/ex/jira",qe=100,ut=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],kt="/rest/api/2/search/jql",Nt="/rest/api/2/search",lt=(r,n,e,t)=>{var i,u,l,p;let s=r.fields.assignee,o=!t,a=(r.fields[(n==null?void 0:n.Sprint)??""]??[]).filter(d=>typeof d=="object");return{id:r.id,commentCount:r.fields.comment.comments.length,number:r.key,title:r.fields.summary,url:e?`${e}/browse/${r.key}`:null,closedDate:null,createdDate:new Date(r.fields.created),author:Ee(r.fields.creator,e,o),updatedDate:new Date(r.fields.updated),assignees:s?[Ee(s,e,o)]:[],description:r.fields.description,repository:null,project:{name:r.fields.project.name,resourceId:t??null,key:r.fields.project.key,namespace:null,id:r.fields.project.id},state:rs(r.fields.status),statusTransitions:((i=r.transitions)==null?void 0:i.map(Yr))??[],components:((u=r.fields.components)==null?void 0:u.map(es))??[],type:r.fields.issuetype.name,upvoteCount:((l=r.fields.votes)==null?void 0:l.votes)||0,labels:((p=r.fields.labels)==null?void 0:p.map(d=>({color:null,description:null,id:null,name:d})))??[],sprints:a.map(ss),fixVersions:r.fields.fixVersions.map(ns)}},Yr=r=>{let n;switch(r.to.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{name:r.name,id:r.id,to:{id:r.to.id,name:r.to.name,color:r.to.statusCategory.colorName,category:n}}},es=r=>({description:r.description??null,id:r.id,name:r.name}),ts=(r,n,e)=>e&&r.name?`${n}/secure/ViewProfile.jspa?name=${encodeURIComponent(r.name)}`:`${n}/jira/people/${r.accountId}`,Ee=(r,n,e)=>({id:(e?r.key:r.accountId)??"",name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrls["48x48"],username:r.displayName,url:ts(r,n,e)}),rs=r=>{let n;switch(r.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{id:r.id,name:r.name,color:r.statusCategory.colorName,category:n}},ss=r=>({id:r.id.toString(),name:r.name,isActive:r.state==="active",startDate:r.startDate?new Date(r.startDate):null,endDate:r.endDate?new Date(r.endDate):null,completedDate:r.completeDate?new Date(r.completeDate):null}),ns=r=>({id:r.id,description:r.description,name:r.name,archived:r.archived,released:r.released,releaseDate:r.releaseDate?new Date(r.releaseDate):null}),z=(r,n,e)=>e?`${n.baseUrl||Zr}/${e}`:`${(n==null?void 0:n.baseUrl)||r.baseUrl}`,Ce=async(r,n,e={})=>{let{resourceId:t}=n;return(await r.request({url:`${z(r,e,t)}/rest/api/2/field`,headers:R(e.token||r.token)})).body},De=async(r,n,e,t={})=>{let{number:s,resourceId:o,fields:a}=n||{},i=await r.request({url:`${z(r,t,o)}/rest/api/2/issue/${s}?fields=${ut.join(",")}&expand=transitions`,headers:R(t.token||r.token)});return{data:lt(i.body,a,e,o)}},Le=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,labelNames:a,fields:i}=n||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1123
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];a&&a.forEach(w=>u.push(`labels = "${w}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?Nt:kt,c=new URL(`${z(r,t,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",qe.toString()),c.searchParams.set("fields",ut.join(",")),c.searchParams.set("expand","transitions"),s&&(p?c.searchParams.set("startAt",s):c.searchParams.set("nextPageToken",s));let g=await r.request({url:c.toString(),headers:R(t.token||r.token)}),m=g.body.issues.map(w=>lt(w,i,e,o)),h=!1,I="";return p?(h=m.length==qe,I=(parseInt(s??"0",10)+m.length).toString()):(h=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:h,endCursor:I}}},Ft=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,jql:a,fields:i}=n||{},u=[...ut],l=i==null?void 0:i.Sprint;l&&u.push(l);let p=!o,d=p?Nt:kt,c=new URL(`${z(r,t,o)}${d}`);c.searchParams.set("jql",a.join(" AND ")),c.searchParams.set("maxResults",qe.toString()),c.searchParams.set("fields",u.join(",")),c.searchParams.set("expand","transitions"),s&&(p?c.searchParams.set("startAt",s):c.searchParams.set("nextPageToken",s));let g=await r.request({url:c.toString(),headers:R(t.token||r.token)}),m=g.body.issues.map(w=>lt(w,i,e,o)),h=!1,I="";return p?(h=m.length==qe,I=(parseInt(s??"0",10)+m.length).toString()):(h=!!g.body.nextPageToken,I=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:h,endCursor:I}}},Ue=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:a,labelNames:i,cursor:u,projectKey:l,resourceId:p,fields:d}=n||{},c=[`project = "${l}"`,"statusCategory != Done"];return o&&c.push(`creator in ("${o}")`),s&&s.length!==0&&c.push(`assignee in ("${s.join('", "')}")`),a&&c.push(`comment ~ "${a}"`),i&&i.forEach(g=>c.push(`labels = "${g}"`)),Ft(r,{resourceId:p,jql:c,cursor:u,fields:d},e,t)},$e=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:a,labelNames:i,cursor:u,projectKeys:l,resourceId:p,fields:d}=n||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),s&&s.length!==0&&g.push(`assignee in ("${s.join('", "')}")`),a&&g.push(`comment ~ "${a}"`),i&&i.forEach(m=>g.push(`labels = "${m}"`)),Ft(r,{resourceId:p,jql:g,fields:d,cursor:u},e,t)},Ae=async(r,n,e={})=>{let{issue:t,labels:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:s.map(a=>a.name)}};await r.request({method:"PUT",url:`${z(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},Ge=async(r,n,e={})=>{let{issue:t,components:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:s.map(a=>({id:a.id}))}};await r.request({method:"PUT",url:`${z(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},Te=async(r,n,e={})=>{let{issue:t,status:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!s.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:s.id}};await r.request({method:"POST",url:`${z(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},Oe=async(r,n,e={})=>{let{resourceId:t,projectIdOrKey:s}=n,o=new URL(`${z(r,e,t)}/rest/api/2/project/${s}/components`);return{data:(await r.request({url:o.toString(),headers:R(e.token||r.token)})).body}};var ie="https://api.atlassian.com/ex/jira",pt=100,se=class extends T{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let s=await Ce(this.config,e,t);this._issueFieldsCache[e.resourceId]=s.reduce((o,a)=>({...o,[a.name]:a.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){var a;let s=t.token||this.config.token;if(!s)return null;let o=this._resourceUrlCache[s];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),((a=this._resourceUrlCache[s])==null?void 0:a[e.resourceId])??null)}async getCurrentUserForResource(e,t={}){let s=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||ie}/${e.resourceId}/rest/api/2/myself`,headers:R(t.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:s?`${s}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let t=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),s=e.token||this.config.token,o=s?this._resourceUrlCache[s]||{}:void 0,a=t.body.map(i=>(o&&(o[i.id]=i.url),{avatarUrl:i.avatarUrl,id:i.id,name:i.name,url:i.url}));return s&&(this._resourceUrlCache[s]=o),{data:a}}async getJiraProjectsForResource(e,t={}){let s=new URL(`${t.baseUrl||ie}/${e.resourceId}/rest/api/2/project/search`);s.searchParams.set("maxResults",pt.toString()),e.cursor&&s.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:s.toString(),headers:R(t.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(a=>({id:a.id,key:a.key,name:a.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let s=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await bt(a=>this.getJiraProjectsForResource({resourceId:o,cursor:a},t))}catch{return[]}})).then((...o)=>{o.forEach(a=>{s=s.concat(...a)})}),{data:s}}async getAccountsForJiraProject(e,t={}){let{resourceId:s,projectKey:o,cursor:a}=e,i=await this.getResourceUrl({resourceId:s},t),u=new URL(`${t.baseUrl||ie}/${s}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",pt.toString()),a&&u.searchParams.set("startAt",a),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((a?parseInt(a):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Ee(p,i,!1))}}async getComponentsForJiraProject(e,t={}){return await Oe(this.config,e,t)}async getIssue(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await De(this.config,{...e,fields:s},o,t)}async getIssuesForProject(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ue(this.config,{...e,fields:s},o,t)}async getIssuesForProjects(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await $e(this.config,{...e,fields:s},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Le(this.config,{...e,fields:s},o,t)}async setIssueStatus(e,t={}){await Te(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:s,assignee:o}=e;if(!s.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!s.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let a={accountId:o==null?void 0:o.id};await this.config.request({method:"PUT",url:`${t.baseUrl||ie}/${s.project.resourceId}/rest/api/2/issue/${s.id}/assignee`,body:JSON.stringify(a),headers:{...R(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await Ge(this.config,e,t)}async setIssueLabels(e,t={}){await Ae(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:s,cursor:o}=e,a=new URL(`${t.baseUrl||ie}/${s}/rest/api/2/label`);a.searchParams.set("maxResults",pt.toString()),o&&a.searchParams.set("startAt",o);let i=await this.config.request({url:a.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:!i.body.isLast,endCursor:(i.body.startAt+i.body.values.length).toString()},data:i.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var ne=class extends k{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=(e==null?void 0:e.baseUrl)||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let s=await Ce(this.config,{},e);this._issueFieldsCache[t]=s.reduce((o,a)=>({...o,[a.name]:a.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/myself`,headers:R((e==null?void 0:e.token)||this.config.token)});return{data:{name:t.body.displayName,email:t.body.emailAddress,avatarUrl:t.body.avatarUrls["48x48"],id:t.body.key,username:t.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/project`,headers:R((e==null?void 0:e.token)||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getIssue(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await De(this.config,{...e,fields:o},s,t)}async getIssuesForProject(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ue(this.config,{...e,fields:o},s,t)}async getIssuesForProjects(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await $e(this.config,{...e,fields:o},s,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Le(this.config,{...e,fields:o},s,t)}async setIssueStatus(e,t={}){await Te(this.config,e,t)}async setIssueLabels(e,t={}){await Ae(this.config,e,t)}async setIssueComponents(e,t={}){await Ge(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:R(e.token||this.config.token)})).body.results.map(({displayName:s})=>({color:null,description:null,id:null,name:s}))}}async getComponentsForJiraProject(e,t={}){return await Oe(this.config,e,t)}};var N="https://api.trello.com",os=1e3,as=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),is=(r,n)=>{let e=new Date(1e3*parseInt(r.id.substring(0,8),16));return{id:r.id,commentCount:r.badges.comments,number:r.idShort.toString(),title:r.name,url:r.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(r.dateLastActivity),assignees:r.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:n[r.idList??""]?{id:r.idList,name:n[r.idList].name,color:null}:null,type:null,repository:null,upvoteCount:r.badges.votes,labels:r.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},oe=class extends T{async getCurrentUser(n,e={}){let t=await this.config.request({url:`${e.baseUrl||N}/1/members/me?key=${n.appKey}&token=${e.token||this.config.token}`,headers:R(e.token||this.config.token)});return{data:{name:t.body.fullName,email:t.body.email,avatarUrl:t.body.avatarHash?`https://trello-members.s3.amazonaws.com/${t.body.id}/${t.body.avatarHash}/50.png`:null,id:t.body.id,username:t.body.username,url:t.body.url}}}async getBoardsForCurrentUser(n,e={}){return{data:(await this.config.request({url:`${e.baseUrl||N}/1/members/me/boards?fields=name&key=${n.appKey}&token=${e.token||this.config.token}&filter=open`,headers:R(e.token||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getListsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||N}/1/boards/${s}/lists?key=${t}&token=${e.token||this.config.token}`,headers:R(e.token||this.config.token)})).body}}async getAccountForId(n,e={}){let{appKey:t,memberId:s}=n,o=await this.config.request({url:`${e.baseUrl||N}/1/members/${s}/?key=${t}&token=${e.token||this.config.token}`});return{data:as(o.body)}}async getAccountsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||N}/1/boards/${s}/members?key=${t}&token=${e.token||this.config.token}`,headers:R(e.token||this.config.token)})).body.map(a=>({id:a.id,name:a.fullName,username:a.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(n,e={}){let t=["-is:archived","sort:edited"],{appKey:s,boardId:o,filterText:a,assigneeLogins:i,labelNamesOrColors:u,trelloBoardListsById:l}=n||{};i&&t.push("@me"),u&&u.forEach(c=>t.push(`label:"${c}"`));let p=`${a?`${a}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||N}/1/search?key=${s}&query=${p}&cards_limit=${os}&token=${e.token||this.config.token}&card_members=true`,headers:R(e.token||this.config.token)})).body.cards.map(c=>is(c,l||{}))}}async updateIssue(n,e,t,s){return await this.config.request({method:"PUT",url:`${s.baseUrl||N}/1/cards/${e.id}?key=${n}&token=${s.token||this.config.token}&${t}`,headers:R(s.token||this.config.token)})}async setIssueStatus(n,e={}){let{appKey:t,issue:s,status:o}=n;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let a=`idList=${o.id}`;if(!(await this.updateIssue(t,s,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(n,e={}){let{appKey:t,issue:s,assignees:o}=n,a=o.map(l=>l.id),i=`idMembers=${encodeURIComponent(a.join(","))}`;if(!(await this.updateIssue(t,s,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(n,e={}){let{appKey:t,issue:s,labels:o}=n,a=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||N}/1/cards/${s.id}?key=${t}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(a)}`,headers:R(e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(n,e={}){let{appKey:t,issue:s,archived:o}=n;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||N}/1/cards/${s.id}?key=${t}&token=${e.token||this.config.token}&closed=${o}`,headers:R(e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!0},e)}async unArchiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!1},e)}async getLabelsForBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||N}/1/boards/${s}/labels?key=${t}&token=${e.token||this.config.token}`,headers:R(e.token||this.config.token)})).body.map(a=>({color:a.color,description:null,id:a.id,name:a.name}))}}};var Qt=r=>{let n={request:r==null?void 0:r.request};return{azureDevOps:new K({...n,...r==null?void 0:r.azureDevOps}),bitbucket:new V({...n,...r==null?void 0:r.bitbucket}),bitbucketServer:new X({...n,...r==null?void 0:r.bitbucketServer}),github:new ee({...n,...r==null?void 0:r.github}),gitlab:new re({...n,...r==null?void 0:r.gitlab}),jira:new se({...n,...r==null?void 0:r.jira}),jiraServer:new ne({...n,...r==null?void 0:r.jiraServer}),trello:new oe({...n,...r==null?void 0:r.trello})}};var _t=(a=>(a.Conflicts="conflicts",a.Failure="failure",a.NotSet="notSet",a.Queued="queued",a.RejectedByPolicy="rejectedByPolicy",a.Succeeded="succeeded",a))(_t||{});var Bt=(e=>(e.Zero="0",e.One="1",e))(Bt||{}),jt=(e=>(e.PullRequest="pr",e.Issue="issue",e))(jt||{}),Mt=(p=>(p.Azure="azure",p.Github="github",p.GithubEnterprise="githubEnterprise",p.Gitlab="gitlab",p.GitlabSelfHosted="gitlabSelfHosted",p.Bitbucket="bitbucket",p.BitbucketServer="bitbucketServer",p.Jira="jira",p.JiraServer="jiraServer",p.Trello="trello",p))(Mt||{});var zt=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(zt||{});var us=Qt;
1122
+ `,variables:{fullPath:`${t}/${s}`,after:o}},e);return{pageInfo:((l=(u=(i=a.body.data)==null?void 0:i.project)==null?void 0:u.labels)==null?void 0:l.pageInfo)??{endCursor:null,hasNextPage:!1},data:((g=(c=(d=(p=a.body.data)==null?void 0:p.project)==null?void 0:d.labels)==null?void 0:c.nodes)==null?void 0:g.map(at))??[]}}async getTreeForRepo(n,e={}){let t=z(n.repo),s=new URL(n.cursor??`${we(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);s.searchParams.set("per_page","10000"),s.searchParams.set("recursive","true"),s.searchParams.set("pagination","keyset"),s.searchParams.set("ref",n.branch);let o=await this.config.request({url:s.toString(),headers:R(e.token||this.config.token)}),a=o.headers.link;return{data:o.body.map(Jr),pageInfo:{endCursor:a?a.substring(1,a.indexOf(">")):null,hasNextPage:!!a}}}};var Zr="https://api.atlassian.com/ex/jira",Ee=100,ut=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],kt="/rest/api/2/search/jql",Nt="/rest/api/2/search",lt=(r,n,e,t)=>{var i,u,l,p;let s=r.fields.assignee,o=!t,a=(r.fields[(n==null?void 0:n.Sprint)??""]??[]).filter(d=>typeof d=="object");return{id:r.id,commentCount:r.fields.comment.comments.length,number:r.key,title:r.fields.summary,url:e?`${e}/browse/${r.key}`:null,closedDate:null,createdDate:new Date(r.fields.created),author:qe(r.fields.creator,e,o),updatedDate:new Date(r.fields.updated),assignees:s?[qe(s,e,o)]:[],description:r.fields.description,repository:null,project:{name:r.fields.project.name,resourceId:t??null,key:r.fields.project.key,namespace:null,id:r.fields.project.id},state:rs(r.fields.status),statusTransitions:((i=r.transitions)==null?void 0:i.map(Yr))??[],components:((u=r.fields.components)==null?void 0:u.map(es))??[],type:r.fields.issuetype.name,upvoteCount:((l=r.fields.votes)==null?void 0:l.votes)||0,labels:((p=r.fields.labels)==null?void 0:p.map(d=>({color:null,description:null,id:null,name:d})))??[],sprints:a.map(ss),fixVersions:r.fields.fixVersions.map(ns)}},Yr=r=>{let n;switch(r.to.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{name:r.name,id:r.id,to:{id:r.to.id,name:r.to.name,color:r.to.statusCategory.colorName,category:n}}},es=r=>({description:r.description??null,id:r.id,name:r.name}),ts=(r,n,e)=>e&&r.name?`${n}/secure/ViewProfile.jspa?name=${encodeURIComponent(r.name)}`:`${n}/jira/people/${r.accountId}`,qe=(r,n,e)=>({id:(e?r.key:r.accountId)??"",name:r.displayName,email:r.emailAddress,avatarUrl:r.avatarUrls["48x48"],username:r.displayName,url:ts(r,n,e)}),rs=r=>{let n;switch(r.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{id:r.id,name:r.name,color:r.statusCategory.colorName,category:n}},ss=r=>({id:r.id.toString(),name:r.name,isActive:r.state==="active",startDate:r.startDate?new Date(r.startDate):null,endDate:r.endDate?new Date(r.endDate):null,completedDate:r.completeDate?new Date(r.completeDate):null}),ns=r=>({id:r.id,description:r.description,name:r.name,archived:r.archived,released:r.released,releaseDate:r.releaseDate?new Date(r.releaseDate):null}),W=(r,n,e)=>e?`${n.baseUrl||Zr}/${e}`:`${(n==null?void 0:n.baseUrl)||r.baseUrl}`,Ce=async(r,n,e={})=>{let{resourceId:t}=n;return(await r.request({url:`${W(r,e,t)}/rest/api/2/field`,headers:R(e.token||r.token)})).body},De=async(r,n,e,t={})=>{let{number:s,resourceId:o,fields:a}=n||{},i=await r.request({url:`${W(r,t,o)}/rest/api/2/issue/${s}?fields=${ut.join(",")}&expand=transitions`,headers:R(t.token||r.token)});return{data:lt(i.body,a,e,o)}},Le=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,labelNames:a,fields:i}=n||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1123
+ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];a&&a.forEach(P=>u.push(`labels = "${P}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?Nt:kt,c=new URL(`${W(r,t,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",Ee.toString()),c.searchParams.set("fields",ut.join(",")),c.searchParams.set("expand","transitions"),s&&(p?c.searchParams.set("startAt",s):c.searchParams.set("nextPageToken",s));let g=await r.request({url:c.toString(),headers:R(t.token||r.token)}),m=g.body.issues.map(P=>lt(P,i,e,o)),I=!1,h="";return p?(I=m.length==Ee,h=(parseInt(s??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,h=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:h}}},Ft=async(r,n,e,t={})=>{let{cursor:s,resourceId:o,jql:a,fields:i}=n||{},u=[...ut],l=i==null?void 0:i.Sprint;l&&u.push(l);let p=!o,d=p?Nt:kt,c=new URL(`${W(r,t,o)}${d}`);c.searchParams.set("jql",a.join(" AND ")),c.searchParams.set("maxResults",Ee.toString()),c.searchParams.set("fields",u.join(",")),c.searchParams.set("expand","transitions"),s&&(p?c.searchParams.set("startAt",s):c.searchParams.set("nextPageToken",s));let g=await r.request({url:c.toString(),headers:R(t.token||r.token)}),m=g.body.issues.map(P=>lt(P,i,e,o)),I=!1,h="";return p?(I=m.length==Ee,h=(parseInt(s??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,h=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:h}}},Ue=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:a,labelNames:i,cursor:u,projectKey:l,resourceId:p,fields:d}=n||{},c=[`project = "${l}"`,"statusCategory != Done"];return o&&c.push(`creator in ("${o}")`),s&&s.length!==0&&c.push(`assignee in ("${s.join('", "')}")`),a&&c.push(`comment ~ "${a}"`),i&&i.forEach(g=>c.push(`labels = "${g}"`)),Ft(r,{resourceId:p,jql:c,cursor:u,fields:d},e,t)},$e=async(r,n,e,t={})=>{let{assigneeLogins:s,authorLogin:o,mentionLogin:a,labelNames:i,cursor:u,projectKeys:l,resourceId:p,fields:d}=n||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),s&&s.length!==0&&g.push(`assignee in ("${s.join('", "')}")`),a&&g.push(`comment ~ "${a}"`),i&&i.forEach(m=>g.push(`labels = "${m}"`)),Ft(r,{resourceId:p,jql:g,fields:d,cursor:u},e,t)},Ae=async(r,n,e={})=>{let{issue:t,labels:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:s.map(a=>a.name)}};await r.request({method:"PUT",url:`${W(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},Ge=async(r,n,e={})=>{let{issue:t,components:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:s.map(a=>({id:a.id}))}};await r.request({method:"PUT",url:`${W(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},Te=async(r,n,e={})=>{let{issue:t,status:s}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!s.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:s.id}};await r.request({method:"POST",url:`${W(r,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||r.token),"Content-Type":"application/json"}})},Oe=async(r,n,e={})=>{let{resourceId:t,projectIdOrKey:s}=n,o=new URL(`${W(r,e,t)}/rest/api/2/project/${s}/components`);return{data:(await r.request({url:o.toString(),headers:R(e.token||r.token)})).body}};var ie="https://api.atlassian.com/ex/jira",pt=100,se=class extends T{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let s=await Ce(this.config,e,t);this._issueFieldsCache[e.resourceId]=s.reduce((o,a)=>({...o,[a.name]:a.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){var a;let s=t.token||this.config.token;if(!s)return null;let o=this._resourceUrlCache[s];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),((a=this._resourceUrlCache[s])==null?void 0:a[e.resourceId])??null)}async getCurrentUserForResource(e,t={}){let s=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||ie}/${e.resourceId}/rest/api/2/myself`,headers:R(t.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:s?`${s}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let t=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),s=e.token||this.config.token,o=s?this._resourceUrlCache[s]||{}:void 0,a=t.body.map(i=>(o&&(o[i.id]=i.url),{avatarUrl:i.avatarUrl,id:i.id,name:i.name,url:i.url}));return s&&(this._resourceUrlCache[s]=o),{data:a}}async getJiraProjectsForResource(e,t={}){let s=new URL(`${t.baseUrl||ie}/${e.resourceId}/rest/api/2/project/search`);s.searchParams.set("maxResults",pt.toString()),e.cursor&&s.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:s.toString(),headers:R(t.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(a=>({id:a.id,key:a.key,name:a.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let s=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await bt(a=>this.getJiraProjectsForResource({resourceId:o,cursor:a},t))}catch{return[]}})).then((...o)=>{o.forEach(a=>{s=s.concat(...a)})}),{data:s}}async getAccountsForJiraProject(e,t={}){let{resourceId:s,projectKey:o,cursor:a}=e,i=await this.getResourceUrl({resourceId:s},t),u=new URL(`${t.baseUrl||ie}/${s}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",pt.toString()),a&&u.searchParams.set("startAt",a),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((a?parseInt(a):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>qe(p,i,!1))}}async getComponentsForJiraProject(e,t={}){return await Oe(this.config,e,t)}async getIssue(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await De(this.config,{...e,fields:s},o,t)}async getIssuesForProject(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ue(this.config,{...e,fields:s},o,t)}async getIssuesForProjects(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await $e(this.config,{...e,fields:s},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Le(this.config,{...e,fields:s},o,t)}async setIssueStatus(e,t={}){await Te(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:s,assignee:o}=e;if(!s.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!s.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let a={accountId:o==null?void 0:o.id};await this.config.request({method:"PUT",url:`${t.baseUrl||ie}/${s.project.resourceId}/rest/api/2/issue/${s.id}/assignee`,body:JSON.stringify(a),headers:{...R(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await Ge(this.config,e,t)}async setIssueLabels(e,t={}){await Ae(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:s,cursor:o}=e,a=new URL(`${t.baseUrl||ie}/${s}/rest/api/2/label`);a.searchParams.set("maxResults",pt.toString()),o&&a.searchParams.set("startAt",o);let i=await this.config.request({url:a.toString(),headers:R(t.token||this.config.token)});return{pageInfo:{hasNextPage:!i.body.isLast,endCursor:(i.body.startAt+i.body.values.length).toString()},data:i.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var ne=class extends k{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=(e==null?void 0:e.baseUrl)||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let s=await Ce(this.config,{},e);this._issueFieldsCache[t]=s.reduce((o,a)=>({...o,[a.name]:a.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/myself`,headers:R((e==null?void 0:e.token)||this.config.token)});return{data:{name:t.body.displayName,email:t.body.emailAddress,avatarUrl:t.body.avatarUrls["48x48"],id:t.body.key,username:t.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/project`,headers:R((e==null?void 0:e.token)||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getIssue(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await De(this.config,{...e,fields:o},s,t)}async getIssuesForProject(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ue(this.config,{...e,fields:o},s,t)}async getIssuesForProjects(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await $e(this.config,{...e,fields:o},s,t)}async getIssuesForResourceForCurrentUser(e,t={}){let s=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!s)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Le(this.config,{...e,fields:o},s,t)}async setIssueStatus(e,t={}){await Te(this.config,e,t)}async setIssueLabels(e,t={}){await Ae(this.config,e,t)}async setIssueComponents(e,t={}){await Ge(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${(e==null?void 0:e.baseUrl)||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:R(e.token||this.config.token)})).body.results.map(({displayName:s})=>({color:null,description:null,id:null,name:s}))}}async getComponentsForJiraProject(e,t={}){return await Oe(this.config,e,t)}};var N="https://api.trello.com",os=1e3,as=r=>({id:r.id,username:r.username,url:r.url,name:r.fullName,email:r.email,avatarUrl:r.avatarUrl}),is=(r,n)=>{let e=new Date(1e3*parseInt(r.id.substring(0,8),16));return{id:r.id,commentCount:r.badges.comments,number:r.idShort.toString(),title:r.name,url:r.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(r.dateLastActivity),assignees:r.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:n[r.idList??""]?{id:r.idList,name:n[r.idList].name,color:null}:null,type:null,repository:null,upvoteCount:r.badges.votes,labels:r.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},oe=class extends T{async getCurrentUser(n,e={}){let t=await this.config.request({url:`${e.baseUrl||N}/1/members/me?key=${n.appKey}&token=${e.token||this.config.token}`,headers:R(e.token||this.config.token)});return{data:{name:t.body.fullName,email:t.body.email,avatarUrl:t.body.avatarHash?`https://trello-members.s3.amazonaws.com/${t.body.id}/${t.body.avatarHash}/50.png`:null,id:t.body.id,username:t.body.username,url:t.body.url}}}async getBoardsForCurrentUser(n,e={}){return{data:(await this.config.request({url:`${e.baseUrl||N}/1/members/me/boards?fields=name&key=${n.appKey}&token=${e.token||this.config.token}&filter=open`,headers:R(e.token||this.config.token)})).body.map(s=>({id:s.id,name:s.name}))}}async getListsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||N}/1/boards/${s}/lists?key=${t}&token=${e.token||this.config.token}`,headers:R(e.token||this.config.token)})).body}}async getAccountForId(n,e={}){let{appKey:t,memberId:s}=n,o=await this.config.request({url:`${e.baseUrl||N}/1/members/${s}/?key=${t}&token=${e.token||this.config.token}`});return{data:as(o.body)}}async getAccountsForTrelloBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||N}/1/boards/${s}/members?key=${t}&token=${e.token||this.config.token}`,headers:R(e.token||this.config.token)})).body.map(a=>({id:a.id,name:a.fullName,username:a.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(n,e={}){let t=["-is:archived","sort:edited"],{appKey:s,boardId:o,filterText:a,assigneeLogins:i,labelNamesOrColors:u,trelloBoardListsById:l}=n||{};i&&t.push("@me"),u&&u.forEach(c=>t.push(`label:"${c}"`));let p=`${a?`${a}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||N}/1/search?key=${s}&query=${p}&cards_limit=${os}&token=${e.token||this.config.token}&card_members=true`,headers:R(e.token||this.config.token)})).body.cards.map(c=>is(c,l||{}))}}async updateIssue(n,e,t,s){return await this.config.request({method:"PUT",url:`${s.baseUrl||N}/1/cards/${e.id}?key=${n}&token=${s.token||this.config.token}&${t}`,headers:R(s.token||this.config.token)})}async setIssueStatus(n,e={}){let{appKey:t,issue:s,status:o}=n;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let a=`idList=${o.id}`;if(!(await this.updateIssue(t,s,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(n,e={}){let{appKey:t,issue:s,assignees:o}=n,a=o.map(l=>l.id),i=`idMembers=${encodeURIComponent(a.join(","))}`;if(!(await this.updateIssue(t,s,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(n,e={}){let{appKey:t,issue:s,labels:o}=n,a=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||N}/1/cards/${s.id}?key=${t}&token=${e.token||this.config.token}&idLabels=${encodeURIComponent(a)}`,headers:R(e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(n,e={}){let{appKey:t,issue:s,archived:o}=n;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||N}/1/cards/${s.id}?key=${t}&token=${e.token||this.config.token}&closed=${o}`,headers:R(e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!0},e)}async unArchiveIssue(n,e={}){await this.setIssueArchived({...n,archived:!1},e)}async getLabelsForBoard(n,e={}){let{appKey:t,boardId:s}=n;return{data:(await this.config.request({url:`${e.baseUrl||N}/1/boards/${s}/labels?key=${t}&token=${e.token||this.config.token}`,headers:R(e.token||this.config.token)})).body.map(a=>({color:a.color,description:null,id:a.id,name:a.name}))}}};var _t=r=>{let n={request:r==null?void 0:r.request};return{azureDevOps:new K({...n,...r==null?void 0:r.azureDevOps}),bitbucket:new X({...n,...r==null?void 0:r.bitbucket}),bitbucketServer:new Z({...n,...r==null?void 0:r.bitbucketServer}),github:new ee({...n,...r==null?void 0:r.github}),gitlab:new re({...n,...r==null?void 0:r.gitlab}),jira:new se({...n,...r==null?void 0:r.jira}),jiraServer:new ne({...n,...r==null?void 0:r.jiraServer}),trello:new oe({...n,...r==null?void 0:r.trello})}};var Qt=(a=>(a.Conflicts="conflicts",a.Failure="failure",a.NotSet="notSet",a.Queued="queued",a.RejectedByPolicy="rejectedByPolicy",a.Succeeded="succeeded",a))(Qt||{});var jt=(e=>(e.Zero="0",e.One="1",e))(jt||{}),Bt=(e=>(e.PullRequest="pr",e.Issue="issue",e))(Bt||{}),Mt=(p=>(p.Azure="azure",p.Github="github",p.GithubEnterprise="githubEnterprise",p.Gitlab="gitlab",p.GitlabSelfHosted="gitlabSelfHosted",p.Bitbucket="bitbucket",p.BitbucketServer="bitbucketServer",p.Jira="jira",p.JiraServer="jiraServer",p.Trello="trello",p))(Mt||{});var zt=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(zt||{});var us=_t;