@gitkraken/provider-apis 0.46.0 → 0.46.2

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,5 +1,5 @@
1
- "use strict";var tt=Object.defineProperty;var zr=Object.getOwnPropertyDescriptor;var Hr=Object.getOwnPropertyNames;var Wr=Object.prototype.hasOwnProperty;var Jr=(s,n)=>{for(var e in n)tt(s,e,{get:n[e],enumerable:!0})},Vr=(s,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Hr(n))!Wr.call(s,r)&&r!==e&&tt(s,r,{get:()=>n[r],enumerable:!(t=zr(n,r))||t.enumerable});return s};var Kr=s=>Vr(tt({},"__esModule",{value:!0}),s);var Un={};Jr(Un,{AzureDevOps:()=>ne,Bitbucket:()=>oe,BitbucketServer:()=>ie,EntityIdentifierProviderType:()=>jr,EntityType:()=>Fr,EntityVersion:()=>Nr,GitBuildStatusStage:()=>Mt,GitBuildStatusState:()=>ve,GitDiffLineType:()=>rt,GitHub:()=>ae,GitHubIssueCloseReason:()=>Qr,GitIssueState:()=>De,GitLab:()=>le,GitMergeStrategy:()=>se,GitPullRequestMergeableState:()=>ee,GitPullRequestReviewState:()=>K,GitPullRequestState:()=>Y,GraphQLErrors:()=>R,Jira:()=>pe,JiraServer:()=>de,PullRequestAsyncStatus:()=>kr,Trello:()=>ce,default:()=>Dn,isFetch:()=>Se});module.exports=Kr(Un);var Yt=require("diff");var Mt=(r=>(r.Build="build",r.Production="production",r.Staging="staging",r.Test="test",r))(Mt||{}),ve=(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))(ve||{}),se=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(se||{}),Y=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(Y||{}),K=(r=>(r.Approved="APPROVED",r.ChangesRequested="CHANGES_REQUESTED",r.Commented="COMMENTED",r.ReviewRequested="REVIEW_REQUESTED",r))(K||{}),ee=(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))(ee||{}),rt=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(rt||{});var zt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},Q=s=>!s||s.length===0?null:s.reduce((n,e)=>zt[e.state]>zt[n]?e.state:n,"APPROVED");var st=(a=>(a[a.Unknown=0]="Unknown",a[a.Active=1]="Active",a[a.Fixed=2]="Fixed",a[a.WontFix=3]="WontFix",a[a.Closed=4]="Closed",a[a.ByDesign=5]="ByDesign",a[a.Pending=6]="Pending",a))(st||{});var L=100;var Ht=globalThis.fetch;var Xr=async s=>{let n=s.headers.get("content-type")||"",e=null;if(n.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(n.startsWith("text/")||n==="")e=await s.text();else if(n.startsWith("application/vnd.github.raw+json")||n.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${n}`);let t={};s.headers.forEach((o,i)=>{t[i]=o});let r={body:e,headers:t,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:r}),o}return r},nt=s=>async({url:n,...e})=>{let t=await s(n,e);return Xr(t)};var Se=(s,n=!1)=>s.name==="fetch"||n;var N=class{constructor(n){let e=n?.request||Ht;this.config={...n,request:Se(e,n?.forceIsFetch)?nt(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&Se(n.request,n?.forceIsFetch??this.config.forceIsFetch)?nt(n.request):this.config.request}}},_=class extends N{};var f=(s,n)=>{let e={};return s&&(e.Authorization=`${n?"Basic":"Bearer"} ${s}`),e},Wt=s=>s?s.reduce((n,e)=>(n[e]=!0,n),{}):void 0,X=(s,n,e)=>!s||n.some(t=>s[t])?e:"",Jt=async s=>{let n=[],e=!0,t;for(;e;){let r=await s(t);n=n.concat(r.data),e=!!r?.pageInfo?.hasNextPage,t=r?.pageInfo?.endCursor||r?.pageInfo?.nextPage}return n};async function ot(s){return(await Promise.allSettled(s)).map(e=>Zr(e)).filter(e=>e!=null)}function Zr(s,n=void 0){return s?.status==="fulfilled"?s.value:n}var Yr="https://app.vssps.visualstudio.com/_apis",es="https://vssps.dev.azure.com/",ts="https://dev.azure.com",P=(s,n={})=>f(n.token||s.token,n.isPAT||s.isPAT),Vt=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),it=(s,n)=>{let e=n.baseUrl||s.baseUrl||Yr;return e=e.replace(/\/$/,""),e},C=(s,n)=>{let e=n.baseUrl||s.baseUrl||ts;return e=e.replace(/\/$/,""),e},at=(s,n)=>{let e=n.baseUrl||s.baseUrl||es;return e=e.replace(/\/$/,""),e};var rs={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},ss=s=>{if(typeof s!="string")return s;let n=s.charAt(0).toUpperCase()+s.slice(1);return st[n]??0},ns=new Set([2,3,4,5]),os={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},te=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Ee=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,is=s=>{switch(s){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},ut=(s,n,e,t,r,o)=>`${s}|${n}|${e}|${t}|${r}|${o}`,Kt=s=>{let n=s.split("|");if(n.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4],commentId:n[5]}},Xt=(s,n,e,t,r)=>`${s}|${n}|${e}|${t}|${r}`,lt=s=>{let n=s.split("|");if(n.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4]}},he=(s,n)=>{let e=[],t=[];return n.reviewers.forEach(r=>{let o={reviewer:te(r),state:os[r.vote??0]||"REVIEW_REQUESTED"};r.isRequired&&e.push(o),t.push(o)}),{id:n.pullRequestId.toString(),title:n.title,description:n.description??null,number:n.codeReviewId,state:rs[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:te(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:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Ee(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:Ee(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:Vt(n),assignees:n.reviewers.map(te),reviews:t,reviewDecision:Q(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:s},remoteInfo:null}:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:is(n.mergeStatus),labels:n.labels?.map(r=>({color:null,description:null,id:r.id,name:r.name}))??[],permissions:null}},Zt=(s,n)=>({id:n.id,name:n.name,namespace:s,project:n.project.name,projectId:n.project.id,webUrl:n.webUrl,httpsUrl:n.remoteUrl,sshUrl:n.sshUrl,defaultBranch:n.defaultBranch?{name:Ee(n.defaultBranch)}:null,permissions:null}),as=(s,n,e,t)=>{let r=e.fields,o=r["System.AssignedTo"],i=r["System.State"],a=r["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:r["System.Title"],commentCount:r["System.CommentCount"],author:{avatarUrl:r["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:r["System.CreatedBy"].id,name:r["System.CreatedBy"].uniqueName??null,username:r["System.CreatedBy"].displayName??null,url:null},closedDate:r["Microsoft.VSTS.Common.ClosedDate"]?new Date(r["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(r["System.CreatedDate"]),updatedDate:new Date(r["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:r["System.Description"]??null,state:{name:u?.title||i,color:null},type:r["System.WorkItemType"],repository:null,project:{namespace:s,name:n,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},ne=class extends _{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let r=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.baseUrl??null]),o=this.cachedUserIds.get(r);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(r);if(i)return i;let a=this.fetchCurrentUserId(e,t,r);return this.inflightUserIds.set(r,a),a}async fetchCurrentUserId(e,t,r){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(r,o.data.id),o.data.id}finally{this.inflightUserIds.delete(r)}}getRepoApiUrl(e,t,r,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(r)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${it(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:r,headers:P(this.config,t)});return{data:{id:o.body.id,name:o.body.displayName,username:o.body.displayName,email:o.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(e,t={}){let o=(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:P(this.config,t)})).body.authorizedUser;if(o.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:o.id,name:o.providerDisplayName,username:o.providerDisplayName,email:o.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:P(this.config,t)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,t={}){let r=`${it(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:P(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let r=`${C(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:P(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let r=new URL(`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/projects`);r.searchParams.set("$top",L.toString()),e.cursor&&r.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:r.toString(),headers:P(this.config,t)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({id:a.id,name:a.name,namespace:e.namespace}))}}async getAzureProjectScopeDescriptor(e,t={}){let{namespace:r,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${at(this.config,t)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:P(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:r,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${at(this.config,t)}/${encodeURIComponent(r)}/_apis/graph/users`);o&&a.searchParams.set("scopeDescriptor",o),i&&a.searchParams.set("continuationToken",i);let u=await this.config.request({url:a.toString(),headers:P(this.config,t)}),l=u.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:l||null,hasNextPage:!!l},data:u.body.value.map(p=>({avatarUrl:p._links?.avatar?.href??null,descriptor:p.descriptor??null,email:p.mailAddress??null,name:p.displayName??null,storageKeyURL:p._links?.storageKey?.href??null,username:p.displayName??null}))}}async getAccountFromAzureGraphAccount(e,t={}){let{azureGraphAccount:r}=e;if(!r.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:r.storageKeyURL,headers:P(this.config,t)});return{data:{avatarUrl:r.avatarUrl,email:r.email,id:o.body.value,name:r.name,username:r.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let r=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);r.push(i.data)}return{data:r}}async getRepo(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:P(this.config,t)});return{data:Zt(e.namespace,r.body)}}async getRepos(e,t={}){let r=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);r.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:r,errors:o}}async getReposForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:P(this.config,t)})).body.value.map(o=>Zt(e.namespace,o))}}async getRefs(e,t,r={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${C(this.config,r)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",L.toString()),t.cursor&&o.searchParams.set("continuationToken",t.cursor);let i=await this.config.request({url:o.toString(),headers:P(this.config,r)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Ee(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,t={}){return this.getRefs("heads",e,t)}async getTags(e,t={}){return this.getRefs("tags",e,t)}async getPullRequestsForRepoBase(e,t={},r=100){let{page:o,repo:i,assigneeLogins:a,authorLogin:u}=e||{},l=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let p="searchCriteria.status=1";return a&&a.length&&(p+=`&searchCriteria.reviewerId=${a[0]}`),u&&(p+=`&searchCriteria.creatorId=${u}`),await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${p}&%24top=${r}&%24skip=${(l-1)*r}`,headers:P(this.config,t)})}async getPullRequestsForRepo(e,t={}){let o=e.page||1,i=await this.getPullRequestsForRepoBase(e,t,100);return{pageInfo:{hasNextPage:i.body.value.length===100,nextPage:o+1},data:i.body.value.map(a=>he(e.repo.namespace,a))}}async getPullRequestsForRepos(e,t={}){if(!e.repos.every(i=>i.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:r}=e||{},o=[];return await Promise.all(r.map(async i=>{try{(await this.getPullRequestsForRepoBase({repo:i,...e},t)).body.value.forEach(u=>{o.push(he(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getPullRequestsForProjectBase(e,t={},r=100){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,repo:p}=e;if(p?.project&&p.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,d=new URL(`${C(this.config,t)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",r.toString()),d.searchParams.set("$skip",((c-1)*r).toString()),p?.id&&p?.project===i&&d.searchParams.set("searchCriteria.repositoryId",p.id),u&&u.length&&d.searchParams.set("searchCriteria.reviewerId",u[0]),l&&d.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:d.toString(),headers:P(this.config,t)})}async getPullRequestsForProject(e,t={}){let o=e.page||1,i=await this.getPullRequestsForProjectBase(e,t,100);return{pageInfo:{hasNextPage:i?.body.value.length===100,nextPage:o+1},data:i?.body.value.map(a=>he(e.namespace,a))||[]}}async getPullRequestsForProjects(e,t={}){let{projects:r}=e||{},o=[];return await Promise.all(r.map(async i=>{try{(!e.repo||e.repo.project&&e.repo.project===i.project)&&(await this.getPullRequestsForProjectBase({...i,...e},t))?.body.value.forEach(u=>{o.push(he(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getAzurePullRequestLastMergeStatus(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:r,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...P(this.config,t)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,t,r){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${encodeURIComponent(e.repository.owner.login)}/${encodeURIComponent(e.repository.project)}/_apis/git/repositories/${e.repository.name}/pullrequests/${e.id}?api-version=6.0`,body:t,headers:{...P(this.config,r),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:r}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(r,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){let{pullRequest:r,mergeStrategy:o}=e,i;switch(o){case"MERGE_COMMIT":{i="noFastForward";break}case"REBASE":{i="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{i="rebaseMerge";break}case"SQUASH":{i="squash";break}}let a={completionOptions:{mergeStrategy:i},lastMergeSourceCommit:{commitId:r.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(a),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){let{pullRequest:r,label:o}=e;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i={name:o.name};if(!(await this.config.request({method:"POST",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...P(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,t={}){let{pullRequest:r,label:o}=e;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...P(this.config,t)}})}async setPullRequestLabels(e,t={}){let{pullRequest:r,labels:o}=e;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=r.labels;if(!i)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of o)i.find(u=>u.id===a.id)||await this.addPullRequestLabel({pullRequest:r,label:a},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:r,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:r,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(r,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){let{pullRequest:r,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...P(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,t={}){let{pullRequest:r,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${o.id}?api-version=6.0`,headers:{...P(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){let{pullRequest:r,reviewers:o}=e;for(let i of o)r.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:i,isRequired:!0},t);for(let i of r.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:r,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=r||1,c=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];i&&d.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&d.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&d.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(h=>d.push(`[System.Tags] Contains '${h}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...P(this.config,t),"Content-Type":"application/json"}}),I=m.body.workItems.slice((p-1)*c,c*p).map(h=>h.id);if(I.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let y=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:I,$expand:"Links"}),method:"POST",headers:{...P(this.config,t),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:m.body.workItems.length>c*p,nextPage:p+1},data:y.body.value.map(h=>as(e.namespace,e.project,h,l||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:r,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=c=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${c.projectId}/${c.id}`;return Object.keys(i).map(m=>({securityNamespaceId:d,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,t)}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...P(this.config,t),"Content-Type":"application/json"}})).body.evaluations.reduce((c,d)=>{let[,g,m]=d.token.split("/"),I=`${g}/${m}`,y=i[d.permissions];for(let h of y)c[I]===void 0&&(c[I]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(c[I][h]=!1);return c},{})}}async decorateReposWithPermissions(e,t={}){let{namespace:r,repos:o}=e,i=await this.getPermissionsForRepos({namespace:r,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,r={}){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(t),headers:{...P(this.config,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:r,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(r,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:r,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(r,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){let{issue:r,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(r,a,t)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:r,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...P(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:r,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...P(this.config,t)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,t={}){let{repo:r,number:o}=e;if(!r.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(r.namespace,r.project,r.name,t)}/pullrequests/${o}?api-version=7.1`,headers:P(this.config,t)});return{data:he(r.namespace,i.body)}}async getMergeBase(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:P(this.config,t)});if(!r.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:r.body.value[0].commitId}}async getFileContents(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...P(this.config,t),Accept:"application/octet-stream"}});return{data:new Blob([r.body])}}async getPullRequestDiff(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=P(this.config,t),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${r}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${r}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,p=a.body.lastMergeSourceCommit.commitId,c=u.body.value;if(c.length===0)return"";let d=c[c.length-1],m=(await this.config.request({url:`${r}/pullrequests/${e.pullRequestId}/iterations/${d.id}/changes?api-version=7.1`,headers:o})).body.changeEntries;if(m.length===0)return"";let I=5,y=[],h=new TextDecoder,q=v=>v instanceof ArrayBuffer?h.decode(v):typeof v=="string"?v:"",$=async(v,me)=>{try{let ge=await this.config.request({url:`${r}/items?path=${encodeURIComponent(v)}&versionDescriptor[version]=${encodeURIComponent(me)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return q(ge.body)}catch{return""}},x=1,S=8,E=16;for(let v=0;v<m.length;v+=I){let me=m.slice(v,v+I),ge=await Promise.all(me.map(async j=>{let Pe=j.item.path,we=(j.changeType&x)!==0,qe=(j.changeType&S)!==0,Qt=(j.changeType&E)!==0&&j.item.originalPath?j.item.originalPath:Pe,Bt=Pe,[Br,Mr]=await Promise.all([we?Promise.resolve(""):$(Qt,l),qe?Promise.resolve(""):$(Bt,p)]);return(0,Yt.createTwoFilesPatch)(`a${Qt}`,`b${Bt}`,Br,Mr)}));y.push(...ge)}return y.join(`
2
- `)}getPullRequestWriteHeaders(e){return{...P(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,r,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(r)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,r,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${t}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:r,commentType:1}],status:1})})}async getCommentsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=P(this.config,t),i=await this.config.request({url:`${r}/pullRequests/${e.pullRequestNumber}/threads?api-version=7.1`,headers:o}),a=[];for(let u of i.body.value)if(!(u.isDeleted||u.threadContext))for(let l of u.comments)l.commentType==="system"||l.isDeleted||a.push({id:ut(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?te(l.author):null,body:l.content||"",createdAt:l.publishedDate?new Date(l.publishedDate):null,url:""});return{data:a,pageInfo:{hasNextPage:!1,endCursor:null}}}async addCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(r,e.pullRequest.id,e.comment,t)}async addInlineCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t),o=this.getPullRequestWriteHeaders(t);if(e.threadId){let p=lt(e.threadId),c=e.pullRequest.repository.owner.login,d=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(p.namespace!==c||p.project!==d||p.repoName!==g||p.prId!==m)throw new Error(`Azure thread ID context mismatch: threadId targets ${p.namespace}/${p.project}/${p.repoName} pull request ${p.prId}, but input.pullRequest targets ${c}/${d}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${r}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}?api-version=7.1`,headers:P(this.config,t)})).body.comments?.find(q=>q.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${p.threadId}.`);let h=await this.config.request({method:"POST",url:`${r}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}/comments?api-version=7.1`,headers:o,body:JSON.stringify({content:e.comment,parentCommentId:y.id,commentType:1})});return ut(c,d,g,Number(m),Number(p.threadId),h.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let l=await this.config.request({method:"POST",url:`${r}/pullRequests/${e.pullRequest.id}/threads?api-version=7.1`,headers:o,body:JSON.stringify({comments:[{parentCommentId:0,content:e.comment,commentType:1}],status:1,threadContext:u})});return Xt(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,t={}){let r=Kt(e.commentId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}/comments/${r.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({content:e.body})})}async editInlineComment(e,t={}){return this.editComment(e,t)}async deleteComment(e,t={}){let r=Kt(e.commentId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}/comments/${r.commentId}?api-version=7.1`,headers:P(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let r=lt(e.threadId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let r=lt(e.threadId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:1})})}async approvePullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(r,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(r,t);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,t),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,t):null])}async requestPullRequestChanges(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(r,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(r,t);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,t),await this.setReviewerVote(o,e.pullRequest.id,i,-5,t)}async commentOnPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(r,e.pullRequest.id,e.comment,t)}async getReviewsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:r,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(r,o,i,t),l=P(this.config,t),[p,c]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:l}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:l})]),d=(h,q)=>ut(r,o,i,a,h,q),g=h=>Xt(r,o,i,a,h),m=new Map;for(let h of c.body.value){if(h.isDeleted)continue;let q=h.comments.filter(O=>!O.isDeleted&&O.commentType!=="system"),$=q.find(O=>O.parentCommentId===0)??q[0];if(!$)continue;let x=$.author?.id;if(!x)continue;let S=q.filter(O=>O.id!==$.id),E=h.threadContext,v=E?.rightFileStart?{side:"RIGHT",start:E.rightFileStart,end:E.rightFileEnd}:E?.leftFileStart?{side:"LEFT",start:E.leftFileStart,end:E.leftFileEnd}:null,me=v?.end?.line??v?.start.line??null,ge=v?.start&&v.end&&v.start.line!==v.end.line?v.start.line:null,j=E?.filePath??"",Pe=j.startsWith("/")?j.slice(1):j,we={id:d(h.id,$.id),author:$.author?te($.author):null,body:$.content??"",createdAt:$.publishedDate?new Date($.publishedDate):null,url:"",diffLines:[],filename:Pe,replies:S.map(O=>({id:d(h.id,O.id),author:O.author?te(O.author):null,body:O.content??"",createdAt:O.publishedDate?new Date(O.publishedDate):null,url:""})),isOutdated:!1,isResolved:ns.has(ss(h.status)),line:me,startLine:ge,side:v?.side??null,threadId:g(h.id)},qe=m.get(x);qe?qe.push(we):m.set(x,[we])}let I=[],y=new Set;for(let h of p.body.value){if(h.hasDeclined)continue;let q=h.vote??0,$=m.get(h.id);q===0&&!$?.length||(I.push({id:h.id,author:te(h),body:"",createdAt:null,url:"",reviewComments:$??[]}),y.add(h.id))}for(let[h,q]of m){if(y.has(h)||!q.length)continue;let $=q[0].author;$&&I.push({id:h,author:$,body:"",createdAt:null,url:"",reviewComments:q})}return{data:I}}};var D=(s,n={})=>f(n.token||s.token,n.isPAT||s.isPAT);var A="https://api.bitbucket.org/2.0",us={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},Ce={owner:4,admin:3,contributor:2,member:1},$e=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),er=s=>{let n=s.links.clone,e=n?.find(r=>r.name==="ssh"),t=n?.find(r=>r.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},pt=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(n=>n.name==="https")?.href??null,sshUrl:s.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),dt=s=>{let n=s.id,e=s.participants?.map(t=>{let r="REVIEW_REQUESTED";return t.approved?r="APPROVED":t.state==="changes_requested"?r="CHANGES_REQUESTED":t.participated_on!==null&&(r="COMMENTED"),{reviewer:$e(t.user),state:r}})??[];return{id:n.toString(),title:s.title,description:s.description,number:n,state:us[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:$e(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo:er(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:Q(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:er(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},ls=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},ps=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"contributor":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};default:return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},oe=class extends N{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:`${A}/user`,headers:D(this.config,e)});return{data:$e(t.body)}}async getUserForCommit(n,e={}){let r=(await this.config.request({url:`${A}/repositories/${n.repo.namespace}/${n.repo.name}/commit/${n.oid}`,headers:D(this.config,e)})).body.author,o=r.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:r.user?.links.avatar.href||null}}}async getRepo(n,e={}){let t=await this.config.request({url:`${A}/repositories/${n.namespace}/${n.name}`,headers:D(this.config,e)});return{data:pt(t.body)}}async getRepos(n,e={}){let t=[],r=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){r.push({input:o,error:i})}})),{data:t,errors:r}}async getReposForWorkspace(n,e={}){let t=new URL(`${A}/repositories/${encodeURIComponent(n.workspace)}`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",L.toString()),n.minimumRole&&t.searchParams.set("role",n.minimumRole);let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(pt)}}async getAllReposForWorkspace(n,e={}){let t=[],r=1;for(;r!==null;){let o=await this.getReposForWorkspace({workspace:n.workspace,minimumRole:n.minimumRole,page:r},e);t.push(...o.data),r=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(n,e={}){let t=new Map,r=[],o=Ce[n.minimumRole||"member"];o<=Ce.admin&&r.push("admin"),o<=Ce.contributor&&r.push("contributor"),o<=Ce.member&&r.push("member");let i=[];for(let a of r){i=await this.getAllReposForWorkspace({workspace:n.workspace,minimumRole:a},e);for(let u of i)t.has(u.id)||t.set(u.id,a)}return{data:i.map(a=>{let u=t.get(a.id)||"member";return{...a,permissions:ps(u)}})}}async getReposForCurrentUser(n,e={}){let t=new URL(`${A}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",L.toString()),n.cursor&&t.searchParams.set("after",n.cursor);let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next,i=null;return r.body.next&&(i=new URL(r.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:r.body.values.map(pt)}}async getBranches(n,e={}){let t=new URL(`${A}/repositories/${n.repo.namespace}/${n.repo.name}/refs/branches`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",L.toString());let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(n,e={}){let t=new URL(`${A}/repositories/${n.repo.namespace}/${n.repo.name}/refs/tags`);t.searchParams.set("pagelen",L.toString()),n.cursor&&t.searchParams.set("page",n.cursor);let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next,i=null;return r.body.next&&(i=new URL(r.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:r.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(n={},e={}){let t=new URL(`${A}/user/workspaces`);t.searchParams.set("page",n?.page?.toString()||"1"),t.searchParams.set("pagelen","50"),n?.administrator!==void 0&&t.searchParams.set("administrator",n.administrator.toString());let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(n,e={}){let t=new URL(`${A}/user/permissions/workspaces`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50");let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(n,e={}){let t=new URL(`${A}/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",n.page?.toString()||"1"),t.searchParams.set("pagelen","50"),n.repos&&n.repos.length>0){let i=`state = "open" AND (${n.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(dt)}}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${A}/repositories/${encodeURI(n.repo.namespace)}/${encodeURI(n.repo.name)}/pullrequests?state=OPEN`),r=[];n.reviewerId&&r.push(`reviewers.uuid="${n.reviewerId}"`),n.authorLogin&&r.push(`author.uuid="${n.authorLogin}"`);let o='state="OPEN"';return r.length&&(o+=` AND (${r.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",n.page?.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=[],r=await this.getPullRequestsForRepoBase(n,e);r.body.values.forEach(i=>{t.push(dt(i))});let o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async r=>{try{(await this.getPullRequestsForRepoBase({repo:r,...n},e)).body.values.forEach(i=>{t.push(dt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(n,e={}){let t=new URL(`${A}/workspaces/${encodeURI(n.workspace)}/members`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>$e(i.user))}}async getReposPermissionsForCurrentUser(n,e={}){let t=new URL(`${A}/user/permissions/repositories`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:ls(a.permission)}),{})}}async decorateReposWithPermissions(n,e={}){let t={},r=1;do{let o=await this.getReposPermissionsForCurrentUser({page:r},e);t={...o.data,...t},r=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(r!==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:`${A}/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:r}=n,o;switch(r){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${A}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),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:r}=n,o={reviewers:r.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${A}/repositories/${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 tr=s=>s?s.find(n=>n.permission==="USER_ADMIN"||n.permission==="PROJECT_ADMIN"||n.permission==="ADMIN"||n.permission==="SYS_ADMIN"||n.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(n=>n.permission==="REPO_WRITE"||n.permission==="REPO_CREATE"||n.permission==="PROJECT_CREATE"||n.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var fe=s=>{let n=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(n&&`${n}/avatar.png`),id:s.id.toString(),username:s.name,url:n}},Le=s=>{let n={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=s.reviewers.map(u=>({reviewer:fe(u.user),state:e[u.status]})),r=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:s.id.toString(),number:s.id,title:s.title,description:s.description,url:s.links.self[0].href,state:n[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:fe(s.author.user),assignees:null,reviews:t,reviewDecision:Q(t),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&r?{cloneUrlHTTPS:o,cloneUrlSSH:r}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},rr=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(n=>n.name==="https"||n.name==="http")?.href??null,sshUrl:s.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),ie=class extends _{getBaseUrl(n){let e=n.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(n){return f(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":r,"x-ausername":o}}=t,i=r?parseInt(r,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:c,name:d,slug:g})=>i?i===c:a===d||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:fe(l)}}async getUserForCommit(n,e){let{repo:t,oid:r}=n,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${r}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:fe(o.body.author)}}async getRepo(n,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${n.namespace}/repos/${n.name}`,headers:this.getRequestHeaders(e)});return{data:rr(t.body)}}async getRepos(n,e={}){let t=[],r=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){r.push({input:o,error:i})}})),{data:t,errors:r}}async getReposForCurrentUser(n,e={}){let t=n.page??0,r=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!r.body.isLastPage,nextPage:r.body.nextPageStart},data:r.body.values.map(rr)}}async getRepoPermissionsForUsername(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${n.repo.namespace}/repos/${n.repo.name}/permissions/search?filterText=${n.username}`);try{let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:tr(r.body.values)}}catch(r){if(r.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw r}}async decorateReposWithPermissions(n,e={}){return await Promise.all(n.repos.map(async r=>{let o=await this.getRepoPermissionsForUsername({repo:r,username:n.username},e);return{...r,permissions:o.data}}))}async getPullRequestsForRepoBase(n,e={}){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",n.page?.toString()||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(n,e={}){let t=[],r=await this.getPullRequestsForRepoBase(n,e);r.body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(Le(i))});let o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async r=>{try{(await this.getPullRequestsForRepoBase({repo:r,...n},e)).body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(Le(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50");let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:r.body.values.map(Le)}}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:r}=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:r,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:r}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:r.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.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")}async getAccountsForProject(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.project)}/permissions/users`);t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50");let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:r.body.values.map(i=>fe(i.user))}}};var Rr=require("js-base64");var De=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(De||{});var R=class extends Error{constructor(e,t){let r=t?.map(i=>`'${i.message}'`).join(", "),o=r?`${e}: ${r}`:e;super(o);this.graphQLErrors=t??[]}};var ds={AS_CODE_OWNER:[3,0,0],CHECK_RUN:[3,0,0],LATEST_REVIEWS:[3,0,0],VIEWER_CAN_MERGE_AS_ADMIN:[3,5,0],ISSUE_FULL_DATABASE_ID:[3,12,0],PR_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_FULL_DATABASE_ID:[3,13,0],PR_REVIEW_COMMENT_FULL_DATABASE_ID:[3,13,0]},sr=15,nr=100,Re={__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"},G=s=>!!s,B=(s,n)=>{let e=ds[n];for(let t=0;t<3;t++){if(s[t]>e[t])return!0;if(s[t]<e[t])return!1}return!0},Ae="https://api.github.com",cs=`${Ae}/graphql`,Ge=`
1
+ "use strict";var rt=Object.defineProperty;var Wr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Vr=Object.prototype.hasOwnProperty;var Kr=(s,n)=>{for(var e in n)rt(s,e,{get:n[e],enumerable:!0})},Xr=(s,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Jr(n))!Vr.call(s,r)&&r!==e&&rt(s,r,{get:()=>n[r],enumerable:!(t=Wr(n,r))||t.enumerable});return s};var Zr=s=>Xr(rt({},"__esModule",{value:!0}),s);var Gn={};Kr(Gn,{AzureDevOps:()=>ae,Bitbucket:()=>ue,BitbucketServer:()=>le,EntityIdentifierProviderType:()=>jr,EntityType:()=>Fr,EntityVersion:()=>Nr,GitBuildStatusStage:()=>Mt,GitBuildStatusState:()=>ve,GitDiffLineType:()=>st,GitHub:()=>pe,GitHubIssueCloseReason:()=>Qr,GitIssueState:()=>De,GitLab:()=>ce,GitMergeStrategy:()=>ie,GitPullRequestMergeableState:()=>te,GitPullRequestReviewState:()=>V,GitPullRequestState:()=>ee,GraphQLErrors:()=>R,Jira:()=>me,JiraServer:()=>ge,PullRequestAsyncStatus:()=>kr,Trello:()=>he,default:()=>An,isFetch:()=>Se});module.exports=Zr(Gn);var Yt=require("diff");var Mt=(r=>(r.Build="build",r.Production="production",r.Staging="staging",r.Test="test",r))(Mt||{}),ve=(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))(ve||{}),ie=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ie||{}),ee=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(ee||{}),V=(r=>(r.Approved="APPROVED",r.ChangesRequested="CHANGES_REQUESTED",r.Commented="COMMENTED",r.ReviewRequested="REVIEW_REQUESTED",r))(V||{}),te=(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))(te||{}),st=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(st||{});var zt={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},j=s=>!s||s.length===0?null:s.reduce((n,e)=>zt[e.state]>zt[n]?e.state:n,"APPROVED");var nt=(a=>(a[a.Unknown=0]="Unknown",a[a.Active=1]="Active",a[a.Fixed=2]="Fixed",a[a.WontFix=3]="WontFix",a[a.Closed=4]="Closed",a[a.ByDesign=5]="ByDesign",a[a.Pending=6]="Pending",a))(nt||{});var L=100;var Ht=globalThis.fetch;var Yr=async s=>{let n=s.headers.get("content-type")||"",e=null;if(n.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(n.startsWith("text/")||n==="")e=await s.text();else if(n.startsWith("application/vnd.github.raw+json")||n.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${n}`);let t={};s.headers.forEach((o,i)=>{t[i]=o});let r={body:e,headers:t,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:r}),o}return r},ot=s=>async({url:n,...e})=>{let t=await s(n,e);return Yr(t)};var Se=(s,n=!1)=>s.name==="fetch"||n;var N=class{constructor(n){let e=n?.request||Ht;this.config={...n,request:Se(e,n?.forceIsFetch)?ot(e):e}}updateConfig(n){this.config={...this.config,...n,request:n.request&&Se(n.request,n?.forceIsFetch??this.config.forceIsFetch)?ot(n.request):this.config.request}}},_=class extends N{};var f=(s,n)=>{let e={};return s&&(e.Authorization=`${n?"Basic":"Bearer"} ${s}`),e},Wt=s=>s?s.reduce((n,e)=>(n[e]=!0,n),{}):void 0,K=(s,n,e)=>!s||n.some(t=>s[t])?e:"",Jt=async s=>{let n=[],e=!0,t;for(;e;){let r=await s(t);n=n.concat(r.data),e=!!r?.pageInfo?.hasNextPage,t=r?.pageInfo?.endCursor||r?.pageInfo?.nextPage}return n};async function it(s){return(await Promise.allSettled(s)).map(e=>es(e)).filter(e=>e!=null)}function es(s,n=void 0){return s?.status==="fulfilled"?s.value:n}var ts="https://app.vssps.visualstudio.com/_apis",rs="https://vssps.dev.azure.com/",ss="https://dev.azure.com",w=(s,n={})=>f(n.token||s.token,n.isPAT||s.isPAT),Vt=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),at=(s,n)=>{let e=n.baseUrl||s.baseUrl||ts;return e=e.replace(/\/$/,""),e},C=(s,n)=>{let e=n.baseUrl||s.baseUrl||ss;return e=e.replace(/\/$/,""),e},ut=(s,n)=>{let e=n.baseUrl||s.baseUrl||rs;return e=e.replace(/\/$/,""),e};var ns={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},os=s=>{if(typeof s!="string")return s;let n=s.charAt(0).toUpperCase()+s.slice(1);return nt[n]??0},is=new Set([2,3,4,5]),as={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},re=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Ee=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,us=s=>{switch(s){case"conflicts":return"CONFLICTS";case"failure":return"FAILING_CHECKS";case"rejectedByPolicy":return"BLOCKED";case"succeeded":return"MERGEABLE";case"notSet":case"queued":default:return"UNKNOWN"}},lt=(s,n,e,t,r,o)=>`${s}|${n}|${e}|${t}|${r}|${o}`,Kt=s=>{let n=s.split("|");if(n.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4],commentId:n[5]}},Xt=(s,n,e,t,r)=>`${s}|${n}|${e}|${t}|${r}`,pt=s=>{let n=s.split("|");if(n.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:n[0],project:n[1],repoName:n[2],prId:n[3],threadId:n[4]}},Re=(s,n)=>{let e=[],t=[];return n.reviewers.forEach(r=>{let o={reviewer:re(r),state:as[r.vote??0]||"REVIEW_REQUESTED"};r.isRequired&&e.push(o),t.push(o)}),{id:n.pullRequestId.toString(),title:n.title,description:n.description??null,number:n.codeReviewId,state:ns[n.status],isDraft:n.isDraft,commentCount:null,upvoteCount:null,author:re(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:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Ee(n.targetRefName),oid:n.lastMergeTargetCommit.commitId},headRef:{name:Ee(n.sourceRefName),oid:n.lastMergeSourceCommit.commitId},url:Vt(n),assignees:n.reviewers.map(re),reviews:t,reviewDecision:j(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:s},remoteInfo:null}:{id:n.repository.id,name:n.repository.name,project:n.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:us(n.mergeStatus),labels:n.labels?.map(r=>({color:null,description:null,id:r.id,name:r.name}))??[],permissions:null}},Zt=(s,n)=>({id:n.id,name:n.name,namespace:s,project:n.project.name,projectId:n.project.id,webUrl:n.webUrl,httpsUrl:n.remoteUrl,sshUrl:n.sshUrl,defaultBranch:n.defaultBranch?{name:Ee(n.defaultBranch)}:null,permissions:null}),ls=(s,n,e,t)=>{let r=e.fields,o=r["System.AssignedTo"],i=r["System.State"],a=r["System.WorkItemType"],u;return i&&a&&(u=t[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:r["System.Title"],commentCount:r["System.CommentCount"],author:{avatarUrl:r["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:r["System.CreatedBy"].id,name:r["System.CreatedBy"].uniqueName??null,username:r["System.CreatedBy"].displayName??null,url:null},closedDate:r["Microsoft.VSTS.Common.ClosedDate"]?new Date(r["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(r["System.CreatedDate"]),updatedDate:new Date(r["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:r["System.Description"]??null,state:{name:u?.title||i,color:null},type:r["System.WorkItemType"],repository:null,project:{namespace:s,name:n,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},ae=class extends _{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let r=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.baseUrl??null]),o=this.cachedUserIds.get(r);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(r);if(i)return i;let a=this.fetchCurrentUserId(e,t,r);return this.inflightUserIds.set(r,a),a}async fetchCurrentUserId(e,t,r){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(r,o.data.id),o.data.id}finally{this.inflightUserIds.delete(r)}}getRepoApiUrl(e,t,r,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(r)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let r=`${at(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:r,headers:w(this.config,t)});return{data:{id:o.body.id,name:o.body.displayName,username:o.body.displayName,email:o.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(e,t={}){let o=(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:w(this.config,t)})).body.authorizedUser;if(o.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:o.id,name:o.providerDisplayName,username:o.providerDisplayName,email:o.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:w(this.config,t)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,t={}){let r=`${at(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:r,headers:w(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let r=`${C(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:r,headers:w(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let r=new URL(`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/projects`);r.searchParams.set("$top",L.toString()),e.cursor&&r.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:r.toString(),headers:w(this.config,t)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({id:a.id,name:a.name,namespace:e.namespace}))}}async getAzureProjectScopeDescriptor(e,t={}){let{namespace:r,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${ut(this.config,t)}/${encodeURIComponent(r)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:w(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:r,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${ut(this.config,t)}/${encodeURIComponent(r)}/_apis/graph/users`);o&&a.searchParams.set("scopeDescriptor",o),i&&a.searchParams.set("continuationToken",i);let u=await this.config.request({url:a.toString(),headers:w(this.config,t)}),l=u.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:l||null,hasNextPage:!!l},data:u.body.value.map(p=>({avatarUrl:p._links?.avatar?.href??null,descriptor:p.descriptor??null,email:p.mailAddress??null,name:p.displayName??null,storageKeyURL:p._links?.storageKey?.href??null,username:p.displayName??null}))}}async getAccountFromAzureGraphAccount(e,t={}){let{azureGraphAccount:r}=e;if(!r.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:r.storageKeyURL,headers:w(this.config,t)});return{data:{avatarUrl:r.avatarUrl,email:r.email,id:o.body.value,name:r.name,username:r.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let r=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);r.push(i.data)}return{data:r}}async getRepo(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:w(this.config,t)});return{data:Zt(e.namespace,r.body)}}async getRepos(e,t={}){let r=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);r.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:r,errors:o}}async getReposForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:w(this.config,t)})).body.value.map(o=>Zt(e.namespace,o))}}async getRefs(e,t,r={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${C(this.config,r)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",L.toString()),t.cursor&&o.searchParams.set("continuationToken",t.cursor);let i=await this.config.request({url:o.toString(),headers:w(this.config,r)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Ee(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,t={}){return this.getRefs("heads",e,t)}async getTags(e,t={}){return this.getRefs("tags",e,t)}async getPullRequestsForRepoBase(e,t={},r=100){let{page:o,repo:i,assigneeLogins:a,authorLogin:u}=e||{},l=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let p="searchCriteria.status=1";return a&&a.length&&(p+=`&searchCriteria.reviewerId=${a[0]}`),u&&(p+=`&searchCriteria.creatorId=${u}`),await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${p}&%24top=${r}&%24skip=${(l-1)*r}`,headers:w(this.config,t)})}async getPullRequestsForRepo(e,t={}){let o=e.page||1,i=await this.getPullRequestsForRepoBase(e,t,100);return{pageInfo:{hasNextPage:i.body.value.length===100,nextPage:o+1},data:i.body.value.map(a=>Re(e.repo.namespace,a))}}async getPullRequestsForRepos(e,t={}){if(!e.repos.every(i=>i.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:r}=e||{},o=[];return await Promise.all(r.map(async i=>{try{(await this.getPullRequestsForRepoBase({repo:i,...e},t)).body.value.forEach(u=>{o.push(Re(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getPullRequestsForProjectBase(e,t={},r=100){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,repo:p}=e;if(p?.project&&p.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,d=new URL(`${C(this.config,t)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",r.toString()),d.searchParams.set("$skip",((c-1)*r).toString()),p?.id&&p?.project===i&&d.searchParams.set("searchCriteria.repositoryId",p.id),u&&u.length&&d.searchParams.set("searchCriteria.reviewerId",u[0]),l&&d.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:d.toString(),headers:w(this.config,t)})}async getPullRequestsForProject(e,t={}){let o=e.page||1,i=await this.getPullRequestsForProjectBase(e,t,100);return{pageInfo:{hasNextPage:i?.body.value.length===100,nextPage:o+1},data:i?.body.value.map(a=>Re(e.namespace,a))||[]}}async getPullRequestsForProjects(e,t={}){let{projects:r}=e||{},o=[];return await Promise.all(r.map(async i=>{try{(!e.repo||e.repo.project&&e.repo.project===i.project)&&(await this.getPullRequestsForProjectBase({...i,...e},t))?.body.value.forEach(u=>{o.push(Re(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getAzurePullRequestLastMergeStatus(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:r,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...w(this.config,t)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,t,r){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${encodeURIComponent(e.repository.owner.login)}/${encodeURIComponent(e.repository.project)}/_apis/git/repositories/${e.repository.name}/pullrequests/${e.id}?api-version=6.0`,body:t,headers:{...w(this.config,r),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:r}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(r,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){let{pullRequest:r,mergeStrategy:o}=e,i;switch(o){case"MERGE_COMMIT":{i="noFastForward";break}case"REBASE":{i="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{i="rebaseMerge";break}case"SQUASH":{i="squash";break}}let a={completionOptions:{mergeStrategy:i},lastMergeSourceCommit:{commitId:r.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(r,JSON.stringify(a),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){let{pullRequest:r,label:o}=e;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i={name:o.name};if(!(await this.config.request({method:"POST",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...w(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,t={}){let{pullRequest:r,label:o}=e;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...w(this.config,t)}})}async setPullRequestLabels(e,t={}){let{pullRequest:r,labels:o}=e;if(!r.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=r.labels;if(!i)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of o)i.find(u=>u.id===a.id)||await this.addPullRequestLabel({pullRequest:r,label:a},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:r,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:r,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(r,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){let{pullRequest:r,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...w(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,t={}){let{pullRequest:r,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${encodeURIComponent(r.repository.owner.login)}/${encodeURIComponent(r.repository.project)}/_apis/git/repositories/${r.repository.name}/pullrequests/${r.id}/reviewers/${o.id}?api-version=6.0`,headers:{...w(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){let{pullRequest:r,reviewers:o}=e;for(let i of o)r.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:r,reviewer:i,isRequired:!0},t);for(let i of r.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:r,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:r,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=r||1,c=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];i&&d.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&d.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&d.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(h=>d.push(`[System.Tags] Contains '${h}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...w(this.config,t),"Content-Type":"application/json"}}),I=m.body.workItems.slice((p-1)*c,c*p).map(h=>h.id);if(I.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let y=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:I,$expand:"Links"}),method:"POST",headers:{...w(this.config,t),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:m.body.workItems.length>c*p,nextPage:p+1},data:y.body.value.map(h=>ls(e.namespace,e.project,h,l||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:r,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=c=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${c.projectId}/${c.id}`;return Object.keys(i).map(m=>({securityNamespaceId:d,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,t)}/${encodeURIComponent(r)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...w(this.config,t),"Content-Type":"application/json"}})).body.evaluations.reduce((c,d)=>{let[,g,m]=d.token.split("/"),I=`${g}/${m}`,y=i[d.permissions];for(let h of y)c[I]===void 0&&(c[I]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(c[I][h]=!1);return c},{})}}async decorateReposWithPermissions(e,t={}){let{namespace:r,repos:o}=e,i=await this.getPermissionsForRepos({namespace:r,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,r={}){return await this.config.request({method:"PATCH",url:`${C(this.config,r)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(t),headers:{...w(this.config,r),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:r,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(r,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:r,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(r,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){let{issue:r,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(r,a,t)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:r,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...w(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:r,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(r)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...w(this.config,t)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,t={}){let{repo:r,number:o}=e;if(!r.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(r.namespace,r.project,r.name,t)}/pullrequests/${o}?api-version=7.1`,headers:w(this.config,t)});return{data:Re(r.namespace,i.body)}}async getMergeBase(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:w(this.config,t)});if(!r.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:r.body.value[0].commitId}}async getFileContents(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...w(this.config,t),Accept:"application/octet-stream"}});return{data:new Blob([r.body])}}async getPullRequestDiff(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=w(this.config,t),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${r}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${r}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,p=a.body.lastMergeSourceCommit.commitId,c=u.body.value;if(c.length===0)return"";let d=c[c.length-1],g=1e3,m=[],I=0;for(;;){let S=(await this.config.request({url:`${r}/pullrequests/${e.pullRequestId}/iterations/${d.id}/changes?api-version=7.1&$top=${g}&$skip=${I}`,headers:o})).body.changeEntries??[];if(S.length===0||(m.push(...S),S.length<g))break;I+=S.length}if(m.length===0)return"";let y=5,h=[],v=new TextDecoder,$=P=>P instanceof ArrayBuffer?v.decode(P):typeof P=="string"?P:"",x=async(P,S)=>{try{let Z=await this.config.request({url:`${r}/items?path=${encodeURIComponent(P)}&versionDescriptor[version]=${encodeURIComponent(S)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return $(Z.body)}catch{return""}},E=P=>{if(typeof P=="number")return{add:(P&1)!==0,rename:(P&8)!==0,delete:(P&16)!==0};let S=P.toLowerCase().split(",").map(Z=>Z.trim());return{add:S.includes("add"),rename:S.includes("rename"),delete:S.includes("delete")}};for(let P=0;P<m.length;P+=y){let S=m.slice(P,P+y),Z=await Promise.all(S.map(async ne=>{let{add:oe,rename:tt,delete:Y}=E(ne.changeType),fe=ne.originalPath??ne.item.originalPath,A=ne.item.path,qe=Y?A??fe??"":A??"",Bt=tt||Y?fe??qe:qe,[Br,Mr]=await Promise.all([oe?Promise.resolve(""):x(Bt,l),Y?Promise.resolve(""):x(qe,p)]),zr=oe?"/dev/null":`a${Bt}`,Hr=Y?"/dev/null":`b${qe}`;return(0,Yt.createTwoFilesPatch)(zr,Hr,Br,Mr)}));h.push(...Z)}return h.join(`
2
+ `)}getPullRequestWriteHeaders(e){return{...w(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,r,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(r)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,r,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${t}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:r,commentType:1}],status:1})})}async getCommentsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=w(this.config,t),i=await this.config.request({url:`${r}/pullRequests/${e.pullRequestNumber}/threads?api-version=7.1`,headers:o}),a=[];for(let u of i.body.value)if(!(u.isDeleted||u.threadContext))for(let l of u.comments)l.commentType==="system"||l.isDeleted||a.push({id:lt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?re(l.author):null,body:l.content||"",createdAt:l.publishedDate?new Date(l.publishedDate):null,url:""});return{data:a,pageInfo:{hasNextPage:!1,endCursor:null}}}async addCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(r,e.pullRequest.id,e.comment,t)}async addInlineCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t),o=this.getPullRequestWriteHeaders(t);if(e.threadId){let p=pt(e.threadId),c=e.pullRequest.repository.owner.login,d=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(p.namespace!==c||p.project!==d||p.repoName!==g||p.prId!==m)throw new Error(`Azure thread ID context mismatch: threadId targets ${p.namespace}/${p.project}/${p.repoName} pull request ${p.prId}, but input.pullRequest targets ${c}/${d}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${r}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}?api-version=7.1`,headers:w(this.config,t)})).body.comments?.find(v=>v.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${p.threadId}.`);let h=await this.config.request({method:"POST",url:`${r}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}/comments?api-version=7.1`,headers:o,body:JSON.stringify({content:e.comment,parentCommentId:y.id,commentType:1})});return lt(c,d,g,Number(m),Number(p.threadId),h.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let l=await this.config.request({method:"POST",url:`${r}/pullRequests/${e.pullRequest.id}/threads?api-version=7.1`,headers:o,body:JSON.stringify({comments:[{parentCommentId:0,content:e.comment,commentType:1}],status:1,threadContext:u})});return Xt(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,t={}){let r=Kt(e.commentId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}/comments/${r.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({content:e.body})})}async editInlineComment(e,t={}){return this.editComment(e,t)}async deleteComment(e,t={}){let r=Kt(e.commentId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}/comments/${r.commentId}?api-version=7.1`,headers:w(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let r=pt(e.threadId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let r=pt(e.threadId),o=this.getRepoApiUrl(r.namespace,r.project,r.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${r.prId}/threads/${r.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:1})})}async approvePullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(r,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(r,t);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,t),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,t):null])}async requestPullRequestChanges(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(r,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(r,t);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,t),await this.setReviewerVote(o,e.pullRequest.id,i,-5,t)}async commentOnPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let r=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(r,e.pullRequest.id,e.comment,t)}async getReviewsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:r,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(r,o,i,t),l=w(this.config,t),[p,c]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:l}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:l})]),d=(h,v)=>lt(r,o,i,a,h,v),g=h=>Xt(r,o,i,a,h),m=new Map;for(let h of c.body.value){if(h.isDeleted)continue;let v=h.comments.filter(A=>!A.isDeleted&&A.commentType!=="system"),$=v.find(A=>A.parentCommentId===0)??v[0];if(!$)continue;let x=$.author?.id;if(!x)continue;let E=v.filter(A=>A.id!==$.id),P=h.threadContext,S=P?.rightFileStart?{side:"RIGHT",start:P.rightFileStart,end:P.rightFileEnd}:P?.leftFileStart?{side:"LEFT",start:P.leftFileStart,end:P.leftFileEnd}:null,Z=S?.end?.line??S?.start.line??null,ne=S?.start&&S.end&&S.start.line!==S.end.line?S.start.line:null,oe=P?.filePath??"",tt=oe.startsWith("/")?oe.slice(1):oe,Y={id:d(h.id,$.id),author:$.author?re($.author):null,body:$.content??"",createdAt:$.publishedDate?new Date($.publishedDate):null,url:"",diffLines:[],filename:tt,replies:E.map(A=>({id:d(h.id,A.id),author:A.author?re(A.author):null,body:A.content??"",createdAt:A.publishedDate?new Date(A.publishedDate):null,url:""})),isOutdated:!1,isResolved:is.has(os(h.status)),line:Z,startLine:ne,side:S?.side??null,threadId:g(h.id)},fe=m.get(x);fe?fe.push(Y):m.set(x,[Y])}let I=[],y=new Set;for(let h of p.body.value){if(h.hasDeclined)continue;let v=h.vote??0,$=m.get(h.id);v===0&&!$?.length||(I.push({id:h.id,author:re(h),body:"",createdAt:null,url:"",reviewComments:$??[]}),y.add(h.id))}for(let[h,v]of m){if(y.has(h)||!v.length)continue;let $=v[0].author;$&&I.push({id:h,author:$,body:"",createdAt:null,url:"",reviewComments:v})}return{data:I}}};var D=(s,n={})=>f(n.token||s.token,n.isPAT||s.isPAT);var G="https://api.bitbucket.org/2.0",ps={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},Ce={owner:4,admin:3,contributor:2,member:1},$e=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),er=s=>{let n=s.links.clone,e=n?.find(r=>r.name==="ssh"),t=n?.find(r=>r.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},dt=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(n=>n.name==="https")?.href??null,sshUrl:s.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),ct=s=>{let n=s.id,e=s.participants?.map(t=>{let r="REVIEW_REQUESTED";return t.approved?r="APPROVED":t.state==="changes_requested"?r="CHANGES_REQUESTED":t.participated_on!==null&&(r="COMMENTED"),{reviewer:$e(t.user),state:r}})??[];return{id:n.toString(),title:s.title,description:s.description,number:n,state:ps[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:$e(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo:er(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:j(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:er(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},ds=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"write":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};case"read":case"none":return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},cs=s=>{switch(s){case"owner":case"admin":return{canCreateWebhook:!0,canPush:!0,isAdmin:!0};case"contributor":return{canCreateWebhook:!1,canPush:!0,isAdmin:!1};default:return{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}},ue=class extends N{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:`${G}/user`,headers:D(this.config,e)});return{data:$e(t.body)}}async getUserForCommit(n,e={}){let r=(await this.config.request({url:`${G}/repositories/${n.repo.namespace}/${n.repo.name}/commit/${n.oid}`,headers:D(this.config,e)})).body.author,o=r.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:r.user?.links.avatar.href||null}}}async getRepo(n,e={}){let t=await this.config.request({url:`${G}/repositories/${n.namespace}/${n.name}`,headers:D(this.config,e)});return{data:dt(t.body)}}async getRepos(n,e={}){let t=[],r=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){r.push({input:o,error:i})}})),{data:t,errors:r}}async getReposForWorkspace(n,e={}){let t=new URL(`${G}/repositories/${encodeURIComponent(n.workspace)}`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",L.toString()),n.minimumRole&&t.searchParams.set("role",n.minimumRole);let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(dt)}}async getAllReposForWorkspace(n,e={}){let t=[],r=1;for(;r!==null;){let o=await this.getReposForWorkspace({workspace:n.workspace,minimumRole:n.minimumRole,page:r},e);t.push(...o.data),r=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(n,e={}){let t=new Map,r=[],o=Ce[n.minimumRole||"member"];o<=Ce.admin&&r.push("admin"),o<=Ce.contributor&&r.push("contributor"),o<=Ce.member&&r.push("member");let i=[];for(let a of r){i=await this.getAllReposForWorkspace({workspace:n.workspace,minimumRole:a},e);for(let u of i)t.has(u.id)||t.set(u.id,a)}return{data:i.map(a=>{let u=t.get(a.id)||"member";return{...a,permissions:cs(u)}})}}async getReposForCurrentUser(n,e={}){let t=new URL(`${G}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",L.toString()),n.cursor&&t.searchParams.set("after",n.cursor);let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next,i=null;return r.body.next&&(i=new URL(r.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:r.body.values.map(dt)}}async getBranches(n,e={}){let t=new URL(`${G}/repositories/${n.repo.namespace}/${n.repo.name}/refs/branches`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen",L.toString());let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(n,e={}){let t=new URL(`${G}/repositories/${n.repo.namespace}/${n.repo.name}/refs/tags`);t.searchParams.set("pagelen",L.toString()),n.cursor&&t.searchParams.set("page",n.cursor);let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next,i=null;return r.body.next&&(i=new URL(r.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:r.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(n={},e={}){let t=new URL(`${G}/user/workspaces`);t.searchParams.set("page",n?.page?.toString()||"1"),t.searchParams.set("pagelen","50"),n?.administrator!==void 0&&t.searchParams.set("administrator",n.administrator.toString());let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(n,e={}){let t=new URL(`${G}/user/permissions/workspaces`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","50");let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(n,e={}){let t=new URL(`${G}/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",n.page?.toString()||"1"),t.searchParams.set("pagelen","50"),n.repos&&n.repos.length>0){let i=`state = "open" AND (${n.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(ct)}}async getPullRequestsForRepoBase(n,e={}){let t=new URL(`${G}/repositories/${encodeURI(n.repo.namespace)}/${encodeURI(n.repo.name)}/pullrequests?state=OPEN`),r=[];n.reviewerId&&r.push(`reviewers.uuid="${n.reviewerId}"`),n.authorLogin&&r.push(`author.uuid="${n.authorLogin}"`);let o='state="OPEN"';return r.length&&(o+=` AND (${r.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",n.page?.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=[],r=await this.getPullRequestsForRepoBase(n,e);r.body.values.forEach(i=>{t.push(ct(i))});let o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async r=>{try{(await this.getPullRequestsForRepoBase({repo:r,...n},e)).body.values.forEach(i=>{t.push(ct(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(n,e={}){let t=new URL(`${G}/workspaces/${encodeURI(n.workspace)}/members`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.map(i=>$e(i.user))}}async getReposPermissionsForCurrentUser(n,e={}){let t=new URL(`${G}/user/permissions/repositories`);t.searchParams.set("page",n.page?.toString()||"1"),t.searchParams.set("pagelen","100");let r=await this.config.request({url:t.toString(),headers:D(this.config,e)}),o=!!r.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.page+1:null},data:r.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:ds(a.permission)}),{})}}async decorateReposWithPermissions(n,e={}){let t={},r=1;do{let o=await this.getReposPermissionsForCurrentUser({page:r},e);t={...o.data,...t},r=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(r!==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:`${G}/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:r}=n,o;switch(r){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${G}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),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:r}=n,o={reviewers:r.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${G}/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 tr=s=>s?s.find(n=>n.permission==="USER_ADMIN"||n.permission==="PROJECT_ADMIN"||n.permission==="ADMIN"||n.permission==="SYS_ADMIN"||n.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(n=>n.permission==="REPO_WRITE"||n.permission==="REPO_CREATE"||n.permission==="PROJECT_CREATE"||n.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Ie=s=>{let n=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(n&&`${n}/avatar.png`),id:s.id.toString(),username:s.name,url:n}},Le=s=>{let n={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=s.reviewers.map(u=>({reviewer:Ie(u.user),state:e[u.status]})),r=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:s.id.toString(),number:s.id,title:s.title,description:s.description,url:s.links.self[0].href,state:n[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Ie(s.author.user),assignees:null,reviews:t,reviewDecision:j(t),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&r?{cloneUrlHTTPS:o,cloneUrlSSH:r}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},rr=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(n=>n.name==="https"||n.name==="http")?.href??null,sshUrl:s.links.clone.find(n=>n.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),le=class extends _{getBaseUrl(n){let e=n.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(n){return f(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":r,"x-ausername":o}}=t,i=r?parseInt(r,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:c,name:d,slug:g})=>i?i===c:a===d||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Ie(l)}}async getUserForCommit(n,e){let{repo:t,oid:r}=n,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${r}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Ie(o.body.author)}}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:rr(t.body)}}async getRepos(n,e={}){let t=[],r=[];return await Promise.all(n.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){r.push({input:o,error:i})}})),{data:t,errors:r}}async getReposForCurrentUser(n,e={}){let t=n.page??0,r=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!r.body.isLastPage,nextPage:r.body.nextPageStart},data:r.body.values.map(rr)}}async getRepoPermissionsForUsername(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${n.repo.namespace}/repos/${n.repo.name}/permissions/search?filterText=${n.username}`);try{let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:tr(r.body.values)}}catch(r){if(r.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw r}}async decorateReposWithPermissions(n,e={}){return await Promise.all(n.repos.map(async r=>{let o=await this.getRepoPermissionsForUsername({repo:r,username:n.username},e);return{...r,permissions:o.data}}))}async getPullRequestsForRepoBase(n,e={}){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",n.page?.toString()||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(n,e={}){let t=[],r=await this.getPullRequestsForRepoBase(n,e);r.body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(Le(i))});let o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:t}}async getPullRequestsForRepos(n,e={}){let t=[];return await Promise.all(n.repos.map(async r=>{try{(await this.getPullRequestsForRepoBase({repo:r,...n},e)).body.values.forEach(i=>{if(n.authorLogin&&i.author.user.name!==n.authorLogin)return null;t.push(Le(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50");let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:r.body.values.map(Le)}}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:r}=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:r,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:r}=n;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:r.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.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")}async getAccountsForProject(n,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(n.project)}/permissions/users`);t.searchParams.set("start",n.page?.toString()||"0"),t.searchParams.set("limit","50");let r=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)}),o=r.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?r.body.start+r.body.values.length:null},data:r.body.values.map(i=>Ie(i.user))}}};var Rr=require("js-base64");var De=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(De||{});var R=class extends Error{constructor(e,t){let r=t?.map(i=>`'${i.message}'`).join(", "),o=r?`${e}: ${r}`:e;super(o);this.graphQLErrors=t??[]}};var ms={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]},sr=15,nr=100,be={__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"},T=s=>!!s,Q=(s,n)=>{let e=ms[n];for(let t=0;t<3;t++){if(s[t]>e[t])return!0;if(s[t]<e[t])return!1}return!0},Ae="https://api.github.com",gs=`${Ae}/graphql`,Ge=`
3
3
  description
4
4
  dueOn
5
5
  id
@@ -7,7 +7,7 @@ number
7
7
  state
8
8
  title
9
9
  url
10
- `,ms=`
10
+ `,hs=`
11
11
  ... on CheckRun {
12
12
  completedAt
13
13
  conclusion
@@ -21,16 +21,16 @@ color
21
21
  description
22
22
  id
23
23
  name
24
- `,or=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},gs=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),or(e),Ue.test(e)&&(e=e.replace(Ue,"")),`${e}/api/graphql`):cs},re=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),or(e),Ue.test(e)&&(e=e.replace(Ue,"")),`${e}/api/v3`):Ae},b=(s,n,e)=>{let t=f(e.token||s.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",s.request({url:gs(s,e),method:"POST",headers:t,body:JSON.stringify(n)})},hs={user:!0,"user:email":!0,"read:user":!0},H=s=>s.some(n=>hs[n]),k=(s=!1,n=!1,e)=>`
24
+ `,or=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},fs=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),or(e),Ue.test(e)&&(e=e.replace(Ue,"")),`${e}/api/graphql`):gs},se=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),or(e),Ue.test(e)&&(e=e.replace(Ue,"")),`${e}/api/v3`):Ae},b=(s,n,e)=>{let t=f(e.token||s.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",s.request({url:fs(s,e),method:"POST",headers:t,body:JSON.stringify(n)})},Rs={user:!0,"user:email":!0,"read:user":!0},z=s=>s.some(n=>Rs[n]),k=(s=!1,n=!1,e)=>`
25
25
  __typename
26
- ${X(e,["graphQLId"],"id")}
27
- ${X(e,["id"],"databaseId")}
28
- ${X(e,["name"],"name")}
29
- ${X(e,["name","username"],"login")}
30
- ${n?X(e,["email"],"email"):""}
31
- ${X(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
32
- ${X(e,["url"],"url")}
33
- `,fs=(s=!1)=>`
26
+ ${K(e,["graphQLId"],"id")}
27
+ ${K(e,["id"],"databaseId")}
28
+ ${K(e,["name"],"name")}
29
+ ${K(e,["name","username"],"login")}
30
+ ${n?K(e,["email"],"email"):""}
31
+ ${K(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
32
+ ${K(e,["url"],"url")}
33
+ `,Is=(s=!1)=>`
34
34
  latestReviews(first: 100) {
35
35
  nodes {
36
36
  author {
@@ -38,7 +38,7 @@ latestReviews(first: 100) {
38
38
  ${k(!1,s)}
39
39
  }
40
40
  ... on EnterpriseUserAccount {
41
- ${ct(!1)}
41
+ ${mt(!1)}
42
42
  }
43
43
  }
44
44
  state
@@ -51,7 +51,7 @@ databaseId
51
51
  login
52
52
  avatarUrl${s?"(size: $avatarSize)":""}
53
53
  url
54
- `,ct=(s=!1)=>`
54
+ `,mt=(s=!1)=>`
55
55
  __typename
56
56
  id
57
57
  login
@@ -59,7 +59,7 @@ avatarUrl${s?"(size: $avatarSize)":""}
59
59
  url
60
60
  `,Oe=(s,n=!1,e)=>`
61
61
  id
62
- ${!e||B(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
62
+ ${!e||Q(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
63
63
  number
64
64
  title
65
65
  body
@@ -72,7 +72,7 @@ author {
72
72
  ${ir(!1)}
73
73
  }
74
74
  ... on EnterpriseUserAccount {
75
- ${ct(!1)}
75
+ ${mt(!1)}
76
76
  }
77
77
  }
78
78
  commits(last: 1) {
@@ -85,7 +85,7 @@ commits(last: 1) {
85
85
  contexts(first: 100) {
86
86
  totalCount
87
87
  nodes {
88
- ${!e||B(e,"CHECK_RUN")?ms:""}
88
+ ${!e||Q(e,"CHECK_RUN")?hs:""}
89
89
  ... on StatusContext {
90
90
  context
91
91
  createdAt
@@ -152,7 +152,7 @@ assignees(first: 100) {
152
152
  }
153
153
  reviewRequests(first: 100) {
154
154
  nodes {
155
- ${!e||B(e,"AS_CODE_OWNER")?"asCodeOwner":""}
155
+ ${!e||Q(e,"AS_CODE_OWNER")?"asCodeOwner":""}
156
156
  requestedReviewer {
157
157
  ... on User {
158
158
  ${k(!1,n)}
@@ -160,7 +160,7 @@ reviewRequests(first: 100) {
160
160
  }
161
161
  }
162
162
  }
163
- ${!e||B(e,"LATEST_REVIEWS")?fs(n):""}
163
+ ${!e||Q(e,"LATEST_REVIEWS")?Is(n):""}
164
164
  additions
165
165
  deletions
166
166
  changedFiles
@@ -174,10 +174,10 @@ labels(first: 100) {
174
174
  ${Te}
175
175
  }
176
176
  }
177
- ${!e||B(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
178
- `,Rs=(s=!1,n)=>`
177
+ ${!e||Q(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
178
+ `,bs=(s=!1,n)=>`
179
179
  id
180
- ${!n||B(n,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
180
+ ${!n||Q(n,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
181
181
  title
182
182
  author {
183
183
  ... on User {
@@ -187,7 +187,7 @@ author {
187
187
  ${ir(!1)}
188
188
  }
189
189
  ... on EnterpriseUserAccount {
190
- ${ct(!1)}
190
+ ${mt(!1)}
191
191
  }
192
192
  }
193
193
  closedAt
@@ -223,7 +223,7 @@ labels(first: 100) {
223
223
  ${Te}
224
224
  }
225
225
  }
226
- `,Is={"-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"},bs=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),mt=s=>{let n=[];return(s.match(bs)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let r=t.split(":")[0];Is[r]&&n.push(t)}}),n},gt=(s,n,e,t)=>{let r=s==="issue";return{query:`
226
+ `,ys={"-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"},Ps=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),gt=s=>{let n=[];return(s.match(Ps)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let r=t.split(":")[0];ys[r]&&n.push(t)}}),n},ht=(s,n,e,t)=>{let r=s==="issue";return{query:`
227
227
  query SearchIssuesOrPullRequests($query: String! $after: String) {
228
228
  search(type:ISSUE query:$query first: ${t.maxPageSize} after:$after) {
229
229
  pageInfo {
@@ -232,18 +232,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
232
232
  }
233
233
  nodes {
234
234
  ... on ${r?"Issue":"PullRequest"} {
235
- ${r?Rs(t.supportsEmail,t.enterpriseVersion??null):Oe(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
235
+ ${r?bs(t.supportsEmail,t.enterpriseVersion??null):Oe(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
236
236
  }
237
237
  }
238
238
  }
239
- }`,variables:{query:`is:${s} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${n}`,after:e}}},ys="Field 'isDraft' doesn't exist on type 'PullRequest'",xe=(s=[])=>s.some(n=>n?.message===ys),Ps=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,ws=`
239
+ }`,variables:{query:`is:${s} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${n}`,after:e}}},ws="Field 'isDraft' doesn't exist on type 'PullRequest'",xe=(s=[])=>s.some(n=>n?.message===ws),qs=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,vs=`
240
240
  \
241
- +`,ar=(s,n,e,t)=>{let r=Ps.exec(s);if(!r||!r[0]||!r[1])return[];let o=parseInt(r[1],10),i=parseInt(r[2],10),a=s.replace(ws,`
241
+ +`,ar=(s,n,e,t)=>{let r=qs.exec(s);if(!r||!r[0]||!r[1])return[];let o=parseInt(r[1],10),i=parseInt(r[2],10),a=s.replace(vs,`
242
242
  +`).split(`
243
243
  `).slice(1),u=o-1,l=i-1,p=a.map(g=>{let m,I;switch(g[0]){case"-":{m="DELETED",u+=1,I=`${g.slice(1)}
244
244
  `;break}case"+":{m="ADDED",l+=1,I=`${g.slice(1)}
245
245
  `;break}default:m="UNMODIFIED",l+=1,u+=1,I=`${g}
246
- `}return{line:I,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),c=e,d=n;if(c!==null&&d!==null&&t!==null&&c<d){let g=0,m=p.length,I=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<p.length;y++){let q=p[y][I];q===c?g=y:q===d&&(m=y)}p=p.slice(g,m+1)}return p},ur=s=>{let n=s.author;return n||(n=Re),{author:{id:"databaseId"in n?n.databaseId.toString():n.id,graphQLId:n.id,name:("name"in n?n.name:n.login)??n.login,username:n.login,email:("email"in n?n.email:null)??null,avatarUrl:n.avatarUrl,url:n.url},body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId?.toString()??s.id,url:s.url}};var lr=`mutation DeleteIssueComment(
246
+ `}return{line:I,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),c=e,d=n;if(c!==null&&d!==null&&t!==null&&c<d){let g=0,m=p.length,I=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<p.length;y++){let v=p[y][I];v===c?g=y:v===d&&(m=y)}p=p.slice(g,m+1)}return p},ur=s=>{let n=s.author;return n||(n=be),{author:{id:"databaseId"in n?n.databaseId.toString():n.id,graphQLId:n.id,name:("name"in n?n.name:n.login)??n.login,username:n.login,email:("email"in n?n.email:null)??null,avatarUrl:n.avatarUrl,url:n.url},body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId?.toString()??s.id,url:s.url}};var lr=`mutation DeleteIssueComment(
247
247
  $issueCommentId: ID!
248
248
  ) {
249
249
  deleteIssueComment(input: {
@@ -355,7 +355,7 @@ query GetPullRequestComments(
355
355
  }
356
356
  }
357
357
  }
358
- `;var ht=`
358
+ `;var ft=`
359
359
  id
360
360
  databaseId
361
361
  owner {
@@ -368,10 +368,10 @@ defaultBranchRef {
368
368
  name
369
369
  }
370
370
  viewerPermission
371
- `,qs={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},vs={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Ss={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Es={OPEN:"OPEN",CLOSED:"CLOSED"},Cs=["ADMIN","MAINTAIN","TRIAGE","WRITE"],It=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),$s=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),ft=s=>({id:s.databaseId.toString(),graphQLId:s.id,namespace:s.owner.login,name:s.name,webUrl:s.url,httpsUrl:s.url.endsWith(".git")?s.url:`${s.url}.git`,sshUrl:s.sshUrl,defaultBranch:s.defaultBranchRef,permissions:$s(s.viewerPermission)}),Ls=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),fr=s=>({id:s.id.toString(),graphQLId:s.node_id,namespace:s.owner.login,name:s.name,webUrl:s.html_url,httpsUrl:s.clone_url,sshUrl:s.ssh_url,defaultBranch:{name:s.default_branch},permissions:Ls(s.permissions)}),Ds=s=>({path:s.path,isDirectory:s.type==="tree"}),Us={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},As={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},F=(s,n=As)=>{let e={};return n.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),n.graphQLId&&(e.graphQLId=s.id),n.name&&(e.name=s.name??s.login),n.username&&(e.username=s.login),n.email&&(e.email=s.email??null),n.avatarUrl&&(e.avatarUrl=s.avatarUrl),n.url&&(e.url=s.url),e},Gs=(s,n)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return s!=="COMPLETED"?e[s]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[n]},Ts=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],Rt=s=>{let n=null;s.author?n=s.author:n=Re;let e=(s.reviewRequests?.nodes||[]).filter(G).filter(i=>!i.asCodeOwner),t=s.headRepository?.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let r=s.repository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:F(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(G).map(i=>{let a=Re;return i.author&&i.author.__typename&&(a=i.author),{reviewer:F(a),state:qs[i.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,description:s.body,number:s.number,state:Us[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:n&&n.__typename?F(n):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.repository.sshUrl}},headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(G)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(G).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Ts(i.state),startedAt:new Date(i.createdAt),stage:null,url:i.targetUrl}:{completedAt:i.completedAt?new Date(i.completedAt):null,description:null,name:i.name,state:Gs(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:s.headRef?{name:s.headRef.name,oid:s.headRef.target?.oid??null}:null,baseRef:s.baseRef?{name:s.baseRef.name,oid:s.baseRef.target?.oid??null}:null,url:s.url,updatedDate:new Date(s.updatedAt),closedDate:s.closedAt?new Date(s.closedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees.nodes?s.assignees.nodes.filter(G).map(i=>F(i)):null,reviews:o,reviewDecision:Q(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:Ss[s.mergeStateStatus]??vs[s.mergeable],milestone:s.milestone?bt(s.milestone):null,labels:s.labels?.nodes?.filter(G).map(It)??[],permissions:{canMerge:Cs.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Os=s=>{let{id:n,comments:e,isOutdated:t,isResolved:r,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:p}=s,c=e.nodes?.[0];if(!c)return null;let{author:d,body:g,databaseId:m,fullDatabaseId:I,id:y,path:h,publishedAt:q,url:$}=c,x=o??u,S=i??l,E=a??p;return{author:d?{avatarUrl:d.avatarUrl,email:null,name:d.login}:null,body:g,createdAt:q?new Date(q):null,diffLines:ar(c.diffHunk,x,S,E),id:I??m.toString(),isOutdated:t,isResolved:r,graphQLId:y,threadId:n,filename:h,replies:e.nodes?.filter(G).slice(1).map(xs)??[],url:$,line:x,startLine:S,side:E}},xs=s=>({author:s.author?{avatarUrl:s.author.avatarUrl,email:null,name:s.author.login}:null,body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId.toString(),url:s.url}),_s=s=>{let n=null;return s.author?n=s.author:n=Re,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:n&&n.__typename?F(n):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:Es[s.state],color:null},type:null,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login}},url:s.url,updatedDate:new Date(s.updatedAt),assignees:s.assignees.nodes?.filter(G).map(e=>F(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?bt(s.milestone):null,labels:s.labels?.nodes?.filter(G).map(It)??[]}},bt=s=>({id:s.number.toString(),graphQLId:s.id.toString(),number:s.number,title:s.title,description:s.description,isOpen:s.state=="OPEN",url:s.url,startDate:null,dueDate:s.dueOn?new Date(s.dueOn):null}),ae=class extends _{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let r=this._scopesCache[t];if(!r){let i=(await b(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];r=i?i.split(", "):[],this._scopesCache[t]=r}return r}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let r=this._enterpriseVersionsCache[t];if(!r){let o=await this.config.request({url:`${re(this.config,e)}/meta`,headers:f(e.token||this.config.token)});if(!o.body.installed_version)return null;r=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[t]=r}return r}getEnterpriseAvatarUrlIfNeeded(e,t,r){let o=r.baseUrl||this.config.baseUrl;return!o||o.startsWith(Ae)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let r=Wt(e.fields),o=await this.getScopes(t),i=await b(this.config,{query:`
371
+ `,Ss={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Es={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Cs={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},$s={OPEN:"OPEN",CLOSED:"CLOSED"},Ls=["ADMIN","MAINTAIN","TRIAGE","WRITE"],bt=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Ds=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Rt=s=>({id:s.databaseId.toString(),graphQLId:s.id,namespace:s.owner.login,name:s.name,webUrl:s.url,httpsUrl:s.url.endsWith(".git")?s.url:`${s.url}.git`,sshUrl:s.sshUrl,defaultBranch:s.defaultBranchRef,permissions:Ds(s.viewerPermission)}),Us=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),fr=s=>({id:s.id.toString(),graphQLId:s.node_id,namespace:s.owner.login,name:s.name,webUrl:s.html_url,httpsUrl:s.clone_url,sshUrl:s.ssh_url,defaultBranch:{name:s.default_branch},permissions:Us(s.permissions)}),As=s=>({path:s.path,isDirectory:s.type==="tree"}),Gs={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},Ts={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},F=(s,n=Ts)=>{let e={};return n.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),n.graphQLId&&(e.graphQLId=s.id),n.name&&(e.name=s.name??s.login),n.username&&(e.username=s.login),n.email&&(e.email=s.email??null),n.avatarUrl&&(e.avatarUrl=s.avatarUrl),n.url&&(e.url=s.url),e},Os=(s,n)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return s!=="COMPLETED"?e[s]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[n]},xs=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],It=s=>{let n=null;s.author?n=s.author:n=be;let e=(s.reviewRequests?.nodes||[]).filter(T).filter(i=>!i.asCodeOwner),t=s.headRepository?.url;t&&!t.endsWith(".git")&&(t=`${t}.git`);let r=s.repository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:F(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(T).map(i=>{let a=be;return i.author&&i.author.__typename&&(a=i.author),{reviewer:F(a),state:Ss[i.state]}}));return{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,title:s.title,description:s.body,number:s.number,state:Gs[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:n&&n.__typename?F(n):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.repository.sshUrl}},headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(T)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(T).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:xs(i.state),startedAt:new Date(i.createdAt),stage:null,url:i.targetUrl}:{completedAt:i.completedAt?new Date(i.completedAt):null,description:null,name:i.name,state:Os(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:s.headRef?{name:s.headRef.name,oid:s.headRef.target?.oid??null}:null,baseRef:s.baseRef?{name:s.baseRef.name,oid:s.baseRef.target?.oid??null}:null,url:s.url,updatedDate:new Date(s.updatedAt),closedDate:s.closedAt?new Date(s.closedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees.nodes?s.assignees.nodes.filter(T).map(i=>F(i)):null,reviews:o,reviewDecision:j(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:Cs[s.mergeStateStatus]??Es[s.mergeable],milestone:s.milestone?yt(s.milestone):null,labels:s.labels?.nodes?.filter(T).map(bt)??[],permissions:{canMerge:Ls.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},_s=s=>{let{id:n,comments:e,isOutdated:t,isResolved:r,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:p}=s,c=e.nodes?.[0];if(!c)return null;let{author:d,body:g,databaseId:m,fullDatabaseId:I,id:y,path:h,publishedAt:v,url:$}=c,x=o??u,E=i??l,P=a??p;return{author:d?{avatarUrl:d.avatarUrl,email:null,name:d.login}:null,body:g,createdAt:v?new Date(v):null,diffLines:ar(c.diffHunk,x,E,P),id:I??m.toString(),isOutdated:t,isResolved:r,graphQLId:y,threadId:n,filename:h,replies:e.nodes?.filter(T).slice(1).map(ks)??[],url:$,line:x,startLine:E,side:P}},ks=s=>({author:s.author?{avatarUrl:s.author.avatarUrl,email:null,name:s.author.login}:null,body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId.toString(),url:s.url}),Ns=s=>{let n=null;return s.author?n=s.author:n=be,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:n&&n.__typename?F(n):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:$s[s.state],color:null},type:null,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login}},url:s.url,updatedDate:new Date(s.updatedAt),assignees:s.assignees.nodes?.filter(T).map(e=>F(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?yt(s.milestone):null,labels:s.labels?.nodes?.filter(T).map(bt)??[]}},yt=s=>({id:s.number.toString(),graphQLId:s.id.toString(),number:s.number,title:s.title,description:s.description,isOpen:s.state=="OPEN",url:s.url,startDate:null,dueDate:s.dueOn?new Date(s.dueOn):null}),pe=class extends _{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let r=this._scopesCache[t];if(!r){let i=(await b(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];r=i?i.split(", "):[],this._scopesCache[t]=r}return r}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let r=this._enterpriseVersionsCache[t];if(!r){let o=await this.config.request({url:`${se(this.config,e)}/meta`,headers:f(e.token||this.config.token)});if(!o.body.installed_version)return null;r=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[t]=r}return r}getEnterpriseAvatarUrlIfNeeded(e,t,r){let o=r.baseUrl||this.config.baseUrl;return!o||o.startsWith(Ae)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let r=Wt(e.fields),o=await this.getScopes(t),i=await b(this.config,{query:`
372
372
  query getCurrentUser {
373
373
  viewer {
374
- ${k(!1,H(o),r)}
374
+ ${k(!1,z(o),r)}
375
375
  }
376
376
  }
377
377
  `},t),a=i.body.data?.viewer;if(!a)throw new R("Current user not found.",i.body.errors);return{data:F(a,r)}}async getAccountsForRepo(e,t={}){let r=await this.getScopes(t),{repo:{namespace:o,name:i},cursor:a}=e,u=await b(this.config,{query:`
@@ -379,7 +379,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
379
379
  repository(owner: $owner, name: $name) {
380
380
  assignableUsers(first: $first, after: $cursor) {
381
381
  nodes {
382
- ${k(!1,H(r))}
382
+ ${k(!1,z(r))}
383
383
  }
384
384
  pageInfo {
385
385
  endCursor
@@ -439,7 +439,7 @@ query getAccountForEmail($query: String! $avatarSize: Int) {
439
439
  search(query: $query, type: USER, first: 1) {
440
440
  nodes {
441
441
  ... on User {
442
- ${k(!0,H(r))}
442
+ ${k(!0,z(r))}
443
443
  }
444
444
  }
445
445
  }
@@ -447,7 +447,7 @@ query getAccountForEmail($query: String! $avatarSize: Int) {
447
447
  `,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},t),i=o.body.data?.search?.nodes?.[0];if(!i)throw new R("Could not find user via email",o.body.errors);return{data:F({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getAccountForUsername(e,t={}){let r=await this.getScopes(t),o=await b(this.config,{query:`
448
448
  query getUserForUsername($login: String! $avatarSize: Int) {
449
449
  user(login: $login) {
450
- ${k(!0,H(r))}
450
+ ${k(!0,z(r))}
451
451
  }
452
452
  }
453
453
  `,variables:{login:e.username,avatarSize:e.avatarSize}},t),i=o.body.data?.user;if(!i)throw new R("Could not find user via username",o.body.errors);return{data:F({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getOrgsForCurrentUser(e={},t={}){let r=await b(this.config,{query:`
@@ -488,19 +488,19 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
488
488
  `,variables:{cursor:e.cursor,first:L,login:e.org}},t);if(!r.body.data?.viewer.organization?.membersWithRole&&r.body.errors?.length)throw new R("Could not read the members of the organization",r.body.errors);let o=r.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:r.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:r.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>F({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}))}}async getRepo(e,t={}){let r=await b(this.config,{query:`
489
489
  query getRepo($owner: String!, $name: String!) {
490
490
  repository(owner: $owner, name: $name) {
491
- ${ht}
491
+ ${ft}
492
492
  }
493
493
  }
494
- `,variables:{owner:e.namespace,name:e.name}},t);if(!r.body.data?.repository)throw new R(`Repository ${e.namespace}/${e.name} not found`,r.body.errors);return{data:ft(r.body.data.repository)}}async getRepos(e,t={}){let r=e.map(({namespace:u,name:l},p)=>`
494
+ `,variables:{owner:e.namespace,name:e.name}},t);if(!r.body.data?.repository)throw new R(`Repository ${e.namespace}/${e.name} not found`,r.body.errors);return{data:Rt(r.body.data.repository)}}async getRepos(e,t={}){let r=e.map(({namespace:u,name:l},p)=>`
495
495
  getRepo_${p}: repository(owner: "${u}", name: "${l}") {
496
- ${ht}
496
+ ${ft}
497
497
  }
498
498
  `).join(`
499
499
  `),o=await b(this.config,{query:`
500
500
  query batchGetRepos {
501
501
  ${r}
502
502
  }
503
- `},t);if(!o.body.data)throw new R("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(ft(p)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,t,r,o){let i=[];for(let c=0;c<t;c++)i.push(r(e+c));let a=await Promise.all(i),u=[];for(let c of a){if(!c.body)throw new Error(c.statusText||"Unknown error");u=u.concat(c.body.map(d=>o(d)))}let l=a.every(c=>c.body.length===100),p=e+t;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?p:null}}}async getReposForCurrentUser(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let r=new URLSearchParams;r.append("per_page","100"),e.affiliations&&r.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${re(this.config,t)}/user/repos?${r.toString()}&page=${i}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,fr)}async getReposForOrg(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let r=o=>this.config.request({url:`${re(this.config,t)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,r,fr)}async getReposForUsernames(e,t={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let r=await b(this.config,{query:`
503
+ `},t);if(!o.body.data)throw new R("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(Rt(p)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,t,r,o){let i=[];for(let c=0;c<t;c++)i.push(r(e+c));let a=await Promise.all(i),u=[];for(let c of a){if(!c.body)throw new Error(c.statusText||"Unknown error");u=u.concat(c.body.map(d=>o(d)))}let l=a.every(c=>c.body.length===100),p=e+t;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?p:null}}}async getReposForCurrentUser(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let r=new URLSearchParams;r.append("per_page","100"),e.affiliations&&r.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${se(this.config,t)}/user/repos?${r.toString()}&page=${i}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,fr)}async getReposForOrg(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let r=o=>this.config.request({url:`${se(this.config,t)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,r,fr)}async getReposForUsernames(e,t={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let r=await b(this.config,{query:`
504
504
  query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
505
505
  search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
506
506
  pageInfo {
@@ -509,12 +509,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
509
509
  }
510
510
  nodes {
511
511
  ... on Repository {
512
- ${ht}
512
+ ${ft}
513
513
  }
514
514
  }
515
515
  }
516
516
  }
517
- `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:L}},t);if(!r.body.data)throw new R("Could not fetch repos for usernames",r.body.errors);let o=r.body.data.search.nodes||[];return{pageInfo:r.body.data.search.pageInfo,data:o.map(ft)}}async getReposForOwners(e,t={}){return this.getReposForUsernames({usernames:e.owners.filter(r=>r.username).map(r=>r.username),cursor:e.cursor},t)}async getRefs(e,t,r={}){let o=await b(this.config,{query:`
517
+ `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:L}},t);if(!r.body.data)throw new R("Could not fetch repos for usernames",r.body.errors);let o=r.body.data.search.nodes||[];return{pageInfo:r.body.data.search.pageInfo,data:o.map(Rt)}}async getReposForOwners(e,t={}){return this.getReposForUsernames({usernames:e.owners.filter(r=>r.username).map(r=>r.username),cursor:e.cursor},t)}async getRefs(e,t,r={}){let o=await b(this.config,{query:`
518
518
  query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
519
519
  repository(owner: $owner, name: $name) {
520
520
  refs(refPrefix: $refPrefix first: $first after: $cursor) {
@@ -574,7 +574,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
574
574
  }
575
575
  }
576
576
  }
577
- `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=r.body.data?.repository;if(!o)throw new R("Blame repository not found.",r.body.errors);let i=o.object;if(!i||!("blame"in i))throw new R("Ref not found.",r.body.errors);if(i.blame.ranges.length===0)throw new R("File not found.",r.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,t={}){let r=await this.config.request({url:`${re(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(r.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!r.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${r.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([r.body])}}async getMergeBase(e,t={}){return{data:(await this.config.request({url:`${re(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:f(t.token||this.config.token)})).body.merge_base_commit.sha}}async searchPullRequests(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=p=>{let c=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return gt("pr",c,e.cursor,{maxPageSize:e.maxPageSize??sr,supportsEmail:i,supportsDrafts:p,enterpriseVersion:r,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await b(this.config,a(!0),t);u.body.errors&&xe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(G).map(Rt)||[]}}async searchIssues(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=await b(this.config,gt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??nr,enterpriseVersion:r}),t),{data:u}=a.body;if(!u)throw new R("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(G).map(_s)||[]}}async getPullRequestsAssociatedWithUser(e,t={}){let r=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{r.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{r.push(`label:"${o}"`)}),this.searchPullRequests({query:r.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:r,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:c,maxPageSize:d}=e,g=mt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),r&&r.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),p&&g.push(`mentions:${p}`),c&&c.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:d},t)}async getPullRequestForRepo(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=c=>({query:`query getPullRequest(
577
+ `,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=r.body.data?.repository;if(!o)throw new R("Blame repository not found.",r.body.errors);let i=o.object;if(!i||!("blame"in i))throw new R("Ref not found.",r.body.errors);if(i.blame.ranges.length===0)throw new R("File not found.",r.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,t={}){let r=await this.config.request({url:`${se(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(r.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!r.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${r.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([r.body])}}async getMergeBase(e,t={}){return{data:(await this.config.request({url:`${se(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:f(t.token||this.config.token)})).body.merge_base_commit.sha}}async searchPullRequests(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=z(o),a=p=>{let c=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return ht("pr",c,e.cursor,{maxPageSize:e.maxPageSize??sr,supportsEmail:i,supportsDrafts:p,enterpriseVersion:r,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await b(this.config,a(!0),t);u.body.errors&&xe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(T).map(It)||[]}}async searchIssues(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=z(o),a=await b(this.config,ht("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??nr,enterpriseVersion:r}),t),{data:u}=a.body;if(!u)throw new R("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(T).map(Ns)||[]}}async getPullRequestsAssociatedWithUser(e,t={}){let r=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{r.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{r.push(`label:"${o}"`)}),this.searchPullRequests({query:r.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:r,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:p,labelNames:c,maxPageSize:d}=e,g=gt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),r&&r.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),p&&g.push(`mentions:${p}`),c&&c.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:d},t)}async getPullRequestForRepo(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=z(o),a=c=>({query:`query getPullRequest(
578
578
  $owner: String!
579
579
  $name: String!
580
580
  $number: Int!
@@ -587,7 +587,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
587
587
  ${Oe(c,i,r)}
588
588
  }
589
589
  }
590
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),t);u.body.errors&&xe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not fetch pull request by number",u.body.errors);let p=u.body.data?.repository.pullRequest;return{data:p?Rt(p):null}}async getPullRequestByGraphQLId(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=H(o),a=c=>({query:`query getPullRequest(
590
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),t);u.body.errors&&xe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not fetch pull request by number",u.body.errors);let p=u.body.data?.repository.pullRequest;return{data:p?It(p):null}}async getPullRequestByGraphQLId(e,t={}){let r=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=z(o),a=c=>({query:`query getPullRequest(
591
591
  $graphQLId: ID!
592
592
  ) {
593
593
  node(id: $graphQLId) {
@@ -595,7 +595,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
595
595
  ${Oe(c,i,r)}
596
596
  }
597
597
  }
598
- }`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),t);u.body.errors&&xe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not fetch pull request by id",u.body.errors);let p=u.body.data?.node;return{data:p?Rt(p):null}}async closePullRequest(e,t={}){let{pullRequest:{graphQLId:r}}=e;if(!r)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
598
+ }`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),t);u.body.errors&&xe(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not fetch pull request by id",u.body.errors);let p=u.body.data?.node;return{data:p?It(p):null}}async closePullRequest(e,t={}){let{pullRequest:{graphQLId:r}}=e;if(!r)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
599
599
  closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
600
600
  pullRequest {
601
601
  id
@@ -770,7 +770,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
770
770
  login
771
771
  }
772
772
  body
773
- ${!r||B(r,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
773
+ ${!r||Q(r,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
774
774
  diffHunk
775
775
  id
776
776
  path
@@ -790,7 +790,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
790
790
  login
791
791
  }
792
792
  body
793
- ${!r||B(r,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
793
+ ${!r||Q(r,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
794
794
  id
795
795
  publishedAt
796
796
  url
@@ -798,13 +798,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
798
798
  }
799
799
  }
800
800
  }
801
- }`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),p=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(G).reduce((d,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return d;let m=g.comments.nodes[0].pullRequestReview,I=Os(g);return I&&(d[m.id]||(d[m.id]=[]),d[m.id].push(I)),d},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(G).filter(d=>p[d.id]).map(d=>({author:d.author?{avatarUrl:d.author.avatarUrl,email:null,name:d.author.login}:null,body:d.body,createdAt:d.publishedAt?new Date(d.publishedAt):null,id:d.fullDatabaseId??d.databaseId.toString(),graphQLId:d.id,reviewComments:p[d.id],url:d.url}))??[]}}async getCommentsForPullRequest(e,t={}){let r=await this.getEnterpriseVersion(t),o=!r||B(r,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,p=await b(this.config,{query:hr(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:L}},t),c=p.body.data?.repository;if(!c)throw new R("Could not fetch pull request comments",p.body.errors);return{data:c.pullRequest.comments.nodes?.filter(G).map(ur)??[],pageInfo:c.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,t={}){let[r,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(d=>{i.push(`label:"${d}"`)});let[a,u]=await Promise.all([r==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:r,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)]),l={},p=[],c=d=>{l[d.id]||(l[d.id]=!0,p.push(d))};return a?.data.forEach(c),u?.data.forEach(c),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:p}}async setPullRequestLabels(e,t={}){let{pullRequest:r,labels:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
801
+ }`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),p=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(T).reduce((d,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return d;let m=g.comments.nodes[0].pullRequestReview,I=_s(g);return I&&(d[m.id]||(d[m.id]=[]),d[m.id].push(I)),d},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(T).filter(d=>p[d.id]).map(d=>({author:d.author?{avatarUrl:d.author.avatarUrl,email:null,name:d.author.login}:null,body:d.body,createdAt:d.publishedAt?new Date(d.publishedAt):null,id:d.fullDatabaseId??d.databaseId.toString(),graphQLId:d.id,reviewComments:p[d.id],url:d.url}))??[]}}async getCommentsForPullRequest(e,t={}){let r=await this.getEnterpriseVersion(t),o=!r||Q(r,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,p=await b(this.config,{query:hr(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:L}},t),c=p.body.data?.repository;if(!c)throw new R("Could not fetch pull request comments",p.body.errors);return{data:c.pullRequest.comments.nodes?.filter(T).map(ur)??[],pageInfo:c.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,t={}){let[r,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(d=>{i.push(`label:"${d}"`)});let[a,u]=await Promise.all([r==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:r,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)]),l={},p=[],c=d=>{l[d.id]||(l[d.id]=!0,p.push(d))};return a?.data.forEach(c),u?.data.forEach(c),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:p}}async setPullRequestLabels(e,t={}){let{pullRequest:r,labels:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
802
802
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
803
803
  pullRequest {
804
804
  id
805
805
  }
806
806
  }
807
- }`,a=await b(this.config,{query:i,variables:{pullRequestGraphQLId:r.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new R("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let r=mt(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(c=>{r.push(`repo:${c.namespace}/${c.name}`)}),i&&i.forEach(c=>{r.push(`assignee:${c}`)}),a&&r.push(`updated:<${a}`),u&&r.push(`author:${u}`),l&&r.push(`mentions:${l}`),p&&p.forEach(c=>{r.push(`label:"${c}"`)}),this.searchIssues({query:`sort:updated ${r.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async closeIssueWithReason(e,t={}){let{issue:r,reason:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
807
+ }`,a=await b(this.config,{query:i,variables:{pullRequestGraphQLId:r.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new R("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let r=gt(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:p}=e;return e.repos.forEach(c=>{r.push(`repo:${c.namespace}/${c.name}`)}),i&&i.forEach(c=>{r.push(`assignee:${c}`)}),a&&r.push(`updated:<${a}`),u&&r.push(`author:${u}`),l&&r.push(`mentions:${l}`),p&&p.forEach(c=>{r.push(`label:"${c}"`)}),this.searchIssues({query:`sort:updated ${r.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async closeIssueWithReason(e,t={}){let{issue:r,reason:o}=e;if(!r.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
808
808
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
809
809
  issue {
810
810
  id
@@ -854,7 +854,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
854
854
  }
855
855
  }
856
856
  }
857
- `,variables:{owner:r,name:o,cursor:i,first:L}},t);if(!a.body.data)throw new R("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(bt)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:r,name:o},cursor:i}=e,a=await b(this.config,{query:`
857
+ `,variables:{owner:r,name:o,cursor:i,first:L}},t);if(!a.body.data)throw new R("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(yt)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:r,name:o},cursor:i}=e,a=await b(this.config,{query:`
858
858
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
859
859
  repository(owner: $owner, name: $name) {
860
860
  labels(first: $first, after: $cursor) {
@@ -868,7 +868,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
868
868
  }
869
869
  }
870
870
  }
871
- `,variables:{owner:r,name:o,cursor:i,first:L}},t);if(!a.body.data)throw new R("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(It)??[]}}async getTreeForRepo(e,t={}){let r=await this.config.request({url:`${re(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...f(t.token||this.config.token)}});if(!r.body)throw new Error("Could not fetch trees");return{data:r.body.tree.map(Ds)}}};var ks="https://gitlab.com/api/v4",Ns="https://gitlab.com/api/graphql",yt=/\/api\/v\d+$/,Ir=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},U=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ir(e),yt.test(e)||(e=e+"/api/v4"),e):ks},Fs=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ir(e),yt.test(e)&&(e=e.replace(yt,"")),`${e}/api/graphql`):Ns},w=(s,n,e)=>{let t=f(e.token||s.token);return s.request({url:Fs(s,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(n)})},Ie=s=>s?.map(n=>`"${n.message}"`).join(", ");var Lt=s=>s.split("/").slice(0,-1).join("/"),Dt=s=>s.split("/").at(-1)??"",_e=s=>({id:s.id.replace(ue,""),graphQLId:s.id,namespace:Lt(s.fullPath),name:Dt(s.fullPath),webUrl:s.webUrl}),ke=s=>({id:s.id.replace(ue,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:Lt(s.fullPath),name:Dt(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),js={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Qs={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var yr="gid://gitlab/User/",ue="gid://gitlab/Project/",Bs="gid://gitlab/MergeRequest/",Ms="gid://gitlab/Issue/",zs="gid://gitlab/ProjectLabel/",Hs="gid://gitlab/Milestone/",Ws="gid://gitlab/Ci::Build/",Ut=`
871
+ `,variables:{owner:r,name:o,cursor:i,first:L}},t);if(!a.body.data)throw new R("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(bt)??[]}}async getTreeForRepo(e,t={}){let r=await this.config.request({url:`${se(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...f(t.token||this.config.token)}});if(!r.body)throw new Error("Could not fetch trees");return{data:r.body.tree.map(As)}}};var Fs="https://gitlab.com/api/v4",js="https://gitlab.com/api/graphql",Pt=/\/api\/v\d+$/,Ir=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},U=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ir(e),Pt.test(e)||(e=e+"/api/v4"),e):Fs},Qs=(s,n)=>{let e=n.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ir(e),Pt.test(e)&&(e=e.replace(Pt,"")),`${e}/api/graphql`):js},q=(s,n,e)=>{let t=f(e.token||s.token);return s.request({url:Qs(s,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(n)})},ye=s=>s?.map(n=>`"${n.message}"`).join(", ");var Dt=s=>s.split("/").slice(0,-1).join("/"),Ut=s=>s.split("/").at(-1)??"",_e=s=>({id:s.id.replace(de,""),graphQLId:s.id,namespace:Dt(s.fullPath),name:Ut(s.fullPath),webUrl:s.webUrl}),ke=s=>({id:s.id.replace(de,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:Dt(s.fullPath),name:Ut(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Bs={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Ms={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var yr="gid://gitlab/User/",de="gid://gitlab/Project/",zs="gid://gitlab/MergeRequest/",Hs="gid://gitlab/Issue/",Ws="gid://gitlab/ProjectLabel/",Js="gid://gitlab/Milestone/",Vs="gid://gitlab/Ci::Build/",At=`
872
872
  description
873
873
  dueDate
874
874
  id
@@ -877,7 +877,7 @@ startDate
877
877
  state
878
878
  title
879
879
  webPath
880
- `,Pt=`
880
+ `,wt=`
881
881
  id
882
882
  fullPath
883
883
  webUrl
@@ -891,25 +891,25 @@ userPermissions {
891
891
  downloadCode
892
892
  pushCode
893
893
  }
894
- `,W=`
894
+ `,H=`
895
895
  id
896
896
  name
897
897
  username
898
898
  publicEmail
899
899
  avatarUrl
900
900
  webUrl
901
- `,At=`
901
+ `,Gt=`
902
902
  color
903
903
  description
904
904
  id
905
905
  title
906
- `,wt=`
906
+ `,qt=`
907
907
  author {
908
- ${W}
908
+ ${H}
909
909
  }
910
910
  assignees {
911
911
  nodes {
912
- ${W}
912
+ ${H}
913
913
  }
914
914
  }
915
915
  closedAt
@@ -920,7 +920,7 @@ id
920
920
  iid
921
921
  labels {
922
922
  nodes {
923
- ${At}
923
+ ${Gt}
924
924
  }
925
925
  }
926
926
  state
@@ -931,9 +931,9 @@ upvotes
931
931
  userNotesCount
932
932
  webUrl
933
933
  milestone {
934
- ${Ut}
934
+ ${At}
935
935
  }
936
- `,Js=`
936
+ `,Ks=`
937
937
  stages {
938
938
  nodes {
939
939
  jobs {
@@ -949,11 +949,11 @@ stages {
949
949
  name
950
950
  }
951
951
  }
952
- `,qt=(s,n,e)=>`
952
+ `,vt=(s,n,e)=>`
953
953
  id
954
954
  state
955
955
  author {
956
- ${W}
956
+ ${H}
957
957
  }
958
958
  diffRefs {
959
959
  baseSha
@@ -979,12 +979,12 @@ targetBranch
979
979
  sourceBranch
980
980
  assignees {
981
981
  nodes {
982
- ${W}
982
+ ${H}
983
983
  }
984
984
  }
985
985
  reviewers {
986
986
  nodes {
987
- ${W}
987
+ ${H}
988
988
  mergeRequestInteraction {
989
989
  approved
990
990
  reviewState
@@ -994,25 +994,25 @@ reviewers {
994
994
  mergeStatusEnum
995
995
  labels {
996
996
  nodes {
997
- ${At}
997
+ ${Gt}
998
998
  }
999
999
  }
1000
1000
  ${s?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
1001
- ${n?`milestone { ${Ut} }`:""}
1002
- ${e?`headPipeline { ${Js} }`:""}
1003
- `,T=s=>`${s.namespace}/${s.name}`,Vs=s=>`${s.namespace}/${s.name}`,Ks=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),Xs=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),vt=s=>({id:s.id.replace(ue,""),graphQLId:s.id,namespace:Lt(s.fullPath),name:Dt(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:Xs(s.userPermissions)}),Zs=s=>({path:s.path,isDirectory:s.type==="tree"}),Ys={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Ne=(s,n,e)=>!n&&s?.startsWith("/")?`https://gitlab.com${s}`:n&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,J=(s,n,e)=>{let t=Ne(s.avatarUrl,n,e);return{id:s.id.replace(yr,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:t,url:s.webUrl}},Gt=s=>({color:s.color,description:s.description,id:s.id.replace(zs,""),graphQLId:s.id,name:s.title}),en=(s,n)=>s?s==="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"}[s]:null,tn=(s,n,e)=>{let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:J(s,n,e),state:s.mergeRequestInteraction?.reviewState?t[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},St=(s,n,e,t,r)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>tn(i,t,r)):null;return{id:s.id.replace(Bs,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:Ys[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?J(s.author,t,r):null,createdDate:new Date(s.createdAt),isDraft:s.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:s.headPipeline?.stages?.nodes?.flatMap(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:en(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${n.webUrl}/-/jobs/${a.id.replace(Ws,"")}`}))??[])??[]},baseRef:{name:s.targetBranch,oid:s.diffRefs?.baseSha??null},headRef:{name:s.sourceBranch,oid:s.diffRefs?.headSha??null},url:s.webUrl,updatedDate:new Date(s.updatedAt),closedDate:s.mergedAt?new Date(s.mergedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees?.nodes?s.assignees.nodes.map(i=>J(i,t,r)):null,reviews:o,reviewDecision:Q(o),additions:s.diffStatsSummary?.additions||0,deletions:s.diffStatsSummary?.deletions||0,fileCount:s.diffStatsSummary?.fileCount||0,commitCount:s.commitCount||0,mergeableState:Qs[s.mergeStatusEnum],milestone:s.milestone?Tt(s.milestone,n.webUrl):null,labels:s.labels?.nodes?.map(Gt)??[],permissions:null}},Et=(s,n,e,t)=>({author:J(s.author,e,t),assignees:s.assignees.nodes.map(r=>J(r,e,t)),commentCount:s.userNotesCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:s.description,graphQLId:s.id,id:s.id.replace(Ms,""),labels:s.labels?.nodes?.map(Gt)??[],number:s.iid,repository:{id:n.id.replace(ue,""),graphQLId:n.id,name:n.name,owner:{login:n.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?Tt(s.milestone,n.webUrl):null}),Tt=(s,n)=>({id:s.id.replace(Hs,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${n}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),rn=s=>Buffer.from(JSON.stringify(s),"utf8").toString("base64"),sn=(s,n)=>{if(!s)return{page:1,perPage:n};try{let e=JSON.parse(Buffer.from(s,"base64").toString("utf8")),t=typeof e.page=="number"&&e.page>0?e.page:1,r=typeof e.perPage=="number"&&e.perPage>0?e.perPage:n;return{page:t,perPage:r}}catch{return{page:1,perPage:n}}},nn=(s,n,e)=>({id:s.id.toString(),graphQLId:`${yr}${s.id}`,name:s.name,username:s.username,email:s.email??null,avatarUrl:Ne(s.avatar_url,n,e),url:s.web_url}),br=(s,n,e)=>({avatarUrl:Ne(s.avatar_url,n,e)??"",email:null,name:s.name}),on=s=>s?.new_line!=null?"RIGHT":s?.old_line!=null?"LEFT":null,an=s=>{let n=s.old_path||s.new_path,e=s.new_path||s.old_path,t=[`diff --git a/${n} b/${e}`];return s.new_file&&s.b_mode?t.push(`new file mode ${s.b_mode}`):s.deleted_file&&s.a_mode?t.push(`deleted file mode ${s.a_mode}`):s.a_mode&&s.b_mode&&s.a_mode!==s.b_mode&&(t.push(`old mode ${s.a_mode}`),t.push(`new mode ${s.b_mode}`)),s.renamed_file&&(t.push(`rename from ${s.old_path}`),t.push(`rename to ${s.new_path}`)),s.diff&&s.diff.length>0?(t.push(`--- ${s.new_file?"/dev/null":`a/${n}`}`),t.push(`+++ ${s.deleted_file?"/dev/null":`b/${e}`}`),`${t.join(`
1001
+ ${n?`milestone { ${At} }`:""}
1002
+ ${e?`headPipeline { ${Ks} }`:""}
1003
+ `,O=s=>`${s.namespace}/${s.name}`,Xs=s=>`${s.namespace}/${s.name}`,Zs=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),Ys=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),St=s=>({id:s.id.replace(de,""),graphQLId:s.id,namespace:Dt(s.fullPath),name:Ut(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:Ys(s.userPermissions)}),en=s=>({path:s.path,isDirectory:s.type==="tree"}),tn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Ne=(s,n,e)=>!n&&s?.startsWith("/")?`https://gitlab.com${s}`:n&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,W=(s,n,e)=>{let t=Ne(s.avatarUrl,n,e);return{id:s.id.replace(yr,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:t,url:s.webUrl}},Tt=s=>({color:s.color,description:s.description,id:s.id.replace(Ws,""),graphQLId:s.id,name:s.title}),rn=(s,n)=>s?s==="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"}[s]:null,sn=(s,n,e)=>{let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:W(s,n,e),state:s.mergeRequestInteraction?.reviewState?t[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},Et=(s,n,e,t,r)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>sn(i,t,r)):null;return{id:s.id.replace(zs,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:tn[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?W(s.author,t,r):null,createdDate:new Date(s.createdAt),isDraft:s.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:s.headPipeline?.stages?.nodes?.flatMap(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:rn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${n.webUrl}/-/jobs/${a.id.replace(Vs,"")}`}))??[])??[]},baseRef:{name:s.targetBranch,oid:s.diffRefs?.baseSha??null},headRef:{name:s.sourceBranch,oid:s.diffRefs?.headSha??null},url:s.webUrl,updatedDate:new Date(s.updatedAt),closedDate:s.mergedAt?new Date(s.mergedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees?.nodes?s.assignees.nodes.map(i=>W(i,t,r)):null,reviews:o,reviewDecision:j(o),additions:s.diffStatsSummary?.additions||0,deletions:s.diffStatsSummary?.deletions||0,fileCount:s.diffStatsSummary?.fileCount||0,commitCount:s.commitCount||0,mergeableState:Ms[s.mergeStatusEnum],milestone:s.milestone?Ot(s.milestone,n.webUrl):null,labels:s.labels?.nodes?.map(Tt)??[],permissions:null}},Ct=(s,n,e,t)=>({author:W(s.author,e,t),assignees:s.assignees.nodes.map(r=>W(r,e,t)),commentCount:s.userNotesCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:s.description,graphQLId:s.id,id:s.id.replace(Hs,""),labels:s.labels?.nodes?.map(Tt)??[],number:s.iid,repository:{id:n.id.replace(de,""),graphQLId:n.id,name:n.name,owner:{login:n.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?Ot(s.milestone,n.webUrl):null}),Ot=(s,n)=>({id:s.id.replace(Js,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${n}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),nn=s=>Buffer.from(JSON.stringify(s),"utf8").toString("base64"),on=(s,n)=>{if(!s)return{page:1,perPage:n};try{let e=JSON.parse(Buffer.from(s,"base64").toString("utf8")),t=typeof e.page=="number"&&e.page>0?e.page:1,r=typeof e.perPage=="number"&&e.perPage>0?e.perPage:n;return{page:t,perPage:r}}catch{return{page:1,perPage:n}}},an=(s,n,e)=>({id:s.id.toString(),graphQLId:`${yr}${s.id}`,name:s.name,username:s.username,email:s.email??null,avatarUrl:Ne(s.avatar_url,n,e),url:s.web_url}),br=(s,n,e)=>({avatarUrl:Ne(s.avatar_url,n,e)??"",email:null,name:s.name}),un=s=>s?.new_line!=null?"RIGHT":s?.old_line!=null?"LEFT":null,ln=s=>{let n=s.old_path||s.new_path,e=s.new_path||s.old_path,t=[`diff --git a/${n} b/${e}`];return s.new_file&&s.b_mode?t.push(`new file mode ${s.b_mode}`):s.deleted_file&&s.a_mode?t.push(`deleted file mode ${s.a_mode}`):s.a_mode&&s.b_mode&&s.a_mode!==s.b_mode&&(t.push(`old mode ${s.a_mode}`),t.push(`new mode ${s.b_mode}`)),s.renamed_file&&(t.push(`rename from ${s.old_path}`),t.push(`rename to ${s.new_path}`)),s.diff&&s.diff.length>0?(t.push(`--- ${s.new_file?"/dev/null":`a/${n}`}`),t.push(`+++ ${s.deleted_file?"/dev/null":`b/${e}`}`),`${t.join(`
1004
1004
  `)}
1005
1005
  ${s.diff.endsWith(`
1006
1006
  `)?s.diff:`${s.diff}
1007
1007
  `}`):`${t.join(`
1008
1008
  `)}
1009
- `},Pr="|",$t=(s,n,e,t)=>[s,n,e.toString(),t.toString()].join(Pr),un=s=>{let n=s.split(Pr);if(n.length!==4)throw new Error("Invalid GitLab comment ID format \u2014 expected a composite ID produced by getCommentsForPullRequest or addInlineCommentToPullRequest.");return{namespace:n[0],name:n[1],mergeRequestIid:n[2],noteId:n[3]}},Ct=(s,n,e,t)=>({author:s.author?nn(s.author,n,e):null,body:s.body,createdAt:s.created_at?new Date(s.created_at):null,id:$t(t.namespace,t.name,t.mergeRequestIid,s.id),url:""}),le=class extends _{getIsSelfHosted(n){return!!n.baseUrl||!!this.config.baseUrl}async getCurrentUser(n={},e={}){let r=(await w(this.config,{query:`
1009
+ `},Pr="|",Lt=(s,n,e,t)=>[s,n,e.toString(),t.toString()].join(Pr),pn=s=>{let n=s.split(Pr);if(n.length!==4)throw new Error("Invalid GitLab comment ID format \u2014 expected a composite ID produced by getCommentsForPullRequest or addInlineCommentToPullRequest.");return{namespace:n[0],name:n[1],mergeRequestIid:n[2],noteId:n[3]}},$t=(s,n,e,t)=>({author:s.author?an(s.author,n,e):null,body:s.body,createdAt:s.created_at?new Date(s.created_at):null,id:Lt(t.namespace,t.name,t.mergeRequestIid,s.id),url:""}),ce=class extends _{getIsSelfHosted(n){return!!n.baseUrl||!!this.config.baseUrl}async getCurrentUser(n={},e={}){let r=(await q(this.config,{query:`
1010
1010
  query getCurrentUser {
1011
1011
  currentUser {
1012
- ${W}
1012
+ ${H}
1013
1013
  }
1014
1014
  }
1015
- `},e)).body.data?.currentUser;if(!r)throw new Error("Current user not found.");return{data:J(r,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(n,e={}){let t=T(n.repo),o=(await w(this.config,{query:`
1015
+ `},e)).body.data?.currentUser;if(!r)throw new Error("Current user not found.");return{data:W(r,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(n,e={}){let t=O(n.repo),o=(await q(this.config,{query:`
1016
1016
  query getUserForCommit($fullPath: ID!, $oid: String!) {
1017
1017
  project(fullPath: $fullPath) {
1018
1018
  repository {
@@ -1028,21 +1028,21 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
1028
1028
  }
1029
1029
  }
1030
1030
  }
1031
- `,variables:{fullPath:t,oid:n.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Ne(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(n,e={}){let r=(await w(this.config,{query:`
1031
+ `,variables:{fullPath:t,oid:n.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Ne(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(n,e={}){let r=(await q(this.config,{query:`
1032
1032
  query getAccountForEmail($email: String!) {
1033
1033
  users(search: $email) {
1034
1034
  nodes {
1035
- ${W}
1035
+ ${H}
1036
1036
  }
1037
1037
  }
1038
1038
  }
1039
- `,variables:{email:n.email}},e)).body.data?.users?.nodes?.[0];if(!r)throw new Error("User not found.");return{data:J(r,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(n,e={}){let r=(await w(this.config,{query:`
1039
+ `,variables:{email:n.email}},e)).body.data?.users?.nodes?.[0];if(!r)throw new Error("User not found.");return{data:W(r,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(n,e={}){let r=(await q(this.config,{query:`
1040
1040
  query getAccountForUsername($username: String!) {
1041
1041
  user(username: $username) {
1042
- ${W}
1042
+ ${H}
1043
1043
  }
1044
1044
  }
1045
- `,variables:{username:n.username}},e)).body.data?.user;if(!r)throw new Error("User not found.");return{data:J(r,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(n,e={}){let{repo:{namespace:t,name:r},cursor:o}=n,i=await w(this.config,{query:`
1045
+ `,variables:{username:n.username}},e)).body.data?.user;if(!r)throw new Error("User not found.");return{data:W(r,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(n,e={}){let{repo:{namespace:t,name:r},cursor:o}=n,i=await q(this.config,{query:`
1046
1046
  query getAccountsForRepo(
1047
1047
  $fullPath: ID!
1048
1048
  $after: String
@@ -1053,7 +1053,7 @@ query getAccountsForRepo(
1053
1053
  projectMembers(after: $after) {
1054
1054
  nodes {
1055
1055
  user {
1056
- ${W}
1056
+ ${H}
1057
1057
  }
1058
1058
  }
1059
1059
  pageInfo {
@@ -1063,22 +1063,22 @@ query getAccountsForRepo(
1063
1063
  }
1064
1064
  }
1065
1065
  }
1066
- `,variables:{fullPath:`${t}/${r}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>J(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(n,e={}){let t=T(n),r=await w(this.config,{query:`
1066
+ `,variables:{fullPath:`${t}/${r}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>W(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(n,e={}){let t=O(n),r=await q(this.config,{query:`
1067
1067
  query getRepo($fullPath: ID!) {
1068
1068
  project(fullPath: $fullPath) {
1069
- ${Pt}
1069
+ ${wt}
1070
1070
  }
1071
1071
  }
1072
- `,variables:{fullPath:t}},e);if(!r.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:vt(r.body.data.project)}}async getReposBase(n,e={}){let r=n.map(T).map((u,l)=>`
1072
+ `,variables:{fullPath:t}},e);if(!r.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:St(r.body.data.project)}}async getReposBase(n,e={}){let r=n.map(O).map((u,l)=>`
1073
1073
  getRepo_${l}: project(fullPath: "${u}") {
1074
- ${Pt}
1074
+ ${wt}
1075
1075
  }
1076
1076
  `).join(`
1077
- `),o=await w(this.config,{query:`
1077
+ `),o=await q(this.config,{query:`
1078
1078
  query batchGetRepos {
1079
1079
  ${r}
1080
1080
  }
1081
- `},e);if(!o.body.data)throw new Error(Ie(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return n.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(vt(p)):a.push({input:u})}),{data:i,errors:a}}async getRepos(n,e={}){let t=[];for(let i=0;i<n.length;i+=15)t.push(n.slice(i,i+15));return(await Promise.all(t.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(n,e={}){let t=await w(this.config,{query:`
1081
+ `},e);if(!o.body.data)throw new Error(ye(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return n.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(St(p)):a.push({input:u})}),{data:i,errors:a}}async getRepos(n,e={}){let t=[];for(let i=0;i<n.length;i+=15)t.push(n.slice(i,i+15));return(await Promise.all(t.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(n,e={}){let t=await q(this.config,{query:`
1082
1082
  query getReposForCurrentUser($after: String) {
1083
1083
  projects(membership: true first: 100 after: $after) {
1084
1084
  pageInfo {
@@ -1086,11 +1086,11 @@ query getReposForCurrentUser($after: String) {
1086
1086
  hasNextPage
1087
1087
  }
1088
1088
  nodes {
1089
- ${Pt}
1089
+ ${wt}
1090
1090
  }
1091
1091
  }
1092
1092
  }
1093
- `,variables:{after:n.cursor}},e);if(!t.body.data?.projects)throw new Error(Ie(t.body.errors)||t.statusText||"Unknown error");let r=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:r.map(vt)}}async getRefs(n,e,t={}){let r=T(e.repo),o=new URL(`${U(this.config,t)}/projects/${encodeURIComponent(r)}/repository/${n}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",L.toString());let i=await this.config.request({url:o.toString(),headers:f(t.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(u=>({name:u.name,commit:{oid:u.commit.id,authoredDate:new Date(u.commit.authored_date),committedDate:new Date(u.commit.committed_date)}}))}}async getBranches(n,e={}){return this.getRefs("branches",n,e)}async getTags(n,e={}){return this.getRefs("tags",n,e)}async getBlame(n,e={}){let t=T(n.repo),r=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/blame`);r.searchParams.set("ref",n.ref);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(n,e={}){let t="";n.repo?.id?t=`projectId:"${n.repo.id}"`:n.repo?.namespace&&n.repo?.name&&(t=`projectPath:"${n.repo.namespace}/${n.repo.name}"`);let r=js[n.association],o=await w(this.config,{query:`
1093
+ `,variables:{after:n.cursor}},e);if(!t.body.data?.projects)throw new Error(ye(t.body.errors)||t.statusText||"Unknown error");let r=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:r.map(St)}}async getRefs(n,e,t={}){let r=O(e.repo),o=new URL(`${U(this.config,t)}/projects/${encodeURIComponent(r)}/repository/${n}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",L.toString());let i=await this.config.request({url:o.toString(),headers:f(t.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(u=>({name:u.name,commit:{oid:u.commit.id,authoredDate:new Date(u.commit.authored_date),committedDate:new Date(u.commit.committed_date)}}))}}async getBranches(n,e={}){return this.getRefs("branches",n,e)}async getTags(n,e={}){return this.getRefs("tags",n,e)}async getBlame(n,e={}){let t=O(n.repo),r=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/blame`);r.searchParams.set("ref",n.ref);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(n,e={}){let t="";n.repo?.id?t=`projectId:"${n.repo.id}"`:n.repo?.namespace&&n.repo?.name&&(t=`projectPath:"${n.repo.namespace}/${n.repo.name}"`);let r=Bs[n.association],o=await q(this.config,{query:`
1094
1094
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
1095
1095
  user(username: $username) {
1096
1096
  ${r}(state:opened first:100 after:$cursor labels: $labelNames${t?` ${t}`:""}) {
@@ -1099,12 +1099,12 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
1099
1099
  hasNextPage
1100
1100
  }
1101
1101
  nodes {
1102
- ${qt(!0,!0,!0)}
1102
+ ${vt(!0,!0,!0)}
1103
1103
  }
1104
1104
  }
1105
1105
  }
1106
1106
  }
1107
- `,variables:{username:n.username,cursor:n.cursor,labelNames:n.labelNames}},e);if(!o.body.data)throw new Error(Ie(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[r];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:i.nodes?.filter(a=>n.includeFromArchivedRepos||!a.project.archived).map(a=>St(a,ke(a.project),ke(a.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[]}}async getPullRequestsAssociatedWithUser(n,e={}){let[t,r,o]=n.cursor?.split(";")||[void 0,void 0,void 0],i=t?.split("-")||[],a=r?.split("-")||[],u=o?.split("-")||[],l=[],p=[],c=[],d=0;do{let S=n.repos&&n.repos[d];i[d]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:n.username,association:"authored",cursor:i[d],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...S&&{repo:S}},e)),a[d]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:n.username,association:"assigned",cursor:a[d],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...S&&{repo:S}},e)),u[d]==="null"?c.push(null):c.push(this.getPullRequestsForUser({username:n.username,association:"reviewRequested",cursor:u[d],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...S&&{repo:S}},e)),d++}while(d<(n.repos?.length||0));let g=[l,p,c].flat(),m=await Promise.all(g),I={},y=[],h=S=>{I[S.id]||(I[S.id]=!0,y.push(S))},q=!1,x=m.map((S,E)=>{let v="";return S&&S.data.forEach(h),S?.pageInfo.hasNextPage?(q=!0,v+=`${S.pageInfo.endCursor||"null"}`):v+="null",n.repos?.length&&(E+1)%n.repos.length!==0?v+="-":E+1<m.length&&(v+=";"),v}).join("");return{pageInfo:{hasNextPage:q,endCursor:x},data:y}}getVariablesForPullRequests(n){let{updatedBefore:e,isDraft:t,authorLogin:r,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=n||{},u={},l=[],p=[],c=(d,g,m)=>{l.push(`$${d}: ${m}`),p.push(`${d}: $${d}`),u[d]=g};return e&&c("updatedBefore",e,"Time"),r&&c("authorUsername",r,"String"),o&&c("assigneeUsername",o[0],"String"),i&&c("labelName",i,"[String]"),t!=null&&c("draft",t,"Boolean"),a&&c("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(n,e={},t){let{cursor:r,repo:o}=n||{},i=T(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(n),p={fullPath:i,...a},c=await w(this.config,{query:`
1107
+ `,variables:{username:n.username,cursor:n.cursor,labelNames:n.labelNames}},e);if(!o.body.data)throw new Error(ye(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[r];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:i.nodes?.filter(a=>n.includeFromArchivedRepos||!a.project.archived).map(a=>Et(a,ke(a.project),ke(a.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[]}}async getPullRequestsAssociatedWithUser(n,e={}){let[t,r,o]=n.cursor?.split(";")||[void 0,void 0,void 0],i=t?.split("-")||[],a=r?.split("-")||[],u=o?.split("-")||[],l=[],p=[],c=[],d=0;do{let E=n.repos&&n.repos[d];i[d]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:n.username,association:"authored",cursor:i[d],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...E&&{repo:E}},e)),a[d]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:n.username,association:"assigned",cursor:a[d],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...E&&{repo:E}},e)),u[d]==="null"?c.push(null):c.push(this.getPullRequestsForUser({username:n.username,association:"reviewRequested",cursor:u[d],includeFromArchivedRepos:n.includeFromArchivedRepos,labelNames:n.labelNames,...E&&{repo:E}},e)),d++}while(d<(n.repos?.length||0));let g=[l,p,c].flat(),m=await Promise.all(g),I={},y=[],h=E=>{I[E.id]||(I[E.id]=!0,y.push(E))},v=!1,x=m.map((E,P)=>{let S="";return E&&E.data.forEach(h),E?.pageInfo.hasNextPage?(v=!0,S+=`${E.pageInfo.endCursor||"null"}`):S+="null",n.repos?.length&&(P+1)%n.repos.length!==0?S+="-":P+1<m.length&&(S+=";"),S}).join("");return{pageInfo:{hasNextPage:v,endCursor:x},data:y}}getVariablesForPullRequests(n){let{updatedBefore:e,isDraft:t,authorLogin:r,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=n||{},u={},l=[],p=[],c=(d,g,m)=>{l.push(`$${d}: ${m}`),p.push(`${d}: $${d}`),u[d]=g};return e&&c("updatedBefore",e,"Time"),r&&c("authorUsername",r,"String"),o&&c("assigneeUsername",o[0],"String"),i&&c("labelName",i,"[String]"),t!=null&&c("draft",t,"Boolean"),a&&c("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(n,e={},t){let{cursor:r,repo:o}=n||{},i=O(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(n),p={fullPath:i,...a},c=await q(this.config,{query:`
1108
1108
  query getPullRequestsForRepo(
1109
1109
  $fullPath: ID!
1110
1110
  $after: String
@@ -1129,19 +1129,19 @@ query getPullRequestsForRepo(
1129
1129
  hasNextPage
1130
1130
  }
1131
1131
  nodes {
1132
- ${qt(!1,!0,!0)}
1132
+ ${vt(!1,!0,!0)}
1133
1133
  }
1134
1134
  }
1135
1135
  }
1136
1136
  }
1137
- `,variables:{...p,after:r}},e),d=[],g=c.body.data?.project;if(!t&&g?.archived)return{pageInfo:null,data:[]};let m=_e(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(y=>{d.push(St(y,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.pageInfo,data:d}}async getPullRequestsForRepo(n,e={}){return this.getPullRequestsForRepoBase(n,e,!1)}async getPullRequestsForRepos(n,e={}){let{repos:t,assigneeLogins:r,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=n;return{data:(await Promise.all(t.map(c=>this.getPullRequestsForRepoBase({repo:c,assigneeLogins:r,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,n.includeFromArchivedRepos??!1)))).flatMap(c=>c.data)}}async closePullRequest(n,e={}){let{pullRequest:t}=n,r=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
1137
+ `,variables:{...p,after:r}},e),d=[],g=c.body.data?.project;if(!t&&g?.archived)return{pageInfo:null,data:[]};let m=_e(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(y=>{d.push(Et(y,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.pageInfo,data:d}}async getPullRequestsForRepo(n,e={}){return this.getPullRequestsForRepoBase(n,e,!1)}async getPullRequestsForRepos(n,e={}){let{repos:t,assigneeLogins:r,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=n;return{data:(await Promise.all(t.map(c=>this.getPullRequestsForRepoBase({repo:c,assigneeLogins:r,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,n.includeFromArchivedRepos??!1)))).flatMap(c=>c.data)}}async closePullRequest(n,e={}){let{pullRequest:t}=n,r=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
1138
1138
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
1139
1139
  errors,
1140
1140
  mergeRequest {
1141
1141
  id
1142
1142
  }
1143
1143
  }
1144
- }`,i=(await w(this.config,{query:r,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:r}=n;if(!t.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
1144
+ }`,i=(await q(this.config,{query:r,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(n,e={}){let{pullRequest:t,mergeStrategy:r}=n;if(!t.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
1145
1145
  $fullPath: ID!,
1146
1146
  $pullRequestId: String!,
1147
1147
  $expectedSourceSha: String!,
@@ -1158,59 +1158,59 @@ query getPullRequestsForRepo(
1158
1158
  id
1159
1159
  }
1160
1160
  }
1161
- }`,a=(await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),expectedSourceSha:t.headRef.oid,squash:r==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(n,e={}){let{pullRequest:t,milestone:r}=n;if(!t.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
1161
+ }`,a=(await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),expectedSourceSha:t.headRef.oid,squash:r==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(n,e={}){let{pullRequest:t,milestone:r}=n;if(!t.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
1162
1162
  mergeRequestSetMilestone(input: { projectPath: $fullPath, iid: $pullRequestId, milestoneId: $milestoneGraphQLId }) {
1163
1163
  errors,
1164
1164
  mergeRequest {
1165
1165
  id
1166
1166
  }
1167
1167
  }
1168
- }`,i=await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),milestoneGraphQLId:r?.graphQLId}},e),a=i.body.data?.mergeRequestSetMilestone;if(!a?.mergeRequest?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(n,e={}){let{pullRequest:t,isDraft:r}=n,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
1168
+ }`,i=await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),milestoneGraphQLId:r?.graphQLId}},e),a=i.body.data?.mergeRequestSetMilestone;if(!a?.mergeRequest?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(n,e={}){let{pullRequest:t,isDraft:r}=n,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
1169
1169
  mergeRequestSetDraft(input: { projectPath: $fullPath, iid: $pullRequestId, draft: $isDraft }) {
1170
1170
  errors,
1171
1171
  mergeRequest {
1172
1172
  id
1173
1173
  }
1174
1174
  }
1175
- }`,a=(await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),isDraft:r}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:r}=n,o=r.map(l=>{if(!l.username)throw new Error('GitLab requires reviewer "username" for this function.');return l.username}),i=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
1175
+ }`,a=(await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),isDraft:r}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(n,e={}){let{pullRequest:t,reviewers:r}=n,o=r.map(l=>{if(!l.username)throw new Error('GitLab requires reviewer "username" for this function.');return l.username}),i=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
1176
1176
  mergeRequestSetReviewers(input: { projectPath: $fullPath, iid: $pullRequestId, reviewerUsernames: $reviewerUsernames }) {
1177
1177
  errors,
1178
1178
  mergeRequest {
1179
1179
  id
1180
1180
  }
1181
1181
  }
1182
- }`,u=(await w(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUsernames:o}},e)).body.data?.mergeRequestSetReviewers;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(n,e={}){let{pullRequest:t,reviewer:r}=n;if(!r.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
1182
+ }`,u=(await q(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUsernames:o}},e)).body.data?.mergeRequestSetReviewers;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(n,e={}){let{pullRequest:t,reviewer:r}=n;if(!r.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
1183
1183
  mergeRequestReviewerRereview(input: { projectPath: $fullPath, iid: $pullRequestId, userId: $reviewerUserId }) {
1184
1184
  errors,
1185
1185
  mergeRequest {
1186
1186
  id
1187
1187
  }
1188
1188
  }
1189
- }`,a=(await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUserId:r.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(n,e={}){let{pullRequest:t,reviewers:r}=n,o=t.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=r.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:t,reviewer:a},e)))}async setPullRequestAssignees(n,e={}){let{pullRequest:t,assignees:r}=n,o=r.map(l=>{if(!l.username)throw new Error('GitLab requires assignee "username" for this function.');return l.username}),i=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
1189
+ }`,a=(await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUserId:r.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(n,e={}){let{pullRequest:t,reviewers:r}=n,o=t.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=r.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:t,reviewer:a},e)))}async setPullRequestAssignees(n,e={}){let{pullRequest:t,assignees:r}=n,o=r.map(l=>{if(!l.username)throw new Error('GitLab requires assignee "username" for this function.');return l.username}),i=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
1190
1190
  mergeRequestSetAssignees(input: { projectPath: $fullPath, iid: $pullRequestId, assigneeUsernames: $assigneeUsernames }) {
1191
1191
  errors,
1192
1192
  mergeRequest {
1193
1193
  id
1194
1194
  }
1195
1195
  }
1196
- }`,u=(await w(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),assigneeUsernames:o}},e)).body.data?.mergeRequestSetAssignees;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(n,e={}){let{pullRequest:t,labels:r}=n,o=r.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return u.graphQLId}),i=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
1196
+ }`,u=(await q(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),assigneeUsernames:o}},e)).body.data?.mergeRequestSetAssignees;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(n,e={}){let{pullRequest:t,labels:r}=n,o=r.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return u.graphQLId}),i=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
1197
1197
  mergeRequestSetLabels(input: { projectPath: $fullPath, iid: $pullRequestId, labelIds: $labelGraphQLIds }) {
1198
1198
  mergeRequest {
1199
1199
  id
1200
1200
  }
1201
1201
  }
1202
- }`;if(!(await w(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(n,e={}){let t=Vs(n),r=await w(this.config,{query:`
1202
+ }`;if(!(await q(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(n,e={}){let t=Xs(n),r=await q(this.config,{query:`
1203
1203
  query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1204
1204
  project(fullPath: $projectId) {
1205
1205
  id
1206
1206
  fullPath
1207
1207
  webUrl
1208
1208
  issue(iid: $issueNumber) {
1209
- ${wt}
1209
+ ${qt}
1210
1210
  }
1211
1211
  }
1212
1212
  }
1213
- `,variables:{issueNumber:n.number,projectId:t}},e);if(!r.body.data?.project)throw new Error(`Repository ${t} not found`);if(!r.body.data?.project?.issue)throw new Error(`Issue ${n.number} not found`);return{data:Et(r.body.data.project.issue,_e(r.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(n){let{updatedBefore:e,authorLogin:t,assigneeLogins:r,labelNames:o}=n||{},i={},a=[],u=[],l=(p,c,d)=>{a.push(`$${p}: ${d}`),u.push(`${p}: $${p}`),i[p]=c};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),r&&l("assigneeUsername",r[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(n,e={}){let{cursor:t,repo:r}=n||{},o=T(r),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(n),l={fullPath:o,...i},p=`
1213
+ `,variables:{issueNumber:n.number,projectId:t}},e);if(!r.body.data?.project)throw new Error(`Repository ${t} not found`);if(!r.body.data?.project?.issue)throw new Error(`Issue ${n.number} not found`);return{data:Ct(r.body.data.project.issue,_e(r.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(n){let{updatedBefore:e,authorLogin:t,assigneeLogins:r,labelNames:o}=n||{},i={},a=[],u=[],l=(p,c,d)=>{a.push(`$${p}: ${d}`),u.push(`${p}: $${p}`),i[p]=c};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),r&&l("assigneeUsername",r[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(n,e={}){let{cursor:t,repo:r}=n||{},o=O(r),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(n),l={fullPath:o,...i},p=`
1214
1214
  query GetIssuesFromProject(
1215
1215
  $fullPath: ID!
1216
1216
  $after: String
@@ -1230,7 +1230,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1230
1230
  ${u.length?u.join(" "):""}
1231
1231
  ) {
1232
1232
  nodes {
1233
- ${wt}
1233
+ ${qt}
1234
1234
  }
1235
1235
  pageInfo {
1236
1236
  endCursor
@@ -1238,7 +1238,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1238
1238
  }
1239
1239
  }
1240
1240
  }
1241
- }`,c=await w(this.config,{query:p,variables:{...l,after:t}},e),d=[],g=c.body.data?.project,m=_e(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(y=>{d.push(Et(y,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:d.sort((y,h)=>(y.updatedDate||y.createdDate).getTime()-(h.updatedDate||h.createdDate).getTime())}}async getIssuesForRepos(n,e={}){let{cursor:t}=n||{},r=n.repoIds.map(g=>g.toString().startsWith(ue)?g:`${ue}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(n),u={projectIds:r,...o},l=`
1241
+ }`,c=await q(this.config,{query:p,variables:{...l,after:t}},e),d=[],g=c.body.data?.project,m=_e(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(y=>{d.push(Ct(y,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:d.sort((y,h)=>(y.updatedDate||y.createdDate).getTime()-(h.updatedDate||h.createdDate).getTime())}}async getIssuesForRepos(n,e={}){let{cursor:t}=n||{},r=n.repoIds.map(g=>g.toString().startsWith(de)?g:`${de}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(n),u={projectIds:r,...o},l=`
1242
1242
  query GetIssuesFromProject(
1243
1243
  $projectIds: [ID!]
1244
1244
  $after: String
@@ -1264,24 +1264,24 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1264
1264
  ${a.length?a.join(" "):""}
1265
1265
  ) {
1266
1266
  nodes {
1267
- ${wt}
1267
+ ${qt}
1268
1268
  }
1269
1269
  }
1270
1270
  }
1271
1271
  }
1272
- }`,p=await w(this.config,{query:l,variables:{...u,after:t}},e),c=[];return(p.body.data?.projects?.nodes||[]).forEach(g=>{if(!n.includeFromArchivedRepos&&g.archived)return;let m=_e(g);(g.issues?.nodes||[]).forEach(y=>c.push(Et(y,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:p.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:c.sort((g,m)=>(g.updatedDate||g.createdDate).getTime()-(m.updatedDate||m.createdDate).getTime())}}async setIssueState(n,e={}){let{issue:t,state:r}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1272
+ }`,p=await q(this.config,{query:l,variables:{...u,after:t}},e),c=[];return(p.body.data?.projects?.nodes||[]).forEach(g=>{if(!n.includeFromArchivedRepos&&g.archived)return;let m=_e(g);(g.issues?.nodes||[]).forEach(y=>c.push(Ct(y,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:p.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:c.sort((g,m)=>(g.updatedDate||g.createdDate).getTime()-(m.updatedDate||m.createdDate).getTime())}}async setIssueState(n,e={}){let{issue:t,state:r}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
1273
1273
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1274
1274
  issue {
1275
1275
  id
1276
1276
  }
1277
1277
  }
1278
- }`;if(!(await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,status:r==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.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={}){let{issue:t,labels:r}=n;if(!t.repository)throw new Error('GitLab requires a "repository" for this function.');let o=r.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return u.graphQLId}),i=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
1278
+ }`;if(!(await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,status:r==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.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={}){let{issue:t,labels:r}=n;if(!t.repository)throw new Error('GitLab requires a "repository" for this function.');let o=r.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return u.graphQLId}),i=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
1279
1279
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, labelIds: $labelGraphQLIds }) {
1280
1280
  issue {
1281
1281
  id
1282
1282
  }
1283
1283
  }
1284
- }`;if(!(await w(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(n,e={}){let{issue:t,milestone:r}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1284
+ }`;if(!(await q(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(n,e={}){let{issue:t,milestone:r}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
1285
1285
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, milestoneId: $milestoneId }) {
1286
1286
  errors
1287
1287
  issue {
@@ -1291,14 +1291,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1291
1291
  }
1292
1292
  }
1293
1293
  }
1294
- }`,i=await w(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:r?.id??null}},e),a=i.body.data?.updateIssue;if(!a?.issue?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(n,e={}){let{issue:t,assignees:r}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=r.map(l=>l.username),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1294
+ }`,i=await q(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:r?.id??null}},e),a=i.body.data?.updateIssue;if(!a?.issue?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(n,e={}){let{issue:t,assignees:r}=n;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=r.map(l=>l.username),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
1295
1295
  issueSetAssignees(input: { projectPath: $fullPath, iid: $issueId, assigneeUsernames: $assigneeUsernames }) {
1296
1296
  errors,
1297
1297
  issue {
1298
1298
  id
1299
1299
  }
1300
1300
  }
1301
- }`,u=(await w(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,assigneeUsernames:o}},e)).body.data?.issueSetAssignees;if(!u?.issue?.id||u?.errors?.length!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(n,e={}){let{repo:{namespace:t,name:r},cursor:o}=n,i=await w(this.config,{query:`
1301
+ }`,u=(await q(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,assigneeUsernames:o}},e)).body.data?.issueSetAssignees;if(!u?.issue?.id||u?.errors?.length!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(n,e={}){let{repo:{namespace:t,name:r},cursor:o}=n,i=await q(this.config,{query:`
1302
1302
  query getLabelsForRepo(
1303
1303
  $fullPath: ID!
1304
1304
  $after: String
@@ -1309,7 +1309,7 @@ query getLabelsForRepo(
1309
1309
  webUrl
1310
1310
  milestones(after: $after) {
1311
1311
  nodes {
1312
- ${Ut}
1312
+ ${At}
1313
1313
  }
1314
1314
  pageInfo {
1315
1315
  endCursor
@@ -1318,7 +1318,7 @@ query getLabelsForRepo(
1318
1318
  }
1319
1319
  }
1320
1320
  }
1321
- `,variables:{fullPath:`${t}/${r}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>Tt(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(n,e={}){let{repo:{namespace:t,name:r},cursor:o}=n,i=await w(this.config,{query:`
1321
+ `,variables:{fullPath:`${t}/${r}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>Ot(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(n,e={}){let{repo:{namespace:t,name:r},cursor:o}=n,i=await q(this.config,{query:`
1322
1322
  query getLabelsForRepo(
1323
1323
  $fullPath: ID!
1324
1324
  $after: String
@@ -1328,7 +1328,7 @@ query getLabelsForRepo(
1328
1328
  ) {
1329
1329
  labels(after: $after) {
1330
1330
  nodes {
1331
- ${At}
1331
+ ${Gt}
1332
1332
  }
1333
1333
  pageInfo {
1334
1334
  endCursor
@@ -1337,7 +1337,7 @@ query getLabelsForRepo(
1337
1337
  }
1338
1338
  }
1339
1339
  }
1340
- `,variables:{fullPath:`${t}/${r}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Gt)??[]}}async getTreeForRepo(n,e={}){let t=T(n.repo),r=new URL(n.cursor??`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);r.searchParams.set("per_page","10000"),r.searchParams.set("recursive","true"),r.searchParams.set("pagination","keyset"),r.searchParams.set("ref",n.branch);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(Zs),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(n,e={}){let t=T(n.repo),o=(await w(this.config,{query:`
1340
+ `,variables:{fullPath:`${t}/${r}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Tt)??[]}}async getTreeForRepo(n,e={}){let t=O(n.repo),r=new URL(n.cursor??`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);r.searchParams.set("per_page","10000"),r.searchParams.set("recursive","true"),r.searchParams.set("pagination","keyset"),r.searchParams.set("ref",n.branch);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(en),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(n,e={}){let t=O(n.repo),o=(await q(this.config,{query:`
1341
1341
  query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
1342
1342
  project(fullPath: $fullPath) {
1343
1343
  id
@@ -1347,7 +1347,7 @@ query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
1347
1347
  webUrl
1348
1348
  archived
1349
1349
  mergeRequest(iid: $iid) {
1350
- ${qt(!1,!0,!0)}
1350
+ ${vt(!1,!0,!0)}
1351
1351
  sourceProject {
1352
1352
  id
1353
1353
  httpUrlToRepo
@@ -1358,15 +1358,15 @@ query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
1358
1358
  }
1359
1359
  }
1360
1360
  }
1361
- `,variables:{fullPath:t,iid:n.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=ke(o),u=i.sourceProject?ke(i.sourceProject):null;return{data:St(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getFileContents(n,e={}){let t=T(n.repo),r=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/raw`);r.searchParams.set("ref",n.ref);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(n,e={}){let t=T(n.repo),{page:r,perPage:o}=sn(n.cursor,L),i=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/merge_requests/${n.pullRequestNumber}/notes`);i.searchParams.set("page",r.toString()),i.searchParams.set("per_page",o.toString()),i.searchParams.set("sort","asc"),i.searchParams.set("order_by","created_at");let a=await this.config.request({url:i.toString(),headers:f(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,p={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestNumber},c=a.body.filter(m=>!m.system&&!m.position).map(m=>Ct(m,u,l,p)),d=!!a.headers["x-next-page"],g=d?rn({page:r+1,perPage:o}):null;return{data:c,pageInfo:{endCursor:g,hasNextPage:d}}}async getReviewsForPullRequest(n,e={}){let t=T(n.repo),r=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=f(e.token||this.config.token),a=U(this.config,e),u=encodeURIComponent(t),[l,p]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${n.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(t,n.pullRequestId,e)]),c=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let I=br(m,r,o),y=`approval-${m.id}`;return{author:I,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),d={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestId},g=p.filter(m=>m.notes.some(I=>!I.system&&!!I.position)).map(m=>{let I=m.notes.filter(E=>!E.system),h=I.filter(E=>!!E.position)[0];if(!h)return null;let q=I.filter(E=>E.id!==h.id).map(E=>Ct(E,r,o,d)),x={...Ct(h,r,o,d),diffLines:[],filename:h.position?.new_path??h.position?.old_path??"",line:h.position?.new_line??h.position?.old_line??null,startLine:h.position?.line_range?.start?.new_line??null,side:on(h.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:q};return{author:h.author?br(h.author,r,o):null,body:h.body??"",createdAt:h.created_at?new Date(h.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[x],url:""}}).filter(m=>m!==null);return{data:[...c,...g]}}async getPullRequestDiff(n,e={}){let t=T(n.repo),r=encodeURIComponent(t),o=U(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${r}/merge_requests/${n.pullRequestId}/diffs`,e)).map(an).join("")}async getMergeBase(n,e={}){let t=T(n.repo),r=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/merge_base`);r.searchParams.append("refs[]",n.base),r.searchParams.append("refs[]",n.head);let i=(await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)})).body?.id;if(!i)throw new Error("No merge base found between the specified commits.");return{data:i}}async fetchAllMergeRequestDiscussions(n,e,t){let r=U(this.config,t),o=encodeURIComponent(n);return this.fetchAllPagedGitLabREST(`${r}/projects/${o}/merge_requests/${e}/discussions`,t)}async fetchAllPagedGitLabREST(n,e){let t=f(e.token||this.config.token),r=[],o=1,i=50;for(;o<=i;){let a=new URL(n);a.searchParams.set("page",o.toString()),a.searchParams.set("per_page",L.toString());let u=await this.config.request({url:a.toString(),headers:t});r.push(...u.body);let l=u.headers["x-next-page"];if(!l)break;let p=parseInt(`${l}`,10);if(Number.isNaN(p))break;o=p}return r}async addCommentToPullRequest(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`,i=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...f(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:r})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(n,e={}){let{pullRequest:t,comment:r,path:o,line:i,side:a="RIGHT",threadId:u}=n;if(!r?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${t.repository.owner.login}/${t.repository.name}`,p=encodeURIComponent(l),c=U(this.config,e),d={...f(e.token||this.config.token),"Content-Type":"application/json"};if(u){let q=await this.config.request({method:"POST",url:`${c}/projects/${p}/merge_requests/${t.number}/discussions/${encodeURIComponent(u)}/notes`,headers:d,body:JSON.stringify({body:r})});return q.body?.id!=null?$t(t.repository.owner.login,t.repository.name,t.number,q.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let m=(await this.config.request({url:`${c}/projects/${p}/merge_requests/${t.number}`,headers:f(e.token||this.config.token)})).body?.diff_refs;if(!m?.base_sha||!m?.start_sha||!m?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let I={position_type:"text",base_sha:m.base_sha,start_sha:m.start_sha,head_sha:m.head_sha,new_path:o,old_path:o};a==="RIGHT"?I.new_line=i:I.old_line=i;let h=(await this.config.request({method:"POST",url:`${c}/projects/${p}/merge_requests/${t.number}/discussions`,headers:d,body:JSON.stringify({body:r,position:I})})).body?.notes?.[0]?.id;return h!=null?$t(t.repository.owner.login,t.repository.name,t.number,h):void 0}getNoteUrl(n,e){if(!n)throw new Error('GitLab requires "commentId" for this function.');let{namespace:t,name:r,mergeRequestIid:o,noteId:i}=un(n);return`${U(this.config,e)}/projects/${encodeURIComponent(`${t}/${r}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(n,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(n,e),headers:f(e.token||this.config.token)})}async deleteComment(n,e={}){await this.deleteNote(n.commentId,e)}async deleteInlineComment(n,e={}){await this.deleteNote(n.commentId,e)}async editNote(n,e,t){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(n,t),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(n,e={}){await this.editNote(n.commentId,n.body,e)}async editInlineComment(n,e={}){await this.editNote(n.commentId,n.body,e)}async resolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!0,e)}async unresolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!1,e)}async setReviewThreadResolved(n,e,t){if(!n.repo||n.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!n.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let r=T(n.repo),o=new URL(`${U(this.config,t)}/projects/${encodeURIComponent(r)}/merge_requests/${n.pullRequestNumber}/discussions/${encodeURIComponent(n.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:f(t.token||this.config.token)})}async approvePullRequest(n,e={}){let{pullRequest:t,comment:r}=n,o=`${t.repository.owner.login}/${t.repository.name}`,i=U(this.config,e),a=encodeURIComponent(o),u=f(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${t.number}/approve`,method:"POST",headers:u}),r&&r.trim()!==""&&await this.postMergeRequestNote(o,t.number,r,e)}async commentOnPullRequest(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;await this.postMergeRequestNote(o,t.number,r,e)}async requestPullRequestChanges(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;if(!await this.tryRequestChangesMutation(o,t.number,e)){let u=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}`,l=f(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:l})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:l})}await this.postMergeRequestNote(o,t.number,r,e)}async tryRequestChangesMutation(n,e,t){let r=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
1361
+ `,variables:{fullPath:t,iid:n.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=ke(o),u=i.sourceProject?ke(i.sourceProject):null;return{data:Et(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getFileContents(n,e={}){let t=O(n.repo),r=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(n.path)}/raw`);r.searchParams.set("ref",n.ref);let o=await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(n,e={}){let t=O(n.repo),{page:r,perPage:o}=on(n.cursor,L),i=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/merge_requests/${n.pullRequestNumber}/notes`);i.searchParams.set("page",r.toString()),i.searchParams.set("per_page",o.toString()),i.searchParams.set("sort","asc"),i.searchParams.set("order_by","created_at");let a=await this.config.request({url:i.toString(),headers:f(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,p={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestNumber},c=a.body.filter(m=>!m.system&&!m.position).map(m=>$t(m,u,l,p)),d=!!a.headers["x-next-page"],g=d?nn({page:r+1,perPage:o}):null;return{data:c,pageInfo:{endCursor:g,hasNextPage:d}}}async getReviewsForPullRequest(n,e={}){let t=O(n.repo),r=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=f(e.token||this.config.token),a=U(this.config,e),u=encodeURIComponent(t),[l,p]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${n.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(t,n.pullRequestId,e)]),c=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let I=br(m,r,o),y=`approval-${m.id}`;return{author:I,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),d={namespace:n.repo.namespace,name:n.repo.name,mergeRequestIid:n.pullRequestId},g=p.filter(m=>m.notes.some(I=>!I.system&&!!I.position)).map(m=>{let I=m.notes.filter(P=>!P.system),h=I.filter(P=>!!P.position)[0];if(!h)return null;let v=I.filter(P=>P.id!==h.id).map(P=>$t(P,r,o,d)),x={...$t(h,r,o,d),diffLines:[],filename:h.position?.new_path??h.position?.old_path??"",line:h.position?.new_line??h.position?.old_line??null,startLine:h.position?.line_range?.start?.new_line??null,side:un(h.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:v};return{author:h.author?br(h.author,r,o):null,body:h.body??"",createdAt:h.created_at?new Date(h.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[x],url:""}}).filter(m=>m!==null);return{data:[...c,...g]}}async getPullRequestDiff(n,e={}){let t=O(n.repo),r=encodeURIComponent(t),o=U(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${r}/merge_requests/${n.pullRequestId}/diffs`,e)).map(ln).join("")}async getMergeBase(n,e={}){let t=O(n.repo),r=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(t)}/repository/merge_base`);r.searchParams.append("refs[]",n.base),r.searchParams.append("refs[]",n.head);let i=(await this.config.request({url:r.toString(),headers:f(e.token||this.config.token)})).body?.id;if(!i)throw new Error("No merge base found between the specified commits.");return{data:i}}async fetchAllMergeRequestDiscussions(n,e,t){let r=U(this.config,t),o=encodeURIComponent(n);return this.fetchAllPagedGitLabREST(`${r}/projects/${o}/merge_requests/${e}/discussions`,t)}async fetchAllPagedGitLabREST(n,e){let t=f(e.token||this.config.token),r=[],o=1,i=50;for(;o<=i;){let a=new URL(n);a.searchParams.set("page",o.toString()),a.searchParams.set("per_page",L.toString());let u=await this.config.request({url:a.toString(),headers:t});r.push(...u.body);let l=u.headers["x-next-page"];if(!l)break;let p=parseInt(`${l}`,10);if(Number.isNaN(p))break;o=p}return r}async addCommentToPullRequest(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`,i=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...f(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:r})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(n,e={}){let{pullRequest:t,comment:r,path:o,line:i,side:a="RIGHT",threadId:u}=n;if(!r?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${t.repository.owner.login}/${t.repository.name}`,p=encodeURIComponent(l),c=U(this.config,e),d={...f(e.token||this.config.token),"Content-Type":"application/json"};if(u){let v=await this.config.request({method:"POST",url:`${c}/projects/${p}/merge_requests/${t.number}/discussions/${encodeURIComponent(u)}/notes`,headers:d,body:JSON.stringify({body:r})});return v.body?.id!=null?Lt(t.repository.owner.login,t.repository.name,t.number,v.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let m=(await this.config.request({url:`${c}/projects/${p}/merge_requests/${t.number}`,headers:f(e.token||this.config.token)})).body?.diff_refs;if(!m?.base_sha||!m?.start_sha||!m?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let I={position_type:"text",base_sha:m.base_sha,start_sha:m.start_sha,head_sha:m.head_sha,new_path:o,old_path:o};a==="RIGHT"?I.new_line=i:I.old_line=i;let h=(await this.config.request({method:"POST",url:`${c}/projects/${p}/merge_requests/${t.number}/discussions`,headers:d,body:JSON.stringify({body:r,position:I})})).body?.notes?.[0]?.id;return h!=null?Lt(t.repository.owner.login,t.repository.name,t.number,h):void 0}getNoteUrl(n,e){if(!n)throw new Error('GitLab requires "commentId" for this function.');let{namespace:t,name:r,mergeRequestIid:o,noteId:i}=pn(n);return`${U(this.config,e)}/projects/${encodeURIComponent(`${t}/${r}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(n,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(n,e),headers:f(e.token||this.config.token)})}async deleteComment(n,e={}){await this.deleteNote(n.commentId,e)}async deleteInlineComment(n,e={}){await this.deleteNote(n.commentId,e)}async editNote(n,e,t){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(n,t),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(n,e={}){await this.editNote(n.commentId,n.body,e)}async editInlineComment(n,e={}){await this.editNote(n.commentId,n.body,e)}async resolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!0,e)}async unresolveReviewThread(n,e={}){await this.setReviewThreadResolved(n,!1,e)}async setReviewThreadResolved(n,e,t){if(!n.repo||n.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!n.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let r=O(n.repo),o=new URL(`${U(this.config,t)}/projects/${encodeURIComponent(r)}/merge_requests/${n.pullRequestNumber}/discussions/${encodeURIComponent(n.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:f(t.token||this.config.token)})}async approvePullRequest(n,e={}){let{pullRequest:t,comment:r}=n,o=`${t.repository.owner.login}/${t.repository.name}`,i=U(this.config,e),a=encodeURIComponent(o),u=f(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${t.number}/approve`,method:"POST",headers:u}),r&&r.trim()!==""&&await this.postMergeRequestNote(o,t.number,r,e)}async commentOnPullRequest(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;await this.postMergeRequestNote(o,t.number,r,e)}async requestPullRequestChanges(n,e={}){let{pullRequest:t,comment:r}=n;if(!r||r.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;if(!await this.tryRequestChangesMutation(o,t.number,e)){let u=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}`,l=f(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:l})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:l})}await this.postMergeRequestNote(o,t.number,r,e)}async tryRequestChangesMutation(n,e,t){let r=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
1362
1362
  mergeRequestRequestChanges(input: { projectPath: $fullPath, iid: $pullRequestId }) {
1363
1363
  errors
1364
1364
  mergeRequest {
1365
1365
  id
1366
1366
  }
1367
1367
  }
1368
- }`,o=await w(this.config,{query:r,variables:{fullPath:n,pullRequestId:e.toString()}},t),i=o.body.errors;if(i?.length){if(i.some(Ks))return!1;throw new Error(`Could not request pull request changes: ${Ie(i)}`)}let a=o.body.data?.mergeRequestRequestChanges;if(a?.errors&&a.errors.length>0)throw new Error(`Could not request pull request changes: ${a.errors.join(", ")}`);if(!a?.mergeRequest?.id)throw new Error("Could not request pull request changes");return!0}async postMergeRequestNote(n,e,t,r){let o=U(this.config,r),i=encodeURIComponent(n),a=f(r.token||this.config.token);await this.config.request({url:`${o}/projects/${i}/merge_requests/${e}/notes`,method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({body:t})})}};var ln="https://api.atlassian.com/ex/jira",Fe=100,Ot=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],wr="/rest/api/2/search/jql",qr="/rest/api/2/search",xt=(s,n,e,t)=>{let r=s.fields.assignee,o=!t,i=(s.fields[n?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:s.id,commentCount:s.fields.comment.comments.length,number:s.key,title:s.fields.summary,url:e?`${e}/browse/${s.key}`:null,closedDate:null,createdDate:new Date(s.fields.created),author:je(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:r?[je(r,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:t??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:mn(s.fields.status),statusTransitions:s.transitions?.map(pn)??[],components:s.fields.components?.map(dn)??[],type:s.fields.issuetype.name,upvoteCount:s.fields.votes?.votes||0,labels:s.fields.labels?.map(a=>({color:null,description:null,id:null,name:a}))??[],sprints:i.map(gn),fixVersions:s.fields.fixVersions.map(hn)}},pn=s=>{let n;switch(s.to.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:n}}},dn=s=>({description:s.description??null,id:s.id,name:s.name}),cn=(s,n,e)=>e&&s.name?`${n}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${n}/jira/people/${s.accountId}`,je=(s,n,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:cn(s,n,e)}),mn=s=>{let n;switch(s.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:n}},gn=s=>({id:s.id.toString(),name:s.name,isActive:s.state==="active",startDate:s.startDate?new Date(s.startDate):null,endDate:s.endDate?new Date(s.endDate):null,completedDate:s.completeDate?new Date(s.completeDate):null}),hn=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),Z=(s,n,e)=>e?`${n.baseUrl||ln}/${e}`:`${n?.baseUrl||s.baseUrl}`,Qe=async(s,n,e={})=>{let{resourceId:t}=n;return(await s.request({url:`${Z(s,e,t)}/rest/api/2/field`,headers:f(e.token||s.token)})).body},Be=async(s,n,e,t={})=>{let{number:r,resourceId:o,fields:i}=n||{},a=await s.request({url:`${Z(s,t,o)}/rest/api/2/issue/${r}?fields=${Ot.join(",")}&expand=transitions`,headers:f(t.token||s.token)});return{data:xt(a.body,i,e,o)}},Me=async(s,n,e,t={})=>{let{cursor:r,resourceId:o,labelNames:i,fields:a}=n||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1369
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(h=>u.push(`labels = "${h}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,c=p?qr:wr,d=new URL(`${Z(s,t,o)}${c}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",Fe.toString()),d.searchParams.set("fields",Ot.join(",")),d.searchParams.set("expand","transitions"),r&&(p?d.searchParams.set("startAt",r):d.searchParams.set("nextPageToken",r));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>xt(h,a,e,o)),I=!1,y="";return p?(I=m.length==Fe,y=(parseInt(r??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},vr=async(s,n,e,t={})=>{let{cursor:r,resourceId:o,jql:i,fields:a}=n||{},u=[...Ot],l=a?.Sprint;l&&u.push(l);let p=!o,c=p?qr:wr,d=new URL(`${Z(s,t,o)}${c}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",Fe.toString()),d.searchParams.set("fields",u.join(",")),d.searchParams.set("expand","transitions"),r&&(p?d.searchParams.set("startAt",r):d.searchParams.set("nextPageToken",r));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>xt(h,a,e,o)),I=!1,y="";return p?(I=m.length==Fe,y=(parseInt(r??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},ze=async(s,n,e,t={})=>{let{assigneeLogins:r,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:c}=n||{},d=[`project = "${l}"`,"statusCategory != Done"];return o&&d.push(`creator in ("${o}")`),r&&r.length!==0&&d.push(`assignee in ("${r.join('", "')}")`),i&&d.push(`comment ~ "${i}"`),a&&a.forEach(g=>d.push(`labels = "${g}"`)),vr(s,{resourceId:p,jql:d,cursor:u,fields:c},e,t)},He=async(s,n,e,t={})=>{let{assigneeLogins:r,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:c}=n||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),r&&r.length!==0&&g.push(`assignee in ("${r.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),vr(s,{resourceId:p,jql:g,fields:c,cursor:u},e,t)},We=async(s,n,e={})=>{let{issue:t,labels:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:r.map(i=>i.name)}};await s.request({method:"PUT",url:`${Z(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},Je=async(s,n,e={})=>{let{issue:t,components:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:r.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${Z(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},Ve=async(s,n,e={})=>{let{issue:t,status:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!r.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:r.id}};await s.request({method:"POST",url:`${Z(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},Ke=async(s,n,e={})=>{let{resourceId:t,projectIdOrKey:r}=n,o=new URL(`${Z(s,e,t)}/rest/api/2/project/${r}/components`);return{data:(await s.request({url:o.toString(),headers:f(e.token||s.token)})).body}};var be="https://api.atlassian.com/ex/jira",_t=100,pe=class extends N{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let r=await Qe(this.config,e,t);this._issueFieldsCache[e.resourceId]=r.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let r=t.token||this.config.token;if(!r)return null;let o=this._resourceUrlCache[r];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[r]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let r=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||be}/${e.resourceId}/rest/api/2/myself`,headers:f(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:r?`${r}/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:f(e.token||this.config.token)}),r=e.token||this.config.token,o=r?this._resourceUrlCache[r]||{}:void 0,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return r&&(this._resourceUrlCache[r]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let r=new URL(`${t.baseUrl||be}/${e.resourceId}/rest/api/2/project/search`);r.searchParams.set("maxResults",_t.toString()),e.cursor&&r.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:r.toString(),headers:f(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(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let r=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Jt(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{r=r.concat(...i)})}),{data:r}}async getAccountsForJiraProject(e,t={}){let{resourceId:r,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:r},t),u=new URL(`${t.baseUrl||be}/${r}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",_t.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>je(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await Ke(this.config,e,t)}async getIssue(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Be(this.config,{...e,fields:r},o,t)}async getIssuesForProject(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await ze(this.config,{...e,fields:r},o,t)}async getIssuesForProjects(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await He(this.config,{...e,fields:r},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Me(this.config,{...e,fields:r},o,t)}async setIssueStatus(e,t={}){await Ve(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:r,assignee:o}=e;if(!r.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!r.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${t.baseUrl||be}/${r.project.resourceId}/rest/api/2/issue/${r.id}/assignee`,body:JSON.stringify(i),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await Je(this.config,e,t)}async setIssueLabels(e,t={}){await We(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:r,cursor:o}=e,i=new URL(`${t.baseUrl||be}/${r}/rest/api/2/label`);i.searchParams.set("maxResults",_t.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var de=class extends _{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let r=await Qe(this.config,{},e);this._issueFieldsCache[t]=r.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:f(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?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:f(e?.token||this.config.token)})).body.map(r=>({id:r.id,name:r.name}))}}async getIssue(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Be(this.config,{...e,fields:o},r,t)}async getIssuesForProject(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await ze(this.config,{...e,fields:o},r,t)}async getIssuesForProjects(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await He(this.config,{...e,fields:o},r,t)}async getIssuesForResourceForCurrentUser(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Me(this.config,{...e,fields:o},r,t)}async setIssueStatus(e,t={}){await Ve(this.config,e,t)}async setIssueLabels(e,t={}){await We(this.config,e,t)}async setIssueComponents(e,t={}){await Je(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:f(e.token||this.config.token)})).body.results.map(({displayName:r})=>({color:null,description:null,id:null,name:r}))}}async getComponentsForJiraProject(e,t={}){return await Ke(this.config,e,t)}};var M="https://api.trello.com",fn=1e3,z=(s,n)=>({...f(n),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${n}"`}),Rn=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),In=(s,n)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:n[s.idList??""]?{id:s.idList,name:n[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},ce=class extends N{async getCurrentUser(n,e={}){let t=await this.config.request({url:`${e.baseUrl||M}/1/members/me`,headers:z(n.appKey,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||M}/1/members/me/boards?fields=name&filter=open`,headers:z(n.appKey,e.token||this.config.token)})).body.map(r=>({id:r.id,name:r.name}))}}async getListsForTrelloBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/lists`,headers:z(t,e.token||this.config.token)})).body}}async getAccountForId(n,e={}){let{appKey:t,memberId:r}=n,o=await this.config.request({url:`${e.baseUrl||M}/1/members/${r}`,headers:z(t,e.token||this.config.token)});return{data:Rn(o.body)}}async getAccountsForTrelloBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/members`,headers:z(t,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(n,e={}){let t=["-is:archived","sort:edited"],{appKey:r,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=n||{};a&&t.push("@me"),u&&u.forEach(d=>t.push(`label:"${d}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/search?query=${p}&cards_limit=${fn}&card_members=true`,headers:z(r,e.token||this.config.token)})).body.cards.map(d=>In(d,l||{}))}}async updateIssue(n,e,t,r){return await this.config.request({method:"PUT",url:`${r.baseUrl||M}/1/cards/${e.id}?${t}`,headers:z(n,r.token||this.config.token)})}async setIssueStatus(n,e={}){let{appKey:t,issue:r,status:o}=n;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,r,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(n,e={}){let{appKey:t,issue:r,assignees:o}=n,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,r,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(n,e={}){let{appKey:t,issue:r,labels:o}=n,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${r.id}?idLabels=${encodeURIComponent(i)}`,headers:z(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(n,e={}){let{appKey:t,issue:r,archived:o}=n;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||M}/1/cards/${r.id}?closed=${o}`,headers:z(t,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:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||M}/1/boards/${r}/labels`,headers:z(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var Nt=100,Xe=class{constructor(){this.set=new Set;this.arr=[]}push(...n){let e=n.filter(t=>!this.set.has(t.id));this.arr.push(...e),e.forEach(t=>this.set.add(t.id))}get length(){return this.arr.length}get items(){return this.arr}},V=async(s,n,e,t)=>{let r=n.token||s.token;if(!r)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:r,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:t})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},kt=s=>s?s instanceof Date?s:new Date(s):null,bn=`
1368
+ }`,o=await q(this.config,{query:r,variables:{fullPath:n,pullRequestId:e.toString()}},t),i=o.body.errors;if(i?.length){if(i.some(Zs))return!1;throw new Error(`Could not request pull request changes: ${ye(i)}`)}let a=o.body.data?.mergeRequestRequestChanges;if(a?.errors&&a.errors.length>0)throw new Error(`Could not request pull request changes: ${a.errors.join(", ")}`);if(!a?.mergeRequest?.id)throw new Error("Could not request pull request changes");return!0}async postMergeRequestNote(n,e,t,r){let o=U(this.config,r),i=encodeURIComponent(n),a=f(r.token||this.config.token);await this.config.request({url:`${o}/projects/${i}/merge_requests/${e}/notes`,method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({body:t})})}};var dn="https://api.atlassian.com/ex/jira",Fe=100,xt=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],wr="/rest/api/2/search/jql",qr="/rest/api/2/search",_t=(s,n,e,t)=>{let r=s.fields.assignee,o=!t,i=(s.fields[n?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:s.id,commentCount:s.fields.comment.comments.length,number:s.key,title:s.fields.summary,url:e?`${e}/browse/${s.key}`:null,closedDate:null,createdDate:new Date(s.fields.created),author:je(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:r?[je(r,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:t??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:hn(s.fields.status),statusTransitions:s.transitions?.map(cn)??[],components:s.fields.components?.map(mn)??[],type:s.fields.issuetype.name,upvoteCount:s.fields.votes?.votes||0,labels:s.fields.labels?.map(a=>({color:null,description:null,id:null,name:a}))??[],sprints:i.map(fn),fixVersions:s.fields.fixVersions.map(Rn)}},cn=s=>{let n;switch(s.to.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:n}}},mn=s=>({description:s.description??null,id:s.id,name:s.name}),gn=(s,n,e)=>e&&s.name?`${n}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${n}/jira/people/${s.accountId}`,je=(s,n,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:gn(s,n,e)}),hn=s=>{let n;switch(s.statusCategory.name){case"To Do":n="TO_DO";break;case"In Progress":n="IN_PROGRESS";break;default:n="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:n}},fn=s=>({id:s.id.toString(),name:s.name,isActive:s.state==="active",startDate:s.startDate?new Date(s.startDate):null,endDate:s.endDate?new Date(s.endDate):null,completedDate:s.completeDate?new Date(s.completeDate):null}),Rn=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),X=(s,n,e)=>e?`${n.baseUrl||dn}/${e}`:`${n?.baseUrl||s.baseUrl}`,Qe=async(s,n,e={})=>{let{resourceId:t}=n;return(await s.request({url:`${X(s,e,t)}/rest/api/2/field`,headers:f(e.token||s.token)})).body},Be=async(s,n,e,t={})=>{let{number:r,resourceId:o,fields:i}=n||{},a=await s.request({url:`${X(s,t,o)}/rest/api/2/issue/${r}?fields=${xt.join(",")}&expand=transitions`,headers:f(t.token||s.token)});return{data:_t(a.body,i,e,o)}},Me=async(s,n,e,t={})=>{let{cursor:r,resourceId:o,labelNames:i,fields:a}=n||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1369
+ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(h=>u.push(`labels = "${h}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,c=p?qr:wr,d=new URL(`${X(s,t,o)}${c}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",Fe.toString()),d.searchParams.set("fields",xt.join(",")),d.searchParams.set("expand","transitions"),r&&(p?d.searchParams.set("startAt",r):d.searchParams.set("nextPageToken",r));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>_t(h,a,e,o)),I=!1,y="";return p?(I=m.length==Fe,y=(parseInt(r??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},vr=async(s,n,e,t={})=>{let{cursor:r,resourceId:o,jql:i,fields:a}=n||{},u=[...xt],l=a?.Sprint;l&&u.push(l);let p=!o,c=p?qr:wr,d=new URL(`${X(s,t,o)}${c}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",Fe.toString()),d.searchParams.set("fields",u.join(",")),d.searchParams.set("expand","transitions"),r&&(p?d.searchParams.set("startAt",r):d.searchParams.set("nextPageToken",r));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>_t(h,a,e,o)),I=!1,y="";return p?(I=m.length==Fe,y=(parseInt(r??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},ze=async(s,n,e,t={})=>{let{assigneeLogins:r,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:c}=n||{},d=[`project = "${l}"`,"statusCategory != Done"];return o&&d.push(`creator in ("${o}")`),r&&r.length!==0&&d.push(`assignee in ("${r.join('", "')}")`),i&&d.push(`comment ~ "${i}"`),a&&a.forEach(g=>d.push(`labels = "${g}"`)),vr(s,{resourceId:p,jql:d,cursor:u,fields:c},e,t)},He=async(s,n,e,t={})=>{let{assigneeLogins:r,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:c}=n||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),r&&r.length!==0&&g.push(`assignee in ("${r.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),vr(s,{resourceId:p,jql:g,fields:c,cursor:u},e,t)},We=async(s,n,e={})=>{let{issue:t,labels:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:r.map(i=>i.name)}};await s.request({method:"PUT",url:`${X(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},Je=async(s,n,e={})=>{let{issue:t,components:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:r.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${X(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},Ve=async(s,n,e={})=>{let{issue:t,status:r}=n;if(!t.project)throw new Error('Jira requires a "project" for this function.');if(!r.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:r.id}};await s.request({method:"POST",url:`${X(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},Ke=async(s,n,e={})=>{let{resourceId:t,projectIdOrKey:r}=n,o=new URL(`${X(s,e,t)}/rest/api/2/project/${r}/components`);return{data:(await s.request({url:o.toString(),headers:f(e.token||s.token)})).body}};var Pe="https://api.atlassian.com/ex/jira",kt=100,me=class extends N{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let r=await Qe(this.config,e,t);this._issueFieldsCache[e.resourceId]=r.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let r=t.token||this.config.token;if(!r)return null;let o=this._resourceUrlCache[r];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[r]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let r=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||Pe}/${e.resourceId}/rest/api/2/myself`,headers:f(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:r?`${r}/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:f(e.token||this.config.token)}),r=e.token||this.config.token,o=r?this._resourceUrlCache[r]||{}:void 0,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return r&&(this._resourceUrlCache[r]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let r=new URL(`${t.baseUrl||Pe}/${e.resourceId}/rest/api/2/project/search`);r.searchParams.set("maxResults",kt.toString()),e.cursor&&r.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:r.toString(),headers:f(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(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let r=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Jt(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{r=r.concat(...i)})}),{data:r}}async getAccountsForJiraProject(e,t={}){let{resourceId:r,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:r},t),u=new URL(`${t.baseUrl||Pe}/${r}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",kt.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>je(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await Ke(this.config,e,t)}async getIssue(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Be(this.config,{...e,fields:r},o,t)}async getIssuesForProject(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await ze(this.config,{...e,fields:r},o,t)}async getIssuesForProjects(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await He(this.config,{...e,fields:r},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let r=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Me(this.config,{...e,fields:r},o,t)}async setIssueStatus(e,t={}){await Ve(this.config,e,t)}async setIssueAssignee(e,t={}){let{issue:r,assignee:o}=e;if(!r.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!r.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${t.baseUrl||Pe}/${r.project.resourceId}/rest/api/2/issue/${r.id}/assignee`,body:JSON.stringify(i),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await Je(this.config,e,t)}async setIssueLabels(e,t={}){await We(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:r,cursor:o}=e,i=new URL(`${t.baseUrl||Pe}/${r}/rest/api/2/label`);i.searchParams.set("maxResults",kt.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var ge=class extends _{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let r=await Qe(this.config,{},e);this._issueFieldsCache[t]=r.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:f(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?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:f(e?.token||this.config.token)})).body.map(r=>({id:r.id,name:r.name}))}}async getIssue(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Be(this.config,{...e,fields:o},r,t)}async getIssuesForProject(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await ze(this.config,{...e,fields:o},r,t)}async getIssuesForProjects(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await He(this.config,{...e,fields:o},r,t)}async getIssuesForResourceForCurrentUser(e,t={}){let r=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!r)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Me(this.config,{...e,fields:o},r,t)}async setIssueStatus(e,t={}){await Ve(this.config,e,t)}async setIssueLabels(e,t={}){await We(this.config,e,t)}async setIssueComponents(e,t={}){await Je(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:f(e.token||this.config.token)})).body.results.map(({displayName:r})=>({color:null,description:null,id:null,name:r}))}}async getComponentsForJiraProject(e,t={}){return await Ke(this.config,e,t)}};var B="https://api.trello.com",In=1e3,M=(s,n)=>({...f(n),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${n}"`}),bn=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),yn=(s,n)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:n[s.idList??""]?{id:s.idList,name:n[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},he=class extends N{async getCurrentUser(n,e={}){let t=await this.config.request({url:`${e.baseUrl||B}/1/members/me`,headers:M(n.appKey,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||B}/1/members/me/boards?fields=name&filter=open`,headers:M(n.appKey,e.token||this.config.token)})).body.map(r=>({id:r.id,name:r.name}))}}async getListsForTrelloBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||B}/1/boards/${r}/lists`,headers:M(t,e.token||this.config.token)})).body}}async getAccountForId(n,e={}){let{appKey:t,memberId:r}=n,o=await this.config.request({url:`${e.baseUrl||B}/1/members/${r}`,headers:M(t,e.token||this.config.token)});return{data:bn(o.body)}}async getAccountsForTrelloBoard(n,e={}){let{appKey:t,boardId:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||B}/1/boards/${r}/members`,headers:M(t,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(n,e={}){let t=["-is:archived","sort:edited"],{appKey:r,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=n||{};a&&t.push("@me"),u&&u.forEach(d=>t.push(`label:"${d}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||B}/1/search?query=${p}&cards_limit=${In}&card_members=true`,headers:M(r,e.token||this.config.token)})).body.cards.map(d=>yn(d,l||{}))}}async updateIssue(n,e,t,r){return await this.config.request({method:"PUT",url:`${r.baseUrl||B}/1/cards/${e.id}?${t}`,headers:M(n,r.token||this.config.token)})}async setIssueStatus(n,e={}){let{appKey:t,issue:r,status:o}=n;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,r,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(n,e={}){let{appKey:t,issue:r,assignees:o}=n,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,r,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(n,e={}){let{appKey:t,issue:r,labels:o}=n,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||B}/1/cards/${r.id}?idLabels=${encodeURIComponent(i)}`,headers:M(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(n,e={}){let{appKey:t,issue:r,archived:o}=n;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||B}/1/cards/${r.id}?closed=${o}`,headers:M(t,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:r}=n;return{data:(await this.config.request({url:`${e.baseUrl||B}/1/boards/${r}/labels`,headers:M(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var Ft=100,Xe=class{constructor(){this.set=new Set;this.arr=[]}push(...n){let e=n.filter(t=>!this.set.has(t.id));this.arr.push(...e),e.forEach(t=>this.set.add(t.id))}get length(){return this.arr.length}get items(){return this.arr}},J=async(s,n,e,t)=>{let r=n.token||s.token;if(!r)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:r,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:t})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},Nt=s=>s?s instanceof Date?s:new Date(s):null,Pn=`
1370
1370
  id
1371
1371
  name
1372
1372
  description
@@ -1374,11 +1374,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1374
1374
  startDate
1375
1375
  targetDate
1376
1376
  url
1377
- `,Sr=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:kt(s.startDate),targetDate:kt(s.targetDate),url:s.url}),Er=async(s,n,e)=>{let t=`
1377
+ `,Sr=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:Nt(s.startDate),targetDate:Nt(s.targetDate),url:s.url}),Er=async(s,n,e)=>{let t=`
1378
1378
  query GetProjects($first: Int!, $after: String) {
1379
1379
  projects(first: $first, after: $after) {
1380
1380
  nodes {
1381
- ${bn}
1381
+ ${Pn}
1382
1382
  }
1383
1383
  pageInfo {
1384
1384
  hasNextPage
@@ -1386,7 +1386,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1386
1386
  }
1387
1387
  }
1388
1388
  }
1389
- `;return(await V(s,n,t,{first:Nt,after:e})).projects},yn=`
1389
+ `;return(await J(s,n,t,{first:Ft,after:e})).projects},wn=`
1390
1390
  id
1391
1391
  name
1392
1392
  number
@@ -1394,11 +1394,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1394
1394
  startsAt
1395
1395
  endsAt
1396
1396
  completedAt
1397
- `,Cr=s=>({id:s.id,name:s.name??`Cycle ${s.number}`,number:s.number,description:s.description??null,startsAt:new Date(s.startsAt),endsAt:new Date(s.endsAt),completedAt:kt(s.completedAt),url:""}),$r=async(s,n,e)=>{let t=`
1397
+ `,Cr=s=>({id:s.id,name:s.name??`Cycle ${s.number}`,number:s.number,description:s.description??null,startsAt:new Date(s.startsAt),endsAt:new Date(s.endsAt),completedAt:Nt(s.completedAt),url:""}),$r=async(s,n,e)=>{let t=`
1398
1398
  query GetCycles($first: Int!, $after: String) {
1399
1399
  cycles(first: $first, after: $after) {
1400
1400
  nodes {
1401
- ${yn}
1401
+ ${wn}
1402
1402
  }
1403
1403
  pageInfo {
1404
1404
  hasNextPage
@@ -1406,7 +1406,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1406
1406
  }
1407
1407
  }
1408
1408
  }
1409
- `;return(await V(s,n,t,{first:Nt,after:e})).cycles},Pn=`
1409
+ `;return(await J(s,n,t,{first:Ft,after:e})).cycles},qn=`
1410
1410
  id
1411
1411
  name
1412
1412
  color
@@ -1415,7 +1415,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1415
1415
  query GetLabels($first: Int!, $after: String) {
1416
1416
  projectLabels(first: $first, after: $after) {
1417
1417
  nodes {
1418
- ${Pn}
1418
+ ${qn}
1419
1419
  }
1420
1420
  pageInfo {
1421
1421
  hasNextPage
@@ -1423,31 +1423,31 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1423
1423
  }
1424
1424
  }
1425
1425
  }
1426
- `;return(await V(s,n,t,{first:Nt,after:e})).projectLabels};var ye=(i=>(i[i.None=0]="None",i[i.Assignee=1]="Assignee",i[i.Creator=2]="Creator",i[i.Mention=3]="Mention",i[i.MentionInDescription=4]="MentionInDescription",i[i.MentionInComments=5]="MentionInComments",i))(ye||{});function Ur(s,n){return s?`${ye[s]}:${n||""}`:n??null}function Ar(s){if(!s)return{category:0};let[n,e]=s.split(":");return n in ye?{category:ye[n],cursor:e||void 0}:{category:0,cursor:s}}var Gr=100;function Ye(s){return s?s instanceof Date?s:new Date(s):null}var xr=`
1426
+ `;return(await J(s,n,t,{first:Ft,after:e})).projectLabels};var we=(i=>(i[i.None=0]="None",i[i.Assignee=1]="Assignee",i[i.Creator=2]="Creator",i[i.Mention=3]="Mention",i[i.MentionInDescription=4]="MentionInDescription",i[i.MentionInComments=5]="MentionInComments",i))(we||{});function Ur(s,n){return s?`${we[s]}:${n||""}`:n??null}function Ar(s){if(!s)return{category:0};let[n,e]=s.split(":");return n in we?{category:we[n],cursor:e||void 0}:{category:0,cursor:s}}var Gr=100;function Ye(s){return s?s instanceof Date?s:new Date(s):null}var xr=`
1427
1427
  id
1428
1428
  name
1429
1429
  key
1430
1430
  icon
1431
- `;function wn(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var Tr=`
1431
+ `;function vn(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var Tr=`
1432
1432
  id
1433
1433
  name
1434
1434
  avatarUrl
1435
- `;function Or(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var qn=`
1435
+ `;function Or(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var Sn=`
1436
1436
  id
1437
1437
  name
1438
- `;function vn(s,n){if(s)return{id:s.id,name:s.name,key:n?.key||null,namespace:null,resourceId:n?.id||null}}var Sn=`
1438
+ `;function En(s,n){if(s)return{id:s.id,name:s.name,key:n?.key||null,namespace:null,resourceId:n?.id||null}}var Cn=`
1439
1439
  id
1440
1440
  sortOrder
1441
1441
  name
1442
1442
  description
1443
1443
  status
1444
1444
  targetDate
1445
- `;function En(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:Ye(s.targetDate)}:null}function Cn(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var $n=`
1445
+ `;function $n(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:Ye(s.targetDate)}:null}function Ln(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Dn=`
1446
1446
  id
1447
1447
  name
1448
1448
  color
1449
1449
  type
1450
- `;function Ln(s){return s?{id:s.id,name:s.name,color:s.color,category:Cn(s.type)}:null}var jt=`
1450
+ `;function Un(s){return s?{id:s.id,name:s.name,color:s.color,category:Ln(s.type)}:null}var Qt=`
1451
1451
  creator {
1452
1452
  ${Tr}
1453
1453
  }
@@ -1460,23 +1460,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1460
1460
  id
1461
1461
  identifier
1462
1462
  project {
1463
- ${qn}
1463
+ ${Sn}
1464
1464
  }
1465
1465
  team {
1466
1466
  ${xr}
1467
1467
  }
1468
1468
  state {
1469
- ${$n}
1469
+ ${Dn}
1470
1470
  }
1471
1471
  title
1472
1472
  updatedAt
1473
1473
  url
1474
1474
  projectMilestone {
1475
- ${Sn}
1475
+ ${Cn}
1476
1476
  }
1477
- `;async function Ft(s){return{author:Or(await s.creator),assignees:[Or(await s.assignee)].filter(n=>n!=null),commentCount:null,closedDate:Ye(s.archivedAt),createdDate:Ye(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:vn(await s.project,await s.team),state:Ln(await s.state),title:s.title,type:null,updatedDate:Ye(s.updatedAt),upvoteCount:null,url:s.url,milestone:En(await s.projectMilestone)}}var Ze=`
1477
+ `;async function jt(s){return{author:Or(await s.creator),assignees:[Or(await s.assignee)].filter(n=>n!=null),commentCount:null,closedDate:Ye(s.archivedAt),createdDate:Ye(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:En(await s.project,await s.team),state:Un(await s.state),title:s.title,type:null,updatedDate:Ye(s.updatedAt),upvoteCount:null,url:s.url,milestone:$n(await s.projectMilestone)}}var Ze=`
1478
1478
  nodes {
1479
- ${jt}
1479
+ ${Qt}
1480
1480
  }
1481
1481
  pageInfo {
1482
1482
  hasNextPage
@@ -1485,10 +1485,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1485
1485
  `,et=class extends N{async fetchIssue(n,e){let t=`
1486
1486
  query GetIssue($identifier: String!) {
1487
1487
  issue(id: $identifier) {
1488
- ${jt}
1488
+ ${Qt}
1489
1489
  }
1490
1490
  }
1491
- `;return(await V(this.config,e,t,{identifier:n})).issue}async fetchOrganization(n){let e=`
1491
+ `;return(await J(this.config,e,t,{identifier:n})).issue}async fetchOrganization(n){let e=`
1492
1492
  query GetOrganization {
1493
1493
  organization {
1494
1494
  id
@@ -1496,7 +1496,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1496
1496
  urlKey
1497
1497
  }
1498
1498
  }
1499
- `;return(await V(this.config,n,e)).organization}async fetchTeams(n){let e=`
1499
+ `;return(await J(this.config,n,e)).organization}async fetchTeams(n){let e=`
1500
1500
  query GetTeams {
1501
1501
  teams {
1502
1502
  nodes {
@@ -1504,7 +1504,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1504
1504
  }
1505
1505
  }
1506
1506
  }
1507
- `;return(await V(this.config,n,e)).teams}async rawRequest(n,e,t){return{data:await V(this.config,n,e,t)}}async fetchViewer(n){let e=`
1507
+ `;return(await J(this.config,n,e)).teams}async rawRequest(n,e,t){return{data:await J(this.config,n,e,t)}}async fetchViewer(n){let e=`
1508
1508
  query GetViewer {
1509
1509
  viewer {
1510
1510
  id
@@ -1513,7 +1513,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1513
1513
  displayName
1514
1514
  }
1515
1515
  }
1516
- `;return(await V(this.config,n,e)).viewer}async getIssue(n,e={}){let t=await this.fetchIssue(n.number,e);return{data:await Ft(t)}}async getLinearOrganization(n={}){let e=await this.fetchOrganization(n);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(n={}){return{data:(await this.fetchTeams(n)).nodes.map(wn)}}async getProjects(n={},e={}){let t=await Er(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Sr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCycles(n={},e={}){let t=await $r(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Cr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getLabels(n={},e={}){let t=await Dr(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Lr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCurrentUser(n={}){return{data:await this.fetchViewer(n)}}async getIssuesForCurrentUser(n,e={}){let{cursor:t}=n,{category:r,cursor:o}=Ar(t),i=await this.fetchViewer(e),a,u,l=new Xe,p=async(c,d)=>{if(u||r>c)return;let g=await d(Math.max(Gr-l.length,1),r===c?o:void 0);if(!g)return;let m=await ot(g.nodes.map(Ft));l.push(...m),g.pageInfo.hasNextPage&&(a=c,u=g.pageInfo.endCursor)};return await p(1,async(c,d)=>(await this.rawRequest(e,`
1516
+ `;return(await J(this.config,n,e)).viewer}async getIssue(n,e={}){let t=await this.fetchIssue(n.number,e);return{data:await jt(t)}}async getLinearOrganization(n={}){let e=await this.fetchOrganization(n);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(n={}){return{data:(await this.fetchTeams(n)).nodes.map(vn)}}async getProjects(n={},e={}){let t=await Er(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Sr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCycles(n={},e={}){let t=await $r(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Cr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getLabels(n={},e={}){let t=await Dr(this.config,e,n.cursor??void 0);return{data:t.nodes.map(Lr),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCurrentUser(n={}){return{data:await this.fetchViewer(n)}}async getIssuesForCurrentUser(n,e={}){let{cursor:t}=n,{category:r,cursor:o}=Ar(t),i=await this.fetchViewer(e),a,u,l=new Xe,p=async(c,d)=>{if(u||r>c)return;let g=await d(Math.max(Gr-l.length,1),r===c?o:void 0);if(!g)return;let m=await it(g.nodes.map(jt));l.push(...m),g.pageInfo.hasNextPage&&(a=c,u=g.pageInfo.endCursor)};return await p(1,async(c,d)=>(await this.rawRequest(e,`
1517
1517
  query GetAssignedIssues($first: Int!, $after: String) {
1518
1518
  viewer {
1519
1519
  issues: assignedIssues(first: $first, after: $after) {
@@ -1576,7 +1576,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1576
1576
  ){
1577
1577
  nodes {
1578
1578
  issue {
1579
- ${jt}
1579
+ ${Qt}
1580
1580
  }
1581
1581
  }
1582
1582
  pageInfo {
@@ -1591,4 +1591,4 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1591
1591
  ${Ze}
1592
1592
  }
1593
1593
  }
1594
- `,c=(await this.rawRequest(e,l,{first:Gr,after:i})).data?.issues;return c?{data:await ot(c.nodes.map(Ft)),pageInfo:{hasNextPage:c.pageInfo.hasNextPage,endCursor:c.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var _r=s=>{let n={request:s?.request};return{azureDevOps:new ne({...n,...s?.azureDevOps}),bitbucket:new oe({...n,...s?.bitbucket}),bitbucketServer:new ie({...n,...s?.bitbucketServer}),github:new ae({...n,...s?.github}),gitlab:new le({...n,...s?.gitlab}),jira:new pe({...n,...s?.jira}),jiraServer:new de({...n,...s?.jiraServer}),linear:new et({...n,...s?.linear}),trello:new ce({...n,...s?.trello})}};var kr=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(kr||{});var Nr=(e=>(e.Zero="0",e.One="1",e))(Nr||{}),Fr=(e=>(e.PullRequest="pr",e.Issue="issue",e))(Fr||{}),jr=(d=>(d.Azure="azure",d.AzureDevOpsServer="azureDevOpsServer",d.Github="github",d.GithubEnterprise="githubEnterprise",d.Gitlab="gitlab",d.GitlabSelfHosted="gitlabSelfHosted",d.Bitbucket="bitbucket",d.BitbucketServer="bitbucketServer",d.Jira="jira",d.JiraServer="jiraServer",d.Linear="linear",d.Trello="trello",d))(jr||{});var Qr=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(Qr||{});var Dn=_r;
1594
+ `,c=(await this.rawRequest(e,l,{first:Gr,after:i})).data?.issues;return c?{data:await it(c.nodes.map(jt)),pageInfo:{hasNextPage:c.pageInfo.hasNextPage,endCursor:c.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var _r=s=>{let n={request:s?.request};return{azureDevOps:new ae({...n,...s?.azureDevOps}),bitbucket:new ue({...n,...s?.bitbucket}),bitbucketServer:new le({...n,...s?.bitbucketServer}),github:new pe({...n,...s?.github}),gitlab:new ce({...n,...s?.gitlab}),jira:new me({...n,...s?.jira}),jiraServer:new ge({...n,...s?.jiraServer}),linear:new et({...n,...s?.linear}),trello:new he({...n,...s?.trello})}};var kr=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(kr||{});var Nr=(e=>(e.Zero="0",e.One="1",e))(Nr||{}),Fr=(e=>(e.PullRequest="pr",e.Issue="issue",e))(Fr||{}),jr=(d=>(d.Azure="azure",d.AzureDevOpsServer="azureDevOpsServer",d.Github="github",d.GithubEnterprise="githubEnterprise",d.Gitlab="gitlab",d.GitlabSelfHosted="gitlabSelfHosted",d.Bitbucket="bitbucket",d.BitbucketServer="bitbucketServer",d.Jira="jira",d.JiraServer="jiraServer",d.Linear="linear",d.Trello="trello",d))(jr||{});var Qr=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(Qr||{});var An=_r;