@gitkraken/provider-apis 0.50.0 → 0.51.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/index.js +31 -31
- package/dist/index.providers.js +22 -22
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var Ot=Object.defineProperty;var ln=Object.getOwnPropertyDescriptor;var pn=Object.getOwnPropertyNames;var dn=Object.prototype.hasOwnProperty;var H=(s,t)=>{for(var e in t)Ot(s,e,{get:t[e],enumerable:!0})},cn=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of pn(t))!dn.call(s,n)&&n!==e&&Ot(s,n,{get:()=>t[n],enumerable:!(r=ln(t,n))||r.enumerable});return s};var mn=s=>cn(Ot({},"__esModule",{value:!0}),s);var wi={};H(wi,{AzureDevOps:()=>Re,AzureDevopsUtils:()=>ht,Bitbucket:()=>Ie,BitbucketServer:()=>be,BitbucketServerUtils:()=>We,BitbucketUtils:()=>ft,EntityIdentifierProviderType:()=>N,EntityIdentifierUtils:()=>Dt,EntityType:()=>j,EntityVersion:()=>B,GitBuildStatusStage:()=>xr,GitBuildStatusState:()=>De,GitDiffLineType:()=>_t,GitHub:()=>ye,GitHubIssueCloseReason:()=>sn,GitHubUtils:()=>$t,GitIssueState:()=>ce,GitLab:()=>we,GitLabUtils:()=>Lt,GitMergeStrategy:()=>fe,GitProviderUtils:()=>At,GitPullRequestMergeableState:()=>ee,GitPullRequestReviewState:()=>V,GitPullRequestState:()=>oe,GraphQLErrors:()=>I,Jira:()=>qe,JiraServer:()=>ve,JiraUtils:()=>Ut,Linear:()=>Ee,PullRequestAsyncStatus:()=>rn,Trello:()=>Se,TrelloUtils:()=>Gt,Utils:()=>Pi,default:()=>yi,isFetch:()=>Be});module.exports=mn(wi);var Jr=require("diff");var xr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(xr||{}),De=(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))(De||{}),fe=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(fe||{}),oe=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(oe||{}),V=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(V||{}),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||{}),_t=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(_t||{});var Nr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},J=s=>!s||s.length===0?null:s.reduce((t,e)=>Nr[e.state]>Nr[t]?e.state:t,"APPROVED"),Ne=(s,t)=>s.name||s.username||s.email||t,de=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var R=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},Br=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,ie=(s,t,e)=>!s||t.some(r=>s[r])?e:"",jr=async s=>{let t=[],e=!0,r;for(;e;){let n=await s(r);t=t.concat(n.data),e=!!n?.pageInfo?.hasNextPage,r=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return t};async function kt(s){return(await Promise.allSettled(s)).map(e=>gn(e)).filter(e=>e!=null)}var L=(s,{fallback:t,max:e})=>!s||s<=0?t:e===void 0?s:Math.min(s,e),x=(s,t)=>{if(!t||t.length===0)return s;let e=new Set(t);return s.filter(r=>e.has(r.state))};function gn(s,t=void 0){return s?.status==="fulfilled"?s.value:t}async function Qr(s,t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)throw new Error("batchSize must be a positive integer");for(let r=0;r<s.length;r+=t){let n=s.slice(r,r+t);await Promise.all(n.map(e))}}var ce=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ce||{});var xt=(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))(xt||{});var $=100;var Fr=globalThis.fetch;var hn=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(t.startsWith("text/")||t===""||t.startsWith("application/vnd.github.diff")||t.startsWith("application/vnd.github.patch"))e=await s.text();else if(t.startsWith("application/vnd.github.raw+json")||t.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${t}`);let r={};s.headers.forEach((o,i)=>{r[i]=o});let n={body:e,headers:r,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},Nt=s=>async({url:t,...e})=>{let r=await s(t,e);return hn(r)};var Be=(s,t=!1)=>s.name==="fetch"||t;var M=class{constructor(t){let e=t?.request||Fr;this.config={...t,request:Be(e,t?.forceIsFetch)?Nt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&Be(t.request,t?.forceIsFetch??this.config.forceIsFetch)?Nt(t.request):this.config.request}}},Q=class extends M{};var fn="https://app.vssps.visualstudio.com/_apis",Rn="https://vssps.dev.azure.com/",In="https://dev.azure.com",q=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT),zr=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),Bt=(s,t)=>{let e=t.baseUrl||s.baseUrl||fn;return e=e.replace(/\/$/,""),e},C=(s,t)=>{let e=t.baseUrl||s.baseUrl||In;return e=e.replace(/\/$/,""),e},jt=(s,t)=>{let e=t.baseUrl||s.baseUrl||Rn;return e=e.replace(/\/$/,""),e};var bn={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},yn={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},je=100,Pn=200,wn=200,Mr=s=>{if(!s||s.length===0)return"active";let t=Array.from(new Set(s.map(e=>yn[e])));return t.length===1?t[0]:"all"},qn=s=>{if(!s||s.length===0)return["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"];let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?[]:r?["([Microsoft.VSTS.Common.ClosedDate] <> '' OR [Microsoft.VSTS.Common.ResolvedDate] <> '')"]:["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"]},vn=s=>{if(typeof s!="string")return s;let t=s.charAt(0).toUpperCase()+s.slice(1);return xt[t]??0},En=new Set([2,3,4,5]),Sn={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},me=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Qe=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Cn=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"}},Qt=(s,t,e,r,n,o)=>`${s}|${t}|${e}|${r}|${n}|${o}`,Wr=s=>{let t=s.split("|");if(t.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4],commentId:t[5]}},Hr=(s,t,e,r,n)=>`${s}|${t}|${e}|${r}|${n}`,Ft=s=>{let t=s.split("|");if(t.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4]}},Ae=(s,t,e)=>{let r=!!t.forkSource,n=[],o=[];return t.reviewers.forEach(i=>{let a={reviewer:me(i),state:Sn[i.vote??0]||"REVIEW_REQUESTED"};i.isRequired&&n.push(a),o.push(a)}),{id:t.pullRequestId.toString(),title:t.title,description:t.description??null,number:t.codeReviewId,state:bn[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:me(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,isCrossRepository:r,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null},headCommit:{buildStatuses:null},baseRef:{name:Qe(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Qe(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:zr(t),assignees:t.reviewers.map(me),reviews:o,reviewDecision:J(n),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:e?.get(t.forkSource.repository.id)??null,isFork:!0}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null,isFork:!1},mergeableState:Cn(t.mergeStatus),labels:t.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},Vr=(s,t)=>({id:t.id,name:t.name,namespace:s,project:t.project.name,projectId:t.project.id,webUrl:t.webUrl,httpsUrl:t.remoteUrl,sshUrl:t.sshUrl,defaultBranch:t.defaultBranch?{name:Qe(t.defaultBranch)}:null,permissions:null}),Dn=(s,t,e,r)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=r[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},Re=class extends Q{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,r){let n=JSON.stringify([e,r.token??null,r.isPAT??this.config.isPAT??!1,r.baseUrl??null]),o=this.cachedUserIds.get(n);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(n);if(i)return i;let a=this.fetchCurrentUserId(e,r,n);return this.inflightUserIds.set(n,a),a}async fetchCurrentUserId(e,r,n){try{let o=await this.getCurrentUserForInstance({namespace:e},r);return this.cachedUserIds.set(n,o.data.id),o.data.id}finally{this.inflightUserIds.delete(n)}}getRepoApiUrl(e,r,n,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(r)}/_apis/git/repositories/${encodeURIComponent(n)}`}async getCurrentUser(e={},r={}){if(r.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let n=`${Bt(this.config,r)}/profile/profiles/me`,o=await this.config.request({url:n,headers:q(this.config,r)});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,r={}){let o=(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:q(this.config,r)})).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,r={}){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,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:q(this.config,r)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,r={}){let n=`${Bt(this.config,r)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,r={}){let n=`${C(this.config,r)}/_apis/projectCollections`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,r={}){let n=new URL(`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/projects`);n.searchParams.set("$top",$.toString()),e.cursor&&n.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:n.toString(),headers:q(this.config,r)}),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,r={}){let{namespace:n,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${jt(this.config,r)}/${encodeURIComponent(n)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:q(this.config,r)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,r={}){let{namespace:n,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${jt(this.config,r)}/${encodeURIComponent(n)}/_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:q(this.config,r)}),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,r={}){let{azureGraphAccount:n}=e;if(!n.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:n.storageKeyURL,headers:q(this.config,r)});return{data:{avatarUrl:n.avatarUrl,email:n.email,id:o.body.value,name:n.name,username:n.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,r={}){let n=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},r);n.push(i.data)}return{data:n}}async getRepo(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:q(this.config,r)});return{data:Vr(e.namespace,n.body)}}async getRepos(e,r={}){let n=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,r);n.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:n,errors:o}}async getReposForAzureProject(e,r={}){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,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:q(this.config,r)})).body.value.map(o=>Vr(e.namespace,o))}}async getRefs(e,r,n={}){if(!r.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${C(this.config,n)}/${encodeURIComponent(r.repo.namespace)}/${encodeURIComponent(r.repo.project)}/_apis/git/repositories/${encodeURIComponent(r.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",$.toString()),r.cursor&&o.searchParams.set("continuationToken",r.cursor);let i=await this.config.request({url:o.toString(),headers:q(this.config,n)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Qe(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,r={}){return this.getRefs("heads",e,r)}async getTags(e,r={}){return this.getRefs("tags",e,r)}async fetchRemoteInfoByRepoId(e,r,n){let o=new Map;if(!e)return o;let i=new Map;for(let{namespace:a,pullRequests:u}of r)for(let l of u)i.has(l.repository.id)||i.set(l.repository.id,a),l.forkSource&&!i.has(l.forkSource.repository.id)&&i.set(l.forkSource.repository.id,a);return await Qr([...i],10,async([a,u])=>{try{let l=await this.config.request({url:`${C(this.config,n)}/${encodeURIComponent(u)}/_apis/git/repositories/${encodeURIComponent(a)}`,headers:q(this.config,n)}),{remoteUrl:p,sshUrl:d}=l.body;p&&d&&o.set(a,{cloneUrlHTTPS:p,cloneUrlSSH:d})}catch{}}),o}async getPullRequestsForRepoBase(e,r={},n=je){let{page:o,repo:i,assigneeLogins:a,authorLogin:u,reviewerId:l}=e||{},p=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let d=L(e.pageSize,{fallback:n}),c=l??(a&&a.length?a[0]:void 0),g=`searchCriteria.status=${Mr(e.states)}`;return c&&(g+=`&searchCriteria.reviewerId=${encodeURIComponent(c)}`),u&&(g+=`&searchCriteria.creatorId=${encodeURIComponent(u)}`),await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${g}&%24top=${d}&%24skip=${(p-1)*d}`,headers:q(this.config,r)})}async getPullRequestsForRepo(e,r={}){let n=L(e.pageSize,{fallback:je}),o=e.page||1,i=await this.getPullRequestsForRepoBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:e.repo.namespace,pullRequests:i.body.value}],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i.body.value.map(l=>Ae(e.repo.namespace,l,u)),e.states)}}async getPullRequestsForRepos(e,r={}){if(!e.repos.every(u=>u.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:n}=e||{},o=[];await Promise.all(n.map(async u=>{try{let l=await this.getPullRequestsForRepoBase({repo:u,...e},r);o.push({namespace:u.namespace,pullRequests:l.body.value})}catch(l){if(l.statusCode!==404&&l.statusCode!==401)throw l}}));let i=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,o,r),a=o.flatMap(({namespace:u,pullRequests:l})=>l.map(p=>Ae(u,p,i)));return{data:x(a,e.states)}}async getPullRequestsForProjectBase(e,r={},n=je){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,reviewerId:p,repo:d}=e;if(d?.project&&d.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,g=L(e.pageSize,{fallback:n}),m=p??(u&&u.length?u[0]:void 0),h=new URL(`${C(this.config,r)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",Mr(e.states)),h.searchParams.set("$top",g.toString()),h.searchParams.set("$skip",((c-1)*g).toString()),d?.id&&d?.project===i&&h.searchParams.set("searchCriteria.repositoryId",d.id),m&&h.searchParams.set("searchCriteria.reviewerId",m),l&&h.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:h.toString(),headers:q(this.config,r)})}async getPullRequestsForProject(e,r={}){let n=L(e.pageSize,{fallback:je}),o=e.page||1,i=await this.getPullRequestsForProjectBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,i?[{namespace:e.namespace,pullRequests:i.body.value}]:[],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i?.body.value.map(l=>Ae(e.namespace,l,u))||[],e.states)}}async getPullRequestsForProjects(e,r={}){let{projects:n}=e||{},o=[];await Promise.all(n.map(async u=>{try{if(!e.repo||e.repo.project&&e.repo.project===u.project){let l=await this.getPullRequestsForProjectBase({...u,...e},r);l&&o.push({namespace:u.namespace,pullRequests:l.body.value})}}catch(l){if(l.statusCode!==404&&l.statusCode!==401)throw l}}));let i=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,o,r),a=o.flatMap(({namespace:u,pullRequests:l})=>l.map(p=>Ae(u,p,i)));return{data:x(a,e.states)}}async getAzurePullRequestLastMergeStatus(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:n,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...q(this.config,r)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,r,n){return await this.config.request({method:"PATCH",url:`${C(this.config,n)}/${encodeURIComponent(e.repository.owner.login)}/${encodeURIComponent(e.repository.project)}/_apis/git/repositories/${e.repository.name}/pullrequests/${e.id}?api-version=6.0`,body:r,headers:{...q(this.config,n),"Content-Type":"application/json"}})}async closePullRequest(e,r={}){let{pullRequest:n}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(n,JSON.stringify(o),r)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,r={}){let{pullRequest:n,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:n.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(n,JSON.stringify(a),r)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.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,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.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,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...q(this.config,r)}})}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=n.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:n,label:a},r);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:n,label:a},r)}async setPullRequestAsDraft(e,r={}){let{pullRequest:n,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(n,JSON.stringify(i),r)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,headers:{...q(this.config,r),Accept:"application/json"}})}async setPullRequestReviewers(e,r={}){let{pullRequest:n,reviewers:o}=e;for(let i of o)n.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:n,reviewer:i,isRequired:!0},r);for(let i of n.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:n,reviewer:i},r)}async getIssuesForAzureProject(e,r={}){let{page:n,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=n||1,d=Math.min(L(e.pageSize,{fallback:Pn}),wn),c=["[System.TeamProject] = @project",...qn(e.states)];i&&c.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&c.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&c.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(A=>c.push(`[System.Tags] Contains '${A}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${c.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}}),h=m.body.workItems.slice((p-1)*d,d*p).map(A=>A.id),y=m.body.workItems.length,f=Math.ceil(y/d),P=y>d*p;if(h.length===0)return{pageInfo:{hasNextPage:!1,nextPage:null,currentPage:p,totalCount:y,totalPages:f},data:[]};let v=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:h,$expand:"Links"}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?p+1:null,currentPage:p,totalCount:y,totalPages:f},data:v.body.value.map(A=>Dn(e.namespace,e.project,A,l||{}))}}async getPermissionsForRepos(e,r={}){let{namespace:n,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=d=>{let c="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${d.projectId}/${d.id}`;return Object.keys(i).map(m=>({securityNamespaceId:c,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,r)}/${encodeURIComponent(n)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.evaluations.reduce((d,c)=>{let[,g,m]=c.token.split("/"),h=`${g}/${m}`,y=i[c.permissions];for(let f of y)d[h]===void 0&&(d[h]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),c.value===!1&&(d[h][f]=!1);return d},{})}}async decorateReposWithPermissions(e,r={}){let{namespace:n,repos:o}=e,i=await this.getPermissionsForRepos({namespace:n,repos:o},r);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,r,n={}){return await this.config.request({method:"PATCH",url:`${C(this.config,n)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(r),headers:{...q(this.config,n),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,r={}){let{issue:n,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,r={}){let{issue:n,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(n,a,r)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...q(this.config,r)}})).body.value}}async getLabelsForProject(e,r={}){let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...q(this.config,r)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:n.namespace,pullRequests:[i.body]}],r);return{data:Ae(n.namespace,i.body,a)}}async getPullRequestDescription(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');try{return{data:{description:(await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,r={}){let{repo:n,number:o,description:i}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:{description:(await this.config.request({method:"PATCH",url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:{...q(this.config,r),"Content-Type":"application/json"},body:JSON.stringify({description:i})})).body?.description??i}}}async getMergeBase(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:q(this.config,r)});if(!n.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:n.body.value[0].commitId}}async getFileContents(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...q(this.config,r),Accept:"application/octet-stream"}});return{data:new Blob([n.body])}}async getPullRequestDiff(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${n}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,p=a.body.lastMergeSourceCommit.commitId,d=u.body.value;if(d.length===0)return"";let c=d[d.length-1],g=1e3,m=[],h=0;for(;;){let S=(await this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations/${c.id}/changes?api-version=7.1&$top=${g}&$skip=${h}`,headers:o})).body.changeEntries??[];if(S.length===0||(m.push(...S),S.length<g))break;h+=S.length}if(m.length===0)return"";let y=5,f=[],P=new TextDecoder,v=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",A=async(w,S)=>{try{let le=await this.config.request({url:`${n}/items?path=${encodeURIComponent(w)}&versionDescriptor[version]=${encodeURIComponent(S)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return v(le.body)}catch{return""}},D=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let S=w.toLowerCase().split(",").map(le=>le.trim());return{add:S.includes("add"),rename:S.includes("rename"),delete:S.includes("delete")}};for(let w=0;w<m.length;w+=y){let S=m.slice(w,w+y),le=await Promise.all(S.map(async ge=>{let{add:he,rename:Tt,delete:pe}=D(ge.changeType),Ce=ge.originalPath??ge.item.originalPath,T=ge.item.path,xe=pe?T??Ce??"":T??"",kr=Tt||pe?Ce??xe:xe,[nn,on]=await Promise.all([he?Promise.resolve(""):A(kr,l),pe?Promise.resolve(""):A(xe,p)]),an=he?"/dev/null":`a${kr}`,un=pe?"/dev/null":`b${xe}`;return(0,Jr.createTwoFilesPatch)(an,un,nn,on)}));f.push(...le)}return f.join(`
|
|
2
|
-
`)}getPullRequestWriteHeaders(e){return{...q(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,r,n,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${r}/reviewers/${encodeURIComponent(n)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,r,n,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${r}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:n,commentType:1}],status:1})})}async getCommentsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i=await this.config.request({url:`${n}/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:Qt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?me(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,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async addInlineCommentToPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r),o=this.getPullRequestWriteHeaders(r);if(e.threadId){let p=Ft(e.threadId),d=e.pullRequest.repository.owner.login,c=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(p.namespace!==d||p.project!==c||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 ${d}/${c}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${n}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}?api-version=7.1`,headers:q(this.config,r)})).body.comments?.find(P=>P.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${p.threadId}.`);let f=await this.config.request({method:"POST",url:`${n}/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 Qt(d,c,g,Number(m),Number(p.threadId),f.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:`${n}/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 Hr(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,r={}){let n=Wr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({content:e.body})})}async editInlineComment(e,r={}){return this.editComment(e,r)}async deleteComment(e,r={}){let n=Wr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:q(this.config,r)})}async deleteInlineComment(e,r={}){return this.deleteComment(e,r)}async resolveReviewThread(e,r={}){let n=Ft(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,r={}){let n=Ft(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:1})})}async approvePullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,r),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,r):null])}async requestPullRequestChanges(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,r),await this.setReviewerVote(o,e.pullRequest.id,i,-5,r)}async commentOnPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async getReviewsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(n,o,i,r),l=q(this.config,r),[p,d]=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})]),c=(f,P)=>Qt(n,o,i,a,f,P),g=f=>Hr(n,o,i,a,f),m=new Map;for(let f of d.body.value){if(f.isDeleted)continue;let P=f.comments.filter(T=>!T.isDeleted&&T.commentType!=="system"),v=P.find(T=>T.parentCommentId===0)??P[0];if(!v)continue;let A=v.author?.id;if(!A)continue;let D=P.filter(T=>T.id!==v.id),w=f.threadContext,S=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,le=S?.end?.line??S?.start.line??null,ge=S?.start&&S.end&&S.start.line!==S.end.line?S.start.line:null,he=w?.filePath??"",Tt=he.startsWith("/")?he.slice(1):he,pe={id:c(f.id,v.id),author:v.author?me(v.author):null,body:v.content??"",createdAt:v.publishedDate?new Date(v.publishedDate):null,url:"",diffLines:[],filename:Tt,replies:D.map(T=>({id:c(f.id,T.id),author:T.author?me(T.author):null,body:T.content??"",createdAt:T.publishedDate?new Date(T.publishedDate):null,url:""})),isOutdated:!1,isResolved:En.has(vn(f.status)),line:le,startLine:ge,side:S?.side??null,threadId:g(f.id)},Ce=m.get(A);Ce?Ce.push(pe):m.set(A,[pe])}let h=[],y=new Set;for(let f of p.body.value){if(f.hasDeclined)continue;let P=f.vote??0,v=m.get(f.id);P===0&&!v?.length||(h.push({id:f.id,author:me(f),body:"",createdAt:null,url:"",reviewComments:v??[]}),y.add(f.id))}for(let[f,P]of m){if(y.has(f)||!P.length)continue;let v=P[0].author;v&&h.push({id:f,author:v,body:"",createdAt:null,url:"",reviewComments:P})}return{data:h}}};var G=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT);var O="https://api.bitbucket.org/2.0",An={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},$n={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},Fe=50,Kr=s=>{let t=!s||s.length===0?["OPEN"]:Array.from(new Set(s.flatMap(r=>$n[r]))),e=t.map(r=>`state="${r}"`).join(" OR ");return t.length>1?`(${e})`:e},Ln=s=>s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Xr=s=>{let t=s?.trim();if(!t)return null;let e=Ln(t);return`(title ~ "${e}" OR description ~ "${e}")`},Zr=s=>{let t=!!s.next,e=typeof s.size=="number"?s.size:null,r=typeof s.pagelen=="number"&&s.pagelen>0?s.pagelen:null;return{hasNextPage:t,nextPage:t?s.page+1:null,currentPage:typeof s.page=="number"?s.page:null,totalCount:e,totalPages:e!==null&&r?Math.ceil(e/r):null}},ze={owner:4,admin:3,contributor:2,member:1},Me=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),Yr=s=>{let t=s.links.clone,e=t?.find(n=>n.name==="ssh"),r=t?.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},zt=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(t=>t.name==="https")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),Mt=s=>{let t=s.id,e=s.participants?.map(r=>{let n="REVIEW_REQUESTED";return r.approved?n="APPROVED":r.state==="changes_requested"?n="CHANGES_REQUESTED":r.participated_on!==null&&(n="COMMENTED"),{reviewer:Me(r.user),state:n}})??[];return{id:t.toString(),title:s.title,description:s.description,number:t,state:An[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:Me(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo:Yr(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:J(e),additions:null,deletions:null,fileCount:null,commitCount:null,isCrossRepository:s.source.repository.uuid!==s.destination.repository.uuid,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:Yr(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Un=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}}},Gn=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}}},Ie=class extends M{async refreshToken(t){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${O}/user`,headers:G(this.config,e)});return{data:Me(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${O}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:G(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${O}/repositories/${t.namespace}/${t.name}`,headers:G(this.config,e)});return{data:zt(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForWorkspace(t,e={}){let r=new URL(`${O}/repositories/${encodeURIComponent(t.workspace)}`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",$.toString()),t.minimumRole&&r.searchParams.set("role",t.minimumRole);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(zt)}}async getAllReposForWorkspace(t,e={}){let r=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:t.workspace,minimumRole:t.minimumRole,page:n},e);r.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return r}async getAllReposForWorkspaceWithPermissions(t,e={}){let r=new Map,n=[],o=ze[t.minimumRole||"member"];o<=ze.admin&&n.push("admin"),o<=ze.contributor&&n.push("contributor"),o<=ze.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:t.workspace,minimumRole:a},e);for(let u of i)r.has(u.id)||r.set(u.id,a)}return{data:i.map(a=>{let u=r.get(a.id)||"member";return{...a,permissions:Gn(u)}})}}async getReposForCurrentUser(t,e={}){let r=new URL(`${O}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",$.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(zt)}}async getBranches(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",$.toString());let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",$.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(t={},e={}){let r=new URL(`${O}/user/workspaces`);r.searchParams.set("page",t?.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t?.administrator!==void 0&&r.searchParams.set("administrator",t.administrator.toString());let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(t,e={}){let r=new URL(`${O}/user/permissions/workspaces`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",L(t.pageSize,{fallback:Fe,max:Fe}).toString());let n=[Kr(t.states)];t.repos&&t.repos.length>0&&n.push(`(${t.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`);let o=Xr(t.query);o&&n.push(o),r.searchParams.set("q",n.join(" AND "));let i=await this.config.request({url:r.toString(),headers:G(this.config,e)});return{pageInfo:Zr(i.body),data:i.body.values.map(Mt)}}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${O}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let o=Kr(t.states);n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`);let i=Xr(t.query);return i&&(o+=` AND ${i}`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",L(t.pageSize,{fallback:Fe,max:Fe}).toString()),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:G(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);return n.body.values.forEach(o=>{r.push(Mt(o))}),{pageInfo:Zr(n.body),data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{r.push(Mt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>Me(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${O}/user/permissions/repositories`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:Un(a.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:G(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var We={};H(We,{normalizePermissions:()=>Wt,restApiPullRequestToCommonPullRequest:()=>Tn});var Tn=s=>$e(s),Wt=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Le=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},$e=s=>{let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(u=>({reviewer:Le(u.user),state:e[u.status]})),n=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:s.id.toString(),number:s.id,title:s.title,description:s.description,url:s.links.self[0].href,state:t[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Le(s.author.user),assignees:null,reviews:r,reviewDecision:J(r),isCrossRepository:s.fromRef.repository.id!==s.toRef.repository.id,repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},es=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(t=>t.name==="https"||t.name==="http")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),ts=50,On={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},rs=s=>{if(!s||s.length===0)return"OPEN";let t=Array.from(new Set(s.map(e=>On[e])));return t.length===1?t[0]:"ALL"},ss=(s,t)=>typeof s!="number"||t<=0?null:Math.floor(s/t)+1,be=class extends Q{getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return R(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>i?i===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Le(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Le(o.body.author)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data:es(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=t.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(es)}}async getRepoPermissionsForUsername(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:Wt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests`);return r.searchParams.set("state",rs(t.states)),r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit",L(t.pageSize,{fallback:ts}).toString()),t.reviewerLogin&&(r.searchParams.set("role.1","REVIEWER"),r.searchParams.set("username.1",t.reviewerLogin)),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push($e(i))});let o=!n.body.isLastPage;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.nextPageStart:null,currentPage:ss(n.body.start,n.body.limit)},data:x(r,t.states)}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push($e(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:x(r,t.states)}}async getPullRequestsForCurrentUser(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state",rs(t.states)),r.searchParams.set("start",t.page?.toString()||"0");let n=L(t.pageSize,{fallback:ts});r.searchParams.set("limit",n.toString()),t.reviewerLogin&&(r.searchParams.set("role.1","REVIEWER"),r.searchParams.set("username.1",t.reviewerLogin));let o=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),i=!o.body.isLastPage;return{pageInfo:{hasNextPage:i,nextPage:i?o.body.nextPageStart:null,currentPage:ss(o.body.start,o.body.limit)},data:x(o.body.values.map($e),t.states)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>Le(i.user))}}};var ys=require("js-base64");var I=class extends Error{constructor(e,r){let n=r?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var _n={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]},ns=15,os=100,Ue={__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"},k=s=>!!s,K=(s,t)=>{let e=_n[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Ve="https://api.github.com",kn=`${Ve}/graphql`,Je=`
|
|
1
|
+
"use strict";var Ot=Object.defineProperty;var ln=Object.getOwnPropertyDescriptor;var pn=Object.getOwnPropertyNames;var dn=Object.prototype.hasOwnProperty;var H=(s,t)=>{for(var e in t)Ot(s,e,{get:t[e],enumerable:!0})},cn=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of pn(t))!dn.call(s,n)&&n!==e&&Ot(s,n,{get:()=>t[n],enumerable:!(r=ln(t,n))||r.enumerable});return s};var mn=s=>cn(Ot({},"__esModule",{value:!0}),s);var vi={};H(vi,{AzureDevOps:()=>Re,AzureDevopsUtils:()=>ht,Bitbucket:()=>Ie,BitbucketServer:()=>be,BitbucketServerUtils:()=>We,BitbucketUtils:()=>ft,EntityIdentifierProviderType:()=>N,EntityIdentifierUtils:()=>Dt,EntityType:()=>j,EntityVersion:()=>B,GitBuildStatusStage:()=>xr,GitBuildStatusState:()=>De,GitDiffLineType:()=>_t,GitHub:()=>ye,GitHubIssueCloseReason:()=>sn,GitHubUtils:()=>$t,GitIssueState:()=>ce,GitLab:()=>we,GitLabUtils:()=>Lt,GitMergeStrategy:()=>fe,GitProviderUtils:()=>At,GitPullRequestMergeableState:()=>ee,GitPullRequestReviewState:()=>V,GitPullRequestState:()=>oe,GraphQLErrors:()=>I,Jira:()=>qe,JiraServer:()=>ve,JiraUtils:()=>Gt,Linear:()=>Ee,PullRequestAsyncStatus:()=>rn,Trello:()=>Se,TrelloUtils:()=>Ut,Utils:()=>qi,default:()=>wi,isFetch:()=>Be});module.exports=mn(vi);var Jr=require("diff");var xr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(xr||{}),De=(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))(De||{}),fe=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(fe||{}),oe=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(oe||{}),V=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(V||{}),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||{}),_t=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(_t||{});var Nr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},J=s=>!s||s.length===0?null:s.reduce((t,e)=>Nr[e.state]>Nr[t]?e.state:t,"APPROVED"),Ne=(s,t)=>s.name||s.username||s.email||t,de=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var R=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},Br=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,ie=(s,t,e)=>!s||t.some(r=>s[r])?e:"",jr=async s=>{let t=[],e=!0,r;for(;e;){let n=await s(r);t=t.concat(n.data),e=!!n?.pageInfo?.hasNextPage,r=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return t};async function kt(s){return(await Promise.allSettled(s)).map(e=>gn(e)).filter(e=>e!=null)}var L=(s,{fallback:t,max:e})=>!s||s<=0?t:e===void 0?s:Math.min(s,e),x=(s,t)=>{if(!t||t.length===0)return s;let e=new Set(t);return s.filter(r=>e.has(r.state))};function gn(s,t=void 0){return s?.status==="fulfilled"?s.value:t}async function Qr(s,t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)throw new Error("batchSize must be a positive integer");for(let r=0;r<s.length;r+=t){let n=s.slice(r,r+t);await Promise.all(n.map(e))}}var ce=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ce||{});var xt=(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))(xt||{});var $=100;var Fr=globalThis.fetch;var hn=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(t.startsWith("text/")||t===""||t.startsWith("application/vnd.github.diff")||t.startsWith("application/vnd.github.patch"))e=await s.text();else if(t.startsWith("application/vnd.github.raw+json")||t.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${t}`);let r={};s.headers.forEach((o,i)=>{r[i]=o});let n={body:e,headers:r,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},Nt=s=>async({url:t,...e})=>{let r=await s(t,e);return hn(r)};var Be=(s,t=!1)=>s.name==="fetch"||t;var M=class{constructor(t){let e=t?.request||Fr;this.config={...t,request:Be(e,t?.forceIsFetch)?Nt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&Be(t.request,t?.forceIsFetch??this.config.forceIsFetch)?Nt(t.request):this.config.request}}},Q=class extends M{};var fn="https://app.vssps.visualstudio.com/_apis",Rn="https://vssps.dev.azure.com/",In="https://dev.azure.com",q=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT),zr=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),Bt=(s,t)=>{let e=t.baseUrl||s.baseUrl||fn;return e=e.replace(/\/$/,""),e},C=(s,t)=>{let e=t.baseUrl||s.baseUrl||In;return e=e.replace(/\/$/,""),e},jt=(s,t)=>{let e=t.baseUrl||s.baseUrl||Rn;return e=e.replace(/\/$/,""),e};var bn={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},yn={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},je=100,Pn=200,wn=200,Mr=s=>{if(!s||s.length===0)return"active";let t=Array.from(new Set(s.map(e=>yn[e])));return t.length===1?t[0]:"all"},qn=s=>{if(!s||s.length===0)return["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"];let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?[]:r?["([Microsoft.VSTS.Common.ClosedDate] <> '' OR [Microsoft.VSTS.Common.ResolvedDate] <> '')"]:["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"]},vn=s=>{if(typeof s!="string")return s;let t=s.charAt(0).toUpperCase()+s.slice(1);return xt[t]??0},En=new Set([2,3,4,5]),Sn={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},me=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Qe=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Cn=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"}},Qt=(s,t,e,r,n,o)=>`${s}|${t}|${e}|${r}|${n}|${o}`,Wr=s=>{let t=s.split("|");if(t.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4],commentId:t[5]}},Hr=(s,t,e,r,n)=>`${s}|${t}|${e}|${r}|${n}`,Ft=s=>{let t=s.split("|");if(t.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4]}},Ae=(s,t,e)=>{let r=!!t.forkSource,n=[],o=[];return t.reviewers.forEach(i=>{let a={reviewer:me(i),state:Sn[i.vote??0]||"REVIEW_REQUESTED"};i.isRequired&&n.push(a),o.push(a)}),{id:t.pullRequestId.toString(),title:t.title,description:t.description??null,number:t.codeReviewId,state:bn[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:me(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,isCrossRepository:r,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null},headCommit:{buildStatuses:null},baseRef:{name:Qe(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Qe(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:zr(t),assignees:t.reviewers.map(me),reviews:o,reviewDecision:J(n),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:e?.get(t.forkSource.repository.id)??null,isFork:!0}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null,isFork:!1},mergeableState:Cn(t.mergeStatus),labels:t.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},Vr=(s,t)=>({id:t.id,name:t.name,namespace:s,project:t.project.name,projectId:t.project.id,webUrl:t.webUrl,httpsUrl:t.remoteUrl,sshUrl:t.sshUrl,defaultBranch:t.defaultBranch?{name:Qe(t.defaultBranch)}:null,permissions:null}),Dn=(s,t,e,r)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=r[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},Re=class extends Q{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,r){let n=JSON.stringify([e,r.token??null,r.isPAT??this.config.isPAT??!1,r.baseUrl??null]),o=this.cachedUserIds.get(n);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(n);if(i)return i;let a=this.fetchCurrentUserId(e,r,n);return this.inflightUserIds.set(n,a),a}async fetchCurrentUserId(e,r,n){try{let o=await this.getCurrentUserForInstance({namespace:e},r);return this.cachedUserIds.set(n,o.data.id),o.data.id}finally{this.inflightUserIds.delete(n)}}getRepoApiUrl(e,r,n,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(r)}/_apis/git/repositories/${encodeURIComponent(n)}`}async getCurrentUser(e={},r={}){if(r.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let n=`${Bt(this.config,r)}/profile/profiles/me`,o=await this.config.request({url:n,headers:q(this.config,r)});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,r={}){let o=(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:q(this.config,r)})).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,r={}){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,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:q(this.config,r)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,r={}){let n=`${Bt(this.config,r)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,r={}){let n=`${C(this.config,r)}/_apis/projectCollections`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,r={}){let n=new URL(`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/projects`);n.searchParams.set("$top",$.toString()),e.cursor&&n.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:n.toString(),headers:q(this.config,r)}),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,r={}){let{namespace:n,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${jt(this.config,r)}/${encodeURIComponent(n)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:q(this.config,r)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,r={}){let{namespace:n,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${jt(this.config,r)}/${encodeURIComponent(n)}/_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:q(this.config,r)}),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,r={}){let{azureGraphAccount:n}=e;if(!n.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:n.storageKeyURL,headers:q(this.config,r)});return{data:{avatarUrl:n.avatarUrl,email:n.email,id:o.body.value,name:n.name,username:n.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,r={}){let n=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},r);n.push(i.data)}return{data:n}}async getRepo(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:q(this.config,r)});return{data:Vr(e.namespace,n.body)}}async getRepos(e,r={}){let n=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,r);n.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:n,errors:o}}async getReposForAzureProject(e,r={}){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,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:q(this.config,r)})).body.value.map(o=>Vr(e.namespace,o))}}async getRefs(e,r,n={}){if(!r.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${C(this.config,n)}/${encodeURIComponent(r.repo.namespace)}/${encodeURIComponent(r.repo.project)}/_apis/git/repositories/${encodeURIComponent(r.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",$.toString()),r.cursor&&o.searchParams.set("continuationToken",r.cursor);let i=await this.config.request({url:o.toString(),headers:q(this.config,n)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Qe(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,r={}){return this.getRefs("heads",e,r)}async getTags(e,r={}){return this.getRefs("tags",e,r)}async fetchRemoteInfoByRepoId(e,r,n){let o=new Map;if(!e)return o;let i=new Map;for(let{namespace:a,pullRequests:u}of r)for(let l of u)i.has(l.repository.id)||i.set(l.repository.id,a),l.forkSource&&!i.has(l.forkSource.repository.id)&&i.set(l.forkSource.repository.id,a);return await Qr([...i],10,async([a,u])=>{try{let l=await this.config.request({url:`${C(this.config,n)}/${encodeURIComponent(u)}/_apis/git/repositories/${encodeURIComponent(a)}`,headers:q(this.config,n)}),{remoteUrl:p,sshUrl:d}=l.body;p&&d&&o.set(a,{cloneUrlHTTPS:p,cloneUrlSSH:d})}catch{}}),o}async getPullRequestsForRepoBase(e,r={},n=je){let{page:o,repo:i,assigneeLogins:a,authorLogin:u,reviewerId:l}=e||{},p=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let d=L(e.pageSize,{fallback:n}),c=l??(a&&a.length?a[0]:void 0),g=`searchCriteria.status=${Mr(e.states)}`;return c&&(g+=`&searchCriteria.reviewerId=${encodeURIComponent(c)}`),u&&(g+=`&searchCriteria.creatorId=${encodeURIComponent(u)}`),await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${g}&%24top=${d}&%24skip=${(p-1)*d}`,headers:q(this.config,r)})}async getPullRequestsForRepo(e,r={}){let n=L(e.pageSize,{fallback:je}),o=e.page||1,i=await this.getPullRequestsForRepoBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:e.repo.namespace,pullRequests:i.body.value}],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i.body.value.map(l=>Ae(e.repo.namespace,l,u)),e.states)}}async getPullRequestsForRepos(e,r={}){if(!e.repos.every(u=>u.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:n}=e||{},o=[];await Promise.all(n.map(async u=>{try{let l=await this.getPullRequestsForRepoBase({repo:u,...e},r);o.push({namespace:u.namespace,pullRequests:l.body.value})}catch(l){if(l.statusCode!==404&&l.statusCode!==401)throw l}}));let i=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,o,r),a=o.flatMap(({namespace:u,pullRequests:l})=>l.map(p=>Ae(u,p,i)));return{data:x(a,e.states)}}async getPullRequestsForProjectBase(e,r={},n=je){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,reviewerId:p,repo:d}=e;if(d?.project&&d.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,g=L(e.pageSize,{fallback:n}),m=p??(u&&u.length?u[0]:void 0),h=new URL(`${C(this.config,r)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",Mr(e.states)),h.searchParams.set("$top",g.toString()),h.searchParams.set("$skip",((c-1)*g).toString()),d?.id&&d?.project===i&&h.searchParams.set("searchCriteria.repositoryId",d.id),m&&h.searchParams.set("searchCriteria.reviewerId",m),l&&h.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:h.toString(),headers:q(this.config,r)})}async getPullRequestsForProject(e,r={}){let n=L(e.pageSize,{fallback:je}),o=e.page||1,i=await this.getPullRequestsForProjectBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,i?[{namespace:e.namespace,pullRequests:i.body.value}]:[],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i?.body.value.map(l=>Ae(e.namespace,l,u))||[],e.states)}}async getPullRequestsForProjects(e,r={}){let{projects:n}=e||{},o=[];await Promise.all(n.map(async u=>{try{if(!e.repo||e.repo.project&&e.repo.project===u.project){let l=await this.getPullRequestsForProjectBase({...u,...e},r);l&&o.push({namespace:u.namespace,pullRequests:l.body.value})}}catch(l){if(l.statusCode!==404&&l.statusCode!==401)throw l}}));let i=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,o,r),a=o.flatMap(({namespace:u,pullRequests:l})=>l.map(p=>Ae(u,p,i)));return{data:x(a,e.states)}}async getAzurePullRequestLastMergeStatus(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:n,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...q(this.config,r)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,r,n){return await this.config.request({method:"PATCH",url:`${C(this.config,n)}/${encodeURIComponent(e.repository.owner.login)}/${encodeURIComponent(e.repository.project)}/_apis/git/repositories/${e.repository.name}/pullrequests/${e.id}?api-version=6.0`,body:r,headers:{...q(this.config,n),"Content-Type":"application/json"}})}async closePullRequest(e,r={}){let{pullRequest:n}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(n,JSON.stringify(o),r)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,r={}){let{pullRequest:n,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:n.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(n,JSON.stringify(a),r)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.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,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.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,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...q(this.config,r)}})}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=n.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:n,label:a},r);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:n,label:a},r)}async setPullRequestAsDraft(e,r={}){let{pullRequest:n,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(n,JSON.stringify(i),r)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,headers:{...q(this.config,r),Accept:"application/json"}})}async setPullRequestReviewers(e,r={}){let{pullRequest:n,reviewers:o}=e;for(let i of o)n.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:n,reviewer:i,isRequired:!0},r);for(let i of n.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:n,reviewer:i},r)}async getIssuesForAzureProject(e,r={}){let{page:n,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=n||1,d=Math.min(L(e.pageSize,{fallback:Pn}),wn),c=["[System.TeamProject] = @project",...qn(e.states)];i&&c.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&c.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&c.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(A=>c.push(`[System.Tags] Contains '${A}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${c.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}}),h=m.body.workItems.slice((p-1)*d,d*p).map(A=>A.id),y=m.body.workItems.length,f=Math.ceil(y/d),P=y>d*p;if(h.length===0)return{pageInfo:{hasNextPage:!1,nextPage:null,currentPage:p,totalCount:y,totalPages:f},data:[]};let v=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:h,$expand:"Links"}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?p+1:null,currentPage:p,totalCount:y,totalPages:f},data:v.body.value.map(A=>Dn(e.namespace,e.project,A,l||{}))}}async getPermissionsForRepos(e,r={}){let{namespace:n,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=d=>{let c="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${d.projectId}/${d.id}`;return Object.keys(i).map(m=>({securityNamespaceId:c,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,r)}/${encodeURIComponent(n)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.evaluations.reduce((d,c)=>{let[,g,m]=c.token.split("/"),h=`${g}/${m}`,y=i[c.permissions];for(let f of y)d[h]===void 0&&(d[h]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),c.value===!1&&(d[h][f]=!1);return d},{})}}async decorateReposWithPermissions(e,r={}){let{namespace:n,repos:o}=e,i=await this.getPermissionsForRepos({namespace:n,repos:o},r);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,r,n={}){return await this.config.request({method:"PATCH",url:`${C(this.config,n)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(r),headers:{...q(this.config,n),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,r={}){let{issue:n,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,r={}){let{issue:n,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(n,a,r)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...q(this.config,r)}})).body.value}}async getLabelsForProject(e,r={}){let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...q(this.config,r)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:n.namespace,pullRequests:[i.body]}],r);return{data:Ae(n.namespace,i.body,a)}}async getPullRequestDescription(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');try{return{data:{description:(await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,r={}){let{repo:n,number:o,description:i}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:{description:(await this.config.request({method:"PATCH",url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:{...q(this.config,r),"Content-Type":"application/json"},body:JSON.stringify({description:i})})).body?.description??i}}}async getMergeBase(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:q(this.config,r)});if(!n.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:n.body.value[0].commitId}}async getFileContents(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...q(this.config,r),Accept:"application/octet-stream"}});return{data:new Blob([n.body])}}async getPullRequestDiff(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${n}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,p=a.body.lastMergeSourceCommit.commitId,d=u.body.value;if(d.length===0)return"";let c=d[d.length-1],g=1e3,m=[],h=0;for(;;){let S=(await this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations/${c.id}/changes?api-version=7.1&$top=${g}&$skip=${h}`,headers:o})).body.changeEntries??[];if(S.length===0||(m.push(...S),S.length<g))break;h+=S.length}if(m.length===0)return"";let y=5,f=[],P=new TextDecoder,v=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",A=async(w,S)=>{try{let le=await this.config.request({url:`${n}/items?path=${encodeURIComponent(w)}&versionDescriptor[version]=${encodeURIComponent(S)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return v(le.body)}catch{return""}},D=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let S=w.toLowerCase().split(",").map(le=>le.trim());return{add:S.includes("add"),rename:S.includes("rename"),delete:S.includes("delete")}};for(let w=0;w<m.length;w+=y){let S=m.slice(w,w+y),le=await Promise.all(S.map(async ge=>{let{add:he,rename:Tt,delete:pe}=D(ge.changeType),Ce=ge.originalPath??ge.item.originalPath,T=ge.item.path,xe=pe?T??Ce??"":T??"",kr=Tt||pe?Ce??xe:xe,[nn,on]=await Promise.all([he?Promise.resolve(""):A(kr,l),pe?Promise.resolve(""):A(xe,p)]),an=he?"/dev/null":`a${kr}`,un=pe?"/dev/null":`b${xe}`;return(0,Jr.createTwoFilesPatch)(an,un,nn,on)}));f.push(...le)}return f.join(`
|
|
2
|
+
`)}getPullRequestWriteHeaders(e){return{...q(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,r,n,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${r}/reviewers/${encodeURIComponent(n)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,r,n,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${r}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:n,commentType:1}],status:1})})}async getCommentsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i=await this.config.request({url:`${n}/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:Qt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?me(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,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async addInlineCommentToPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r),o=this.getPullRequestWriteHeaders(r);if(e.threadId){let p=Ft(e.threadId),d=e.pullRequest.repository.owner.login,c=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(p.namespace!==d||p.project!==c||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 ${d}/${c}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${n}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}?api-version=7.1`,headers:q(this.config,r)})).body.comments?.find(P=>P.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${p.threadId}.`);let f=await this.config.request({method:"POST",url:`${n}/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 Qt(d,c,g,Number(m),Number(p.threadId),f.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:`${n}/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 Hr(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,r={}){let n=Wr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({content:e.body})})}async editInlineComment(e,r={}){return this.editComment(e,r)}async deleteComment(e,r={}){let n=Wr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:q(this.config,r)})}async deleteInlineComment(e,r={}){return this.deleteComment(e,r)}async resolveReviewThread(e,r={}){let n=Ft(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,r={}){let n=Ft(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:1})})}async approvePullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,r),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,r):null])}async requestPullRequestChanges(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,r),await this.setReviewerVote(o,e.pullRequest.id,i,-5,r)}async commentOnPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async getReviewsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(n,o,i,r),l=q(this.config,r),[p,d]=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})]),c=(f,P)=>Qt(n,o,i,a,f,P),g=f=>Hr(n,o,i,a,f),m=new Map;for(let f of d.body.value){if(f.isDeleted)continue;let P=f.comments.filter(T=>!T.isDeleted&&T.commentType!=="system"),v=P.find(T=>T.parentCommentId===0)??P[0];if(!v)continue;let A=v.author?.id;if(!A)continue;let D=P.filter(T=>T.id!==v.id),w=f.threadContext,S=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,le=S?.end?.line??S?.start.line??null,ge=S?.start&&S.end&&S.start.line!==S.end.line?S.start.line:null,he=w?.filePath??"",Tt=he.startsWith("/")?he.slice(1):he,pe={id:c(f.id,v.id),author:v.author?me(v.author):null,body:v.content??"",createdAt:v.publishedDate?new Date(v.publishedDate):null,url:"",diffLines:[],filename:Tt,replies:D.map(T=>({id:c(f.id,T.id),author:T.author?me(T.author):null,body:T.content??"",createdAt:T.publishedDate?new Date(T.publishedDate):null,url:""})),isOutdated:!1,isResolved:En.has(vn(f.status)),line:le,startLine:ge,side:S?.side??null,threadId:g(f.id)},Ce=m.get(A);Ce?Ce.push(pe):m.set(A,[pe])}let h=[],y=new Set;for(let f of p.body.value){if(f.hasDeclined)continue;let P=f.vote??0,v=m.get(f.id);P===0&&!v?.length||(h.push({id:f.id,author:me(f),body:"",createdAt:null,url:"",reviewComments:v??[]}),y.add(f.id))}for(let[f,P]of m){if(y.has(f)||!P.length)continue;let v=P[0].author;v&&h.push({id:f,author:v,body:"",createdAt:null,url:"",reviewComments:P})}return{data:h}}};var U=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT);var O="https://api.bitbucket.org/2.0",An={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},$n={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},Fe=50,Kr=s=>{let t=!s||s.length===0?["OPEN"]:Array.from(new Set(s.flatMap(r=>$n[r]))),e=t.map(r=>`state="${r}"`).join(" OR ");return t.length>1?`(${e})`:e},Ln=s=>s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Xr=s=>{let t=s?.trim();if(!t)return null;let e=Ln(t);return`(title ~ "${e}" OR description ~ "${e}")`},Zr=s=>{let t=!!s.next,e=typeof s.size=="number"?s.size:null,r=typeof s.pagelen=="number"&&s.pagelen>0?s.pagelen:null;return{hasNextPage:t,nextPage:t?s.page+1:null,currentPage:typeof s.page=="number"?s.page:null,totalCount:e,totalPages:e!==null&&r?Math.ceil(e/r):null}},ze={owner:4,admin:3,contributor:2,member:1},Me=s=>({id:s.uuid,name:s.display_name||s.nickname,username:s.nickname||s.display_name,email:null,avatarUrl:s.links.avatar.href,url:s.links.html.href}),Yr=s=>{let t=s.links.clone,e=t?.find(n=>n.name==="ssh"),r=t?.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},zt=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(t=>t.name==="https")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),Mt=s=>{let t=s.id,e=s.participants?.map(r=>{let n="REVIEW_REQUESTED";return r.approved?n="APPROVED":r.state==="changes_requested"?n="CHANGES_REQUESTED":r.participated_on!==null&&(n="COMMENTED"),{reviewer:Me(r.user),state:n}})??[];return{id:t.toString(),title:s.title,description:s.description,number:t,state:An[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:Me(s.author),createdDate:new Date(s.created_on),updatedDate:new Date(s.updated_on),closedDate:null,mergedDate:null,repository:{id:s.destination.repository.uuid,name:s.destination.repository.name,owner:{login:s.destination.repository.full_name.split("/")[0]},remoteInfo:Yr(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:J(e),additions:null,deletions:null,fileCount:null,commitCount:null,isCrossRepository:s.source.repository.uuid!==s.destination.repository.uuid,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:Yr(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Gn=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}}},Un=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}}},Ie=class extends M{async refreshToken(t){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${O}/user`,headers:U(this.config,e)});return{data:Me(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${O}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:U(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${O}/repositories/${t.namespace}/${t.name}`,headers:U(this.config,e)});return{data:zt(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForWorkspace(t,e={}){let r=new URL(`${O}/repositories/${encodeURIComponent(t.workspace)}`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",$.toString()),t.minimumRole&&r.searchParams.set("role",t.minimumRole);let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(zt)}}async getAllReposForWorkspace(t,e={}){let r=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:t.workspace,minimumRole:t.minimumRole,page:n},e);r.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return r}async getAllReposForWorkspaceWithPermissions(t,e={}){let r=new Map,n=[],o=ze[t.minimumRole||"member"];o<=ze.admin&&n.push("admin"),o<=ze.contributor&&n.push("contributor"),o<=ze.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:t.workspace,minimumRole:a},e);for(let u of i)r.has(u.id)||r.set(u.id,a)}return{data:i.map(a=>{let u=r.get(a.id)||"member";return{...a,permissions:Un(u)}})}}async getReposForCurrentUser(t,e={}){let r=new URL(`${O}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",$.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(zt)}}async getBranches(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",$.toString());let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",$.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(t={},e={}){let r=new URL(`${O}/user/workspaces`);r.searchParams.set("page",t?.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t?.administrator!==void 0&&r.searchParams.set("administrator",t.administrator.toString());let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(t,e={}){let r=new URL(`${O}/user/permissions/workspaces`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",L(t.pageSize,{fallback:Fe,max:Fe}).toString());let n=[Kr(t.states)];t.repos&&t.repos.length>0&&n.push(`(${t.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`);let o=Xr(t.query);o&&n.push(o),r.searchParams.set("q",n.join(" AND "));let i=await this.config.request({url:r.toString(),headers:U(this.config,e)});return{pageInfo:Zr(i.body),data:i.body.values.map(Mt)}}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${O}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let o=Kr(t.states);n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`);let i=Xr(t.query);return i&&(o+=` AND ${i}`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",L(t.pageSize,{fallback:Fe,max:Fe}).toString()),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:U(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);return n.body.values.forEach(o=>{r.push(Mt(o))}),{pageInfo:Zr(n.body),data:r}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{r.push(Mt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:r}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>Me(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${O}/user/permissions/repositories`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:U(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:Gn(a.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:U(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...U(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...U(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var We={};H(We,{normalizePermissions:()=>Wt,restApiPullRequestToCommonPullRequest:()=>Tn});var Tn=s=>$e(s),Wt=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Le=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},$e=s=>{let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(u=>({reviewer:Le(u.user),state:e[u.status]})),n=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:s.id.toString(),number:s.id,title:s.title,description:s.description,url:s.links.self[0].href,state:t[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Le(s.author.user),assignees:null,reviews:r,reviewDecision:J(r),isCrossRepository:s.fromRef.repository.id!==s.toRef.repository.id,repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},es=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(t=>t.name==="https"||t.name==="http")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),ts=50,On={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},rs=s=>{if(!s||s.length===0)return"OPEN";let t=Array.from(new Set(s.map(e=>On[e])));return t.length===1?t[0]:"ALL"},ss=(s,t)=>typeof s!="number"||t<=0?null:Math.floor(s/t)+1,be=class extends Q{getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return R(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:p,id:d,name:c,slug:g})=>i?i===d:a===c||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Le(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Le(o.body.author)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data:es(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=t.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(es)}}async getRepoPermissionsForUsername(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:Wt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests`);return r.searchParams.set("state",rs(t.states)),r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit",L(t.pageSize,{fallback:ts}).toString()),t.reviewerLogin&&(r.searchParams.set("role.1","REVIEWER"),r.searchParams.set("username.1",t.reviewerLogin)),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push($e(i))});let o=!n.body.isLastPage;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.nextPageStart:null,currentPage:ss(n.body.start,n.body.limit)},data:x(r,t.states)}}async getPullRequestsForRepos(t,e={}){let r=[];return await Promise.all(t.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...t},e)).body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push($e(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:x(r,t.states)}}async getPullRequestsForCurrentUser(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state",rs(t.states)),r.searchParams.set("start",t.page?.toString()||"0");let n=L(t.pageSize,{fallback:ts});r.searchParams.set("limit",n.toString()),t.reviewerLogin&&(r.searchParams.set("role.1","REVIEWER"),r.searchParams.set("username.1",t.reviewerLogin));let o=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),i=!o.body.isLastPage;return{pageInfo:{hasNextPage:i,nextPage:i?o.body.nextPageStart:null,currentPage:ss(o.body.start,o.body.limit)},data:x(o.body.values.map($e),t.states)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>Le(i.user))}}};var ys=require("js-base64");var I=class extends Error{constructor(e,r){let n=r?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var _n={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]},ns=15,os=100,Ge={__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"},k=s=>!!s,K=(s,t)=>{let e=_n[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Ve="https://api.github.com",kn=`${Ve}/graphql`,Je=`
|
|
3
3
|
description
|
|
4
4
|
dueOn
|
|
5
5
|
id
|
|
@@ -244,7 +244,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
244
244
|
`).slice(1),u=o-1,l=i-1,p=a.map(g=>{let m,h;switch(g[0]){case"-":{m="DELETED",u+=1,h=`${g.slice(1)}
|
|
245
245
|
`;break}case"+":{m="ADDED",l+=1,h=`${g.slice(1)}
|
|
246
246
|
`;break}default:m="UNMODIFIED",l+=1,u+=1,h=`${g}
|
|
247
|
-
`}return{line:h,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=t;if(d!==null&&c!==null&&r!==null&&d<c){let g=0,m=p.length,h=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<p.length;y++){let P=p[y][h];P===d?g=y:P===c&&(m=y)}p=p.slice(g,m+1)}return p},ds=s=>{let t=s.author;return t||(t=
|
|
247
|
+
`}return{line:h,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),d=e,c=t;if(d!==null&&c!==null&&r!==null&&d<c){let g=0,m=p.length,h=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<p.length;y++){let P=p[y][h];P===d?g=y:P===c&&(m=y)}p=p.slice(g,m+1)}return p},ds=s=>{let t=s.author;return t||(t=Ge),{author:{id:"databaseId"in t?t.databaseId.toString():t.id,graphQLId:t.id,name:("name"in t?t.name:t.login)??t.login,username:t.login,email:("email"in t?t.email:null)??null,avatarUrl:t.avatarUrl,url:t.url},body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId?.toString()??s.id,url:s.url}};var cs=`mutation DeleteIssueComment(
|
|
248
248
|
$issueCommentId: ID!
|
|
249
249
|
) {
|
|
250
250
|
deleteIssueComment(input: {
|
|
@@ -369,7 +369,7 @@ defaultBranchRef {
|
|
|
369
369
|
name
|
|
370
370
|
}
|
|
371
371
|
viewerPermission
|
|
372
|
-
`,Vn={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Jn={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Kn={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Xn={OPEN:"OPEN",CLOSED:"CLOSED"},Zn=["ADMIN","MAINTAIN","TRIAGE","WRITE"],er=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Yn=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Zt=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:Yn(s.viewerPermission)}),eo=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),bs=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:eo(s.permissions)}),to=s=>({path:s.path,isDirectory:s.type==="tree"}),ro={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},so={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},W=(s,t=so)=>{let e={};return t.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),t.graphQLId&&(e.graphQLId=s.id),t.name&&(e.name=s.name??s.login),t.username&&(e.username=s.login),t.email&&(e.email=s.email??null),t.avatarUrl&&(e.avatarUrl=s.avatarUrl),t.url&&(e.url=s.url),e},no=(s,t)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return s!=="COMPLETED"?e[s]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[t]},oo=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],Yt=s=>{let t=null;s.author?t=s.author:t=
|
|
372
|
+
`,Vn={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Jn={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Kn={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},Xn={OPEN:"OPEN",CLOSED:"CLOSED"},Zn=["ADMIN","MAINTAIN","TRIAGE","WRITE"],er=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Yn=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),Zt=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:Yn(s.viewerPermission)}),eo=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),bs=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:eo(s.permissions)}),to=s=>({path:s.path,isDirectory:s.type==="tree"}),ro={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},so={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},W=(s,t=so)=>{let e={};return t.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),t.graphQLId&&(e.graphQLId=s.id),t.name&&(e.name=s.name??s.login),t.username&&(e.username=s.login),t.email&&(e.email=s.email??null),t.avatarUrl&&(e.avatarUrl=s.avatarUrl),t.url&&(e.url=s.url),e},no=(s,t)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return s!=="COMPLETED"?e[s]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[t]},oo=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],Yt=s=>{let t=null;s.author?t=s.author:t=Ge;let e=(s.reviewRequests?.nodes||[]).filter(k).filter(i=>!i.asCodeOwner),r=s.headRepository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=s.repository?.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:W(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(k).map(i=>{let a=Ge;return i.author&&i.author.__typename&&(a=i.author),{reviewer:W(a),state:Vn[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:ro[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?W(t):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:s.repository.sshUrl}},isCrossRepository:s.headRepository!=null&&s.headRepository.databaseId!==s.repository.databaseId,headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.headRepository.sshUrl},isFork:s.headRepository.isFork}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(k)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(k).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:oo(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:no(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(k).map(i=>W(i)):null,reviews:o,reviewDecision:J(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:Kn[s.mergeStateStatus]??Jn[s.mergeable],milestone:s.milestone?tr(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(er)??[],permissions:{canMerge:Zn.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},io=s=>{let{id:t,comments:e,isOutdated:r,isResolved:n,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:p}=s,d=e.nodes?.[0];if(!d)return null;let{author:c,body:g,databaseId:m,fullDatabaseId:h,id:y,path:f,publishedAt:P,url:v}=d,A=o??u,D=i??l,w=a??p;return{author:c?{avatarUrl:c.avatarUrl,email:null,name:c.login}:null,body:g,createdAt:P?new Date(P):null,diffLines:ps(d.diffHunk,A,D,w),id:h??m.toString(),isOutdated:r,isResolved:n,graphQLId:y,threadId:t,filename:f,replies:e.nodes?.filter(k).slice(1).map(ao)??[],url:v,line:A,startLine:D,side:w}},ao=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}),uo=s=>{let t=null;return s.author?t=s.author:t=Ge,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?W(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:Xn[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(k).map(e=>W(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?tr(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(er)??[]}},tr=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}),ye=class extends Q{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let r=e.token||this.config.token;if(!r)return[];let n=this._scopesCache[r];if(!n){let i=(await b(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[r]=n}return n}async getEnterpriseVersion(e){let r=e.baseUrl||this.config.baseUrl;if(!r)return null;let n=this._enterpriseVersionsCache[r];if(!n){let o=await this.config.request({url:`${X(this.config,e)}/meta`,headers:R(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[r]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,r,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(Ve)?e:r?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(r)}`:""}async getCurrentUser(e={},r={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=Br(e.fields),o=await this.getScopes(r),i=await b(this.config,{query:`
|
|
373
373
|
query getCurrentUser {
|
|
374
374
|
viewer {
|
|
375
375
|
${F(!1,te(o),n)}
|
|
@@ -869,7 +869,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
869
869
|
}
|
|
870
870
|
}
|
|
871
871
|
}
|
|
872
|
-
`,variables:{owner:n,name:o,cursor:i,first:$}},r);if(!a.body.data)throw new I("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(er)??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...R(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(to)}}};var lo="https://gitlab.com/api/v4",po="https://gitlab.com/api/graphql",rr=/\/api\/v\d+$/,Ps=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.")},
|
|
872
|
+
`,variables:{owner:n,name:o,cursor:i,first:$}},r);if(!a.body.data)throw new I("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(er)??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...R(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(to)}}};var lo="https://gitlab.com/api/v4",po="https://gitlab.com/api/graphql",rr=/\/api\/v\d+$/,Ps=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.")},G=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ps(e),rr.test(e)||(e=e+"/api/v4"),e):lo},co=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Ps(e),rr.test(e)&&(e=e.replace(rr,"")),`${e}/api/graphql`):po},E=(s,t,e)=>{let r=R(e.token||s.token);return s.request({url:co(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},Ue=s=>s?.map(t=>`"${t.message}"`).join(", ");var dr=s=>s.split("/").slice(0,-1).join("/"),cr=s=>s.split("/").at(-1)??"",ws=s=>{let t=parseInt(`${s["x-next-page"]}`,10);return Number.isNaN(t)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:t}},Ye=s=>({id:s.id.replace(Pe,""),graphQLId:s.id,namespace:dr(s.fullPath),name:cr(s.fullPath),webUrl:s.webUrl}),Te=s=>({id:s.id.replace(Pe,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:dr(s.fullPath),name:cr(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),mo={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},go={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Ss="gid://gitlab/User/",Pe="gid://gitlab/Project/",ho="gid://gitlab/MergeRequest/",fo="gid://gitlab/Issue/",Ro="gid://gitlab/ProjectLabel/",Io="gid://gitlab/Milestone/",bo="gid://gitlab/Ci::Build/",mr=`
|
|
873
873
|
description
|
|
874
874
|
dueDate
|
|
875
875
|
id
|
|
@@ -1007,13 +1007,13 @@ labels {
|
|
|
1007
1007
|
${s?`project { ${Oe} archived } sourceProject { ${Oe} }`:""}
|
|
1008
1008
|
${t?`milestone { ${mr} }`:""}
|
|
1009
1009
|
${e?`headPipeline { ${yo} }`:""}
|
|
1010
|
-
`,_=s=>`${s.namespace}/${s.name}`,Po=s=>`${s.namespace}/${s.name}`,wo=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),qo=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),ir=s=>({id:s.id.replace(Pe,""),graphQLId:s.id,namespace:dr(s.fullPath),name:cr(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:qo(s.userPermissions)}),vo=s=>({path:s.path,isDirectory:s.type==="tree"}),Eo={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},So={OPEN:"opened",MERGED:"merged",CLOSED:"closed"},qs=s=>{if(!s||s.length===0)return"state: opened";let t=Array.from(new Set(s));return t.length>1?"":`state: ${So[t[0]]}`},vs=s=>{if(!s||s.length===0)return"state: opened";let t=Array.from(new Set(s));return t.length>1?"":`state: ${t[0]==="CLOSED"?"closed":"opened"}`},ae=100,et=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,se=(s,t,e)=>{let r=et(s.avatarUrl,t,e);return{id:s.id.replace(Ss,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},hr=s=>({color:s.color,description:s.description,id:s.id.replace(Ro,""),graphQLId:s.id,name:s.title}),
|
|
1010
|
+
`,_=s=>`${s.namespace}/${s.name}`,Po=s=>`${s.namespace}/${s.name}`,wo=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),qo=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),ir=s=>({id:s.id.replace(Pe,""),graphQLId:s.id,namespace:dr(s.fullPath),name:cr(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:qo(s.userPermissions)}),vo=s=>({path:s.path,isDirectory:s.type==="tree"}),Eo={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},So={OPEN:"opened",MERGED:"merged",CLOSED:"closed"},qs=s=>{if(!s||s.length===0)return"state: opened";let t=Array.from(new Set(s));return t.length>1?"":`state: ${So[t[0]]}`},vs=s=>{if(!s||s.length===0)return"state: opened";let t=Array.from(new Set(s));return t.length>1?"":`state: ${t[0]==="CLOSED"?"closed":"opened"}`},ae=100,Co=20,Do=250,et=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,se=(s,t,e)=>{let r=et(s.avatarUrl,t,e);return{id:s.id.replace(Ss,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},hr=s=>({color:s.color,description:s.description,id:s.id.replace(Ro,""),graphQLId:s.id,name:s.title}),Ao=(s,t)=>s?s==="FAILED"&&t?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[s]:null,$o=(s,t,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:se(s,t,e),state:s.mergeRequestInteraction?.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},ar=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>$o(i,r,n)):null;return{id:s.id.replace(ho,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:Eo[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?se(s.author,r,n):null,createdDate:new Date(s.createdAt),isDraft:s.draft,repository:{id:t.id,graphQLId:t.graphQLId,name:t.name,owner:{login:t.namespace},remoteInfo:t.httpsUrl&&t.sshUrl?{cloneUrlHTTPS:t.httpsUrl,cloneUrlSSH:t.sshUrl}:null},isCrossRepository:e!=null&&e.id!==t.id,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:Ao(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(bo,"")}`}))??[])??[]},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=>se(i,r,n)):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:go[s.mergeStatusEnum],milestone:s.milestone?fr(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(hr)??[],permissions:null}},ur=(s,t,e,r)=>({author:se(s.author,e,r),assignees:s.assignees.nodes.map(n=>se(n,e,r)),commentCount:s.userNotesCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:s.description,graphQLId:s.id,id:s.id.replace(fo,""),labels:s.labels?.nodes?.map(hr)??[],number:s.iid,repository:{id:t.id.replace(Pe,""),graphQLId:t.id,name:t.name,owner:{login:t.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?fr(s.milestone,t.webUrl):null}),fr=(s,t)=>({id:s.id.replace(Io,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${t}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),Lo=s=>Buffer.from(JSON.stringify(s),"utf8").toString("base64"),Go=(s,t)=>{if(!s)return{page:1,perPage:t};try{let e=JSON.parse(Buffer.from(s,"base64").toString("utf8")),r=typeof e.page=="number"&&e.page>0?e.page:1,n=typeof e.perPage=="number"&&e.perPage>0?e.perPage:t;return{page:r,perPage:n}}catch{return{page:1,perPage:t}}},Uo=(s,t,e)=>({id:s.id.toString(),graphQLId:`${Ss}${s.id}`,name:s.name,username:s.username,email:s.email??null,avatarUrl:et(s.avatar_url,t,e),url:s.web_url}),Es=(s,t,e)=>({avatarUrl:et(s.avatar_url,t,e)??"",email:null,name:s.name}),To=s=>s?.new_line!=null?"RIGHT":s?.old_line!=null?"LEFT":null,Oo=s=>{let t=s.old_path||s.new_path,e=s.new_path||s.old_path,r=[`diff --git a/${t} b/${e}`];return s.new_file&&s.b_mode?r.push(`new file mode ${s.b_mode}`):s.deleted_file&&s.a_mode?r.push(`deleted file mode ${s.a_mode}`):s.a_mode&&s.b_mode&&s.a_mode!==s.b_mode&&(r.push(`old mode ${s.a_mode}`),r.push(`new mode ${s.b_mode}`)),s.renamed_file&&(r.push(`rename from ${s.old_path}`),r.push(`rename to ${s.new_path}`)),s.diff&&s.diff.length>0?(r.push(`--- ${s.new_file?"/dev/null":`a/${t}`}`),r.push(`+++ ${s.deleted_file?"/dev/null":`b/${e}`}`),`${r.join(`
|
|
1011
1011
|
`)}
|
|
1012
1012
|
${s.diff.endsWith(`
|
|
1013
1013
|
`)?s.diff:`${s.diff}
|
|
1014
1014
|
`}`):`${r.join(`
|
|
1015
1015
|
`)}
|
|
1016
|
-
`},Cs="|",pr=(s,t,e,r)=>[s,t,e.toString(),r.toString()].join(Cs),
|
|
1016
|
+
`},Cs="|",pr=(s,t,e,r)=>[s,t,e.toString(),r.toString()].join(Cs),_o=s=>{let t=s.split(Cs);if(t.length!==4)throw new Error("Invalid GitLab comment ID format \u2014 expected a composite ID produced by getCommentsForPullRequest or addInlineCommentToPullRequest.");return{namespace:t[0],name:t[1],mergeRequestIid:t[2],noteId:t[3]}},lr=(s,t,e,r)=>({author:s.author?Uo(s.author,t,e):null,body:s.body,createdAt:s.created_at?new Date(s.created_at):null,id:pr(r.namespace,r.name,r.mergeRequestIid,s.id),url:""}),we=class extends Q{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){let n=(await E(this.config,{query:`
|
|
1017
1017
|
query getCurrentUser {
|
|
1018
1018
|
currentUser {
|
|
1019
1019
|
${re}
|
|
@@ -1085,7 +1085,7 @@ query getRepo($fullPath: ID!) {
|
|
|
1085
1085
|
query batchGetRepos {
|
|
1086
1086
|
${n}
|
|
1087
1087
|
}
|
|
1088
|
-
`},e);if(!o.body.data)throw new Error(
|
|
1088
|
+
`},e);if(!o.body.data)throw new Error(Ue(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let p=o.body.data[`getRepo_${l}`];p?i.push(ir(p)):a.push({input:u})}),{data:i,errors:a}}async getRepos(t,e={}){let r=[];for(let i=0;i<t.length;i+=15)r.push(t.slice(i,i+15));return(await Promise.all(r.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(t,e={}){let r=await E(this.config,{query:`
|
|
1089
1089
|
query getReposForCurrentUser($after: String) {
|
|
1090
1090
|
projects(membership: true first: 100 after: $after) {
|
|
1091
1091
|
pageInfo {
|
|
@@ -1097,7 +1097,7 @@ query getReposForCurrentUser($after: String) {
|
|
|
1097
1097
|
}
|
|
1098
1098
|
}
|
|
1099
1099
|
}
|
|
1100
|
-
`,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(
|
|
1100
|
+
`,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(Ue(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(ir)}}async getGroupsForCurrentUser(t={},e={}){let r=new URL(`${G(this.config,e)}/groups`);r.searchParams.set("top_level_only",(t.topLevelOnly??!0).toString()),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("per_page",$.toString());let n=await this.config.request({url:r.toString(),headers:R(e.token||this.config.token)});return{pageInfo:ws(n.headers),data:n.body.map(o=>({id:o.id.toString(),path:o.path,fullPath:o.full_path,name:o.name,webUrl:o.web_url}))}}async getRefs(t,e,r={}){let n=_(e.repo),o=new URL(`${G(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",$.toString());let i=await this.config.request({url:o.toString(),headers:R(r.token||this.config.token)});return{pageInfo:ws(i.headers),data:i.body.map(a=>({name:a.name,commit:{oid:a.commit.id,authoredDate:new Date(a.commit.authored_date),committedDate:new Date(a.commit.committed_date)}}))}}async getBranches(t,e={}){return this.getRefs("branches",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getBlame(t,e={}){let r=_(t.repo),n=new URL(`${G(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/blame`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(t,e={}){let r="";t.repo?.id?r=`projectId:"${t.repo.id}"`:t.repo?.namespace&&t.repo?.name&&(r=`projectPath:"${t.repo.namespace}/${t.repo.name}"`);let n=mo[t.association],o=qs(t.states),i=L(t.pageSize,{fallback:ae,max:ae}),a=await E(this.config,{query:`
|
|
1101
1101
|
query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
|
|
1102
1102
|
user(username: $username) {
|
|
1103
1103
|
${n}(${o} first: ${i} after:$cursor labels: $labelNames${r?` ${r}`:""}) {
|
|
@@ -1111,7 +1111,7 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
|
|
|
1111
1111
|
}
|
|
1112
1112
|
}
|
|
1113
1113
|
}
|
|
1114
|
-
`,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!a.body.data)throw new Error(
|
|
1114
|
+
`,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!a.body.data)throw new Error(Ue(a.body.errors)||a.statusText||"Unknown error");if(!a.body.data.user)throw new Error("User not found");let u=a.body.data.user[n];if(!u)throw new Error("Unexpected response");let l=u.nodes?.filter(p=>t.includeFromArchivedRepos||!p.project.archived).map(p=>ar(p,Te(p.project),p.sourceProject?Te(p.sourceProject):null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[];return{pageInfo:u.pageInfo,data:x(l,t.states)}}async getPullRequestsAssociatedWithUser(t,e={}){let[r,n,o]=t.cursor?.split(";")||[void 0,void 0,void 0],i=r?.split("-")||[],a=n?.split("-")||[],u=o?.split("-")||[],l=[],p=[],d=[],c=0;do{let D=t.repos&&t.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:i[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...D&&{repo:D}},e)),a[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...D&&{repo:D}},e)),u[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...D&&{repo:D}},e)),c++}while(c<(t.repos?.length||0));let g=[l,p,d].flat(),m=await Promise.all(g),h={},y=[],f=D=>{h[D.id]||(h[D.id]=!0,y.push(D))},P=!1,A=m.map((D,w)=>{let S="";return D&&D.data.forEach(f),D?.pageInfo.hasNextPage?(P=!0,S+=`${D.pageInfo.endCursor||"null"}`):S+="null",t.repos?.length&&(w+1)%t.repos.length!==0?S+="-":w+1<m.length&&(S+=";"),S}).join("");return{pageInfo:{hasNextPage:P,endCursor:A},data:y}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=t||{},u={},l=[],p=[],d=(c,g,m)=>{l.push(`$${c}: ${m}`),p.push(`${c}: $${c}`),u[c]=g};return e&&d("updatedBefore",e,"Time"),n&&d("authorUsername",n,"String"),o&&o.length&&(o.length===1?d("assigneeUsername",o[0],"String"):d("assigneeUsernames",o,"[String!]")),i&&d("labelName",i,"[String]"),r!=null&&d("draft",r,"Boolean"),a&&d("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:p}}async getPullRequestsForRepoBase(t,e={},r){let{cursor:n,repo:o}=t||{},i=_(o),a=qs(t.states),u=L(t.pageSize,{fallback:ae,max:ae}),{variables:l,variableTypes:p,mergeRequestArguments:d}=this.getVariablesForPullRequests(t),c={fullPath:i,...l},g=await E(this.config,{query:`
|
|
1115
1115
|
query getPullRequestsForRepo(
|
|
1116
1116
|
$fullPath: ID!
|
|
1117
1117
|
$after: String
|
|
@@ -1347,7 +1347,7 @@ query getLabelsForRepo(
|
|
|
1347
1347
|
}
|
|
1348
1348
|
}
|
|
1349
1349
|
}
|
|
1350
|
-
`,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(hr)??[]}}async getTreeForRepo(t,e={}){let r=_(t.repo),n=new URL(t.cursor??`${
|
|
1350
|
+
`,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(hr)??[]}}async getTreeForRepo(t,e={}){let r=_(t.repo),n=new URL(t.cursor??`${G(this.config,e)}/projects/${encodeURIComponent(r)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",t.branch);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(vo),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(t,e={}){let r=_(t.repo),o=(await E(this.config,{query:`
|
|
1351
1351
|
query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
|
|
1352
1352
|
project(fullPath: $fullPath) {
|
|
1353
1353
|
${Oe}
|
|
@@ -1360,15 +1360,15 @@ query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
|
|
|
1360
1360
|
}
|
|
1361
1361
|
}
|
|
1362
1362
|
}
|
|
1363
|
-
`,variables:{fullPath:r,iid:t.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=Te(o),u=i.sourceProject?Te(i.sourceProject):null;return{data:ar(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(t,e,r){let n=_(t);return`${U(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${e}`}async getPullRequestDescription(t,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(t.repo,t.number,e),headers:R(e.token||this.config.token)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(t,e={}){return{data:{description:(await this.config.request({method:"PUT",url:this.getMergeRequestUrl(t.repo,t.number,e),headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({description:t.description})})).body?.description??t.description}}}async getFileContents(t,e={}){let r=_(t.repo),n=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/raw`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(t,e={}){let r=_(t.repo),{page:n,perPage:o}=$o(t.cursor,$),i=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/merge_requests/${t.pullRequestNumber}/notes`);i.searchParams.set("page",n.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:R(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,p={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestNumber},d=a.body.filter(m=>!m.system&&!m.position).map(m=>lr(m,u,l,p)),c=!!a.headers["x-next-page"],g=c?Ao({page:n+1,perPage:o}):null;return{data:d,pageInfo:{endCursor:g,hasNextPage:c}}}async getReviewsForPullRequest(t,e={}){let r=_(t.repo),n=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=R(e.token||this.config.token),a=U(this.config,e),u=encodeURIComponent(r),[l,p]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${t.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(r,t.pullRequestId,e)]),d=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let h=Es(m,n,o),y=`approval-${m.id}`;return{author:h,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),c={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestId},g=p.filter(m=>m.notes.some(h=>!h.system&&!!h.position)).map(m=>{let h=m.notes.filter(w=>!w.system),f=h.filter(w=>!!w.position)[0];if(!f)return null;let P=h.filter(w=>w.id!==f.id).map(w=>lr(w,n,o,c)),A={...lr(f,n,o,c),diffLines:[],filename:f.position?.new_path??f.position?.old_path??"",line:f.position?.new_line??f.position?.old_line??null,startLine:f.position?.line_range?.start?.new_line??null,side:Uo(f.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:P};return{author:f.author?Es(f.author,n,o):null,body:f.body??"",createdAt:f.created_at?new Date(f.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[A],url:""}}).filter(m=>m!==null);return{data:[...d,...g]}}async getPullRequestDiff(t,e={}){let r=_(t.repo),n=encodeURIComponent(r),o=U(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${n}/merge_requests/${t.pullRequestId}/diffs`,e)).map(Go).join("")}async getMergeBase(t,e={}){let r=_(t.repo),n=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/merge_base`);n.searchParams.append("refs[]",t.base),n.searchParams.append("refs[]",t.head);let i=(await this.config.request({url:n.toString(),headers:R(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(t,e,r){let n=U(this.config,r),o=encodeURIComponent(t);return this.fetchAllPagedGitLabREST(`${n}/projects/${o}/merge_requests/${e}/discussions`,r)}async fetchAllPagedGitLabREST(t,e){let r=R(e.token||this.config.token),n=[],o=1,i=50;for(;o<=i;){let a=new URL(t);a.searchParams.set("page",o.toString()),a.searchParams.set("per_page",$.toString());let u=await this.config.request({url:a.toString(),headers:r});n.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 n}async addCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`,i=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:n})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n,path:o,line:i,side:a="RIGHT",threadId:u}=t;if(!n?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${r.repository.owner.login}/${r.repository.name}`,p=encodeURIComponent(l),d=U(this.config,e),c={...R(e.token||this.config.token),"Content-Type":"application/json"};if(u){let P=await this.config.request({method:"POST",url:`${d}/projects/${p}/merge_requests/${r.number}/discussions/${encodeURIComponent(u)}/notes`,headers:c,body:JSON.stringify({body:n})});return P.body?.id!=null?pr(r.repository.owner.login,r.repository.name,r.number,P.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:`${d}/projects/${p}/merge_requests/${r.number}`,headers:R(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 h={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"?h.new_line=i:h.old_line=i;let f=(await this.config.request({method:"POST",url:`${d}/projects/${p}/merge_requests/${r.number}/discussions`,headers:c,body:JSON.stringify({body:n,position:h})})).body?.notes?.[0]?.id;return f!=null?pr(r.repository.owner.login,r.repository.name,r.number,f):void 0}getNoteUrl(t,e){if(!t)throw new Error('GitLab requires "commentId" for this function.');let{namespace:r,name:n,mergeRequestIid:o,noteId:i}=To(t);return`${U(this.config,e)}/projects/${encodeURIComponent(`${r}/${n}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(t,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(t,e),headers:R(e.token||this.config.token)})}async deleteComment(t,e={}){await this.deleteNote(t.commentId,e)}async deleteInlineComment(t,e={}){await this.deleteNote(t.commentId,e)}async editNote(t,e,r){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(t,r),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async editInlineComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async resolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!0,e)}async unresolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!1,e)}async setReviewThreadResolved(t,e,r){if(!t.repo||t.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!t.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let n=_(t.repo),o=new URL(`${U(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${t.pullRequestNumber}/discussions/${encodeURIComponent(t.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:R(r.token||this.config.token)})}async approvePullRequest(t,e={}){let{pullRequest:r,comment:n}=t,o=`${r.repository.owner.login}/${r.repository.name}`,i=U(this.config,e),a=encodeURIComponent(o),u=R(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${r.number}/approve`,method:"POST",headers:u}),n&&n.trim()!==""&&await this.postMergeRequestNote(o,r.number,n,e)}async commentOnPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;await this.postMergeRequestNote(o,r.number,n,e)}async requestPullRequestChanges(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;if(!await this.tryRequestChangesMutation(o,r.number,e)){let u=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}`,l=R(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,r.number,n,e)}async tryRequestChangesMutation(t,e,r){let n=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
|
|
1363
|
+
`,variables:{fullPath:r,iid:t.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=Te(o),u=i.sourceProject?Te(i.sourceProject):null;return{data:ar(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(t,e,r){let n=_(t);return`${G(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${e}`}async getPullRequestDescription(t,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(t.repo,t.number,e),headers:R(e.token||this.config.token)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(t,e={}){return{data:{description:(await this.config.request({method:"PUT",url:this.getMergeRequestUrl(t.repo,t.number,e),headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({description:t.description})})).body?.description??t.description}}}async getFileContents(t,e={}){let r=_(t.repo),n=new URL(`${G(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/raw`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(t,e={}){let r=_(t.repo),{page:n,perPage:o}=Go(t.cursor,$),i=new URL(`${G(this.config,e)}/projects/${encodeURIComponent(r)}/merge_requests/${t.pullRequestNumber}/notes`);i.searchParams.set("page",n.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:R(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,p={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestNumber},d=a.body.filter(m=>!m.system&&!m.position).map(m=>lr(m,u,l,p)),c=!!a.headers["x-next-page"],g=c?Lo({page:n+1,perPage:o}):null;return{data:d,pageInfo:{endCursor:g,hasNextPage:c}}}async getReviewsForPullRequest(t,e={}){let r=_(t.repo),n=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=R(e.token||this.config.token),a=G(this.config,e),u=encodeURIComponent(r),[l,p]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${t.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(r,t.pullRequestId,e)]),d=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let h=Es(m,n,o),y=`approval-${m.id}`;return{author:h,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),c={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestId},g=p.filter(m=>m.notes.some(h=>!h.system&&!!h.position)).map(m=>{let h=m.notes.filter(w=>!w.system),f=h.filter(w=>!!w.position)[0];if(!f)return null;let P=h.filter(w=>w.id!==f.id).map(w=>lr(w,n,o,c)),A={...lr(f,n,o,c),diffLines:[],filename:f.position?.new_path??f.position?.old_path??"",line:f.position?.new_line??f.position?.old_line??null,startLine:f.position?.line_range?.start?.new_line??null,side:To(f.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:P};return{author:f.author?Es(f.author,n,o):null,body:f.body??"",createdAt:f.created_at?new Date(f.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[A],url:""}}).filter(m=>m!==null);return{data:[...d,...g]}}async getPullRequestDiff(t,e={}){let r=_(t.repo),n=encodeURIComponent(r),o=G(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${n}/merge_requests/${t.pullRequestId}/diffs`,e,{perPage:Co,maxPages:Do})).map(Oo).join("")}async getMergeBase(t,e={}){let r=_(t.repo),n=new URL(`${G(this.config,e)}/projects/${encodeURIComponent(r)}/repository/merge_base`);n.searchParams.append("refs[]",t.base),n.searchParams.append("refs[]",t.head);let i=(await this.config.request({url:n.toString(),headers:R(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(t,e,r){let n=G(this.config,r),o=encodeURIComponent(t);return this.fetchAllPagedGitLabREST(`${n}/projects/${o}/merge_requests/${e}/discussions`,r)}async fetchAllPagedGitLabREST(t,e,{perPage:r=$,maxPages:n=50}={}){let o=R(e.token||this.config.token),i=[],a=1;for(;a<=n;){let u=new URL(t);u.searchParams.set("page",a.toString()),u.searchParams.set("per_page",r.toString());let l=await this.config.request({url:u.toString(),headers:o});i.push(...l.body);let p=l.headers["x-next-page"];if(!p)break;let d=parseInt(`${p}`,10);if(Number.isNaN(d)||d<=a)break;a=d}return i}async addCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`,i=`${G(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:n})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n,path:o,line:i,side:a="RIGHT",threadId:u}=t;if(!n?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${r.repository.owner.login}/${r.repository.name}`,p=encodeURIComponent(l),d=G(this.config,e),c={...R(e.token||this.config.token),"Content-Type":"application/json"};if(u){let P=await this.config.request({method:"POST",url:`${d}/projects/${p}/merge_requests/${r.number}/discussions/${encodeURIComponent(u)}/notes`,headers:c,body:JSON.stringify({body:n})});return P.body?.id!=null?pr(r.repository.owner.login,r.repository.name,r.number,P.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:`${d}/projects/${p}/merge_requests/${r.number}`,headers:R(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 h={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"?h.new_line=i:h.old_line=i;let f=(await this.config.request({method:"POST",url:`${d}/projects/${p}/merge_requests/${r.number}/discussions`,headers:c,body:JSON.stringify({body:n,position:h})})).body?.notes?.[0]?.id;return f!=null?pr(r.repository.owner.login,r.repository.name,r.number,f):void 0}getNoteUrl(t,e){if(!t)throw new Error('GitLab requires "commentId" for this function.');let{namespace:r,name:n,mergeRequestIid:o,noteId:i}=_o(t);return`${G(this.config,e)}/projects/${encodeURIComponent(`${r}/${n}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(t,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(t,e),headers:R(e.token||this.config.token)})}async deleteComment(t,e={}){await this.deleteNote(t.commentId,e)}async deleteInlineComment(t,e={}){await this.deleteNote(t.commentId,e)}async editNote(t,e,r){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(t,r),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async editInlineComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async resolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!0,e)}async unresolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!1,e)}async setReviewThreadResolved(t,e,r){if(!t.repo||t.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!t.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let n=_(t.repo),o=new URL(`${G(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${t.pullRequestNumber}/discussions/${encodeURIComponent(t.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:R(r.token||this.config.token)})}async approvePullRequest(t,e={}){let{pullRequest:r,comment:n}=t,o=`${r.repository.owner.login}/${r.repository.name}`,i=G(this.config,e),a=encodeURIComponent(o),u=R(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${r.number}/approve`,method:"POST",headers:u}),n&&n.trim()!==""&&await this.postMergeRequestNote(o,r.number,n,e)}async commentOnPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;await this.postMergeRequestNote(o,r.number,n,e)}async requestPullRequestChanges(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;if(!await this.tryRequestChangesMutation(o,r.number,e)){let u=`${G(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}`,l=R(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,r.number,n,e)}async tryRequestChangesMutation(t,e,r){let n=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
|
|
1364
1364
|
mergeRequestRequestChanges(input: { projectPath: $fullPath, iid: $pullRequestId }) {
|
|
1365
1365
|
errors
|
|
1366
1366
|
mergeRequest {
|
|
1367
1367
|
id
|
|
1368
1368
|
}
|
|
1369
1369
|
}
|
|
1370
|
-
}`,o=await E(this.config,{query:n,variables:{fullPath:t,pullRequestId:e.toString()}},r),i=o.body.errors;if(i?.length){if(i.some(wo))return!1;throw new Error(`Could not request pull request changes: ${
|
|
1371
|
-
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?$s:As,c=new URL(`${ue(s,r,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",tt.toString()),c.searchParams.set("fields",Rr.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:R(r.token||s.token)}),m=g.body.issues.map(f=>Ir(f,a,e,o)),h=!1,y="";return p?(h=m.length==tt,y=(parseInt(n??"0",10)+m.length).toString()):(h=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:h,endCursor:y}}},Ls=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=L(t?.pageSize,{fallback:tt,max:tt}),l=[...Rr],p=a?.Sprint;p&&l.push(p);let d=!o,c=d?$s:As,g=new URL(`${ue(s,r,o)}${c}`);g.searchParams.set("jql",i.join(" AND ")),g.searchParams.set("maxResults",u.toString()),g.searchParams.set("fields",l.join(",")),g.searchParams.set("expand","transitions"),n&&(d?g.searchParams.set("startAt",n):g.searchParams.set("nextPageToken",n));let m=await s.request({url:g.toString(),headers:R(r.token||s.token)}),h=m.body.issues.map(P=>Ir(P,a,e,o)),y=!1,f="";if(d){let P=parseInt(n??"0",10),v=typeof m.body.startAt=="number"?m.body.startAt:Number.isNaN(P)?0:P,A=m.body.total;y=typeof A=="number"?v+h.length<A:h.length===u,f=(v+h.length).toString()}else y=!!m.body.nextPageToken,f=m.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},it=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=t||{},c=[`project = "${l}"`],g=Ds(t.states);return g&&c.push(g),o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(m=>c.push(`labels = "${m}"`)),Ls(s,{resourceId:p,jql:c,cursor:u,fields:d,pageSize:t.pageSize},e,r)},at=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=t||{},g=["("+l.map(h=>`project = "${h}"`).join(" OR ")+")"],m=Ds(t.states);return m&&g.push(m),o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(h=>g.push(`labels = "${h}"`)),Ls(s,{resourceId:p,jql:g,fields:d,cursor:u,pageSize:t.pageSize},e,r)},ut=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${ue(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},lt=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${ue(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},pt=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${ue(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},dt=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${ue(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:R(e.token||s.token)})).body}};var _e="https://api.atlassian.com/ex/jira",br=100,qe=class extends M{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await st(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||_e}/${e.resourceId}/rest/api/2/myself`,headers:R(r.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||_e}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",br.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,r={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await jr(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},r))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||_e}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",br.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>rt(p,a,!1))}}async getComponentsForJiraProject(e,r={}){return await dt(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await nt(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await it(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await at(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await ot(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await pt(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${r.baseUrl||_e}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await lt(this.config,e,r)}async setIssueLabels(e,r={}){await ut(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||_e}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",br.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var ve=class extends Q{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await st(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:R(e?.token||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:R(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await nt(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await it(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await at(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await ot(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await pt(this.config,e,r)}async setIssueLabels(e,r={}){await ut(this.config,e,r)}async setIssueComponents(e,r={}){await lt(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:R(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await dt(this.config,e,r)}};var Pr=100,ct=class{constructor(){this.set=new Set;this.arr=[]}push(...t){let e=t.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}},ne=async(s,t,e,r)=>{let n=t.token||s.token;if(!n)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},yr=s=>s?s instanceof Date?s:new Date(s):null,Qo=`
|
|
1370
|
+
}`,o=await E(this.config,{query:n,variables:{fullPath:t,pullRequestId:e.toString()}},r),i=o.body.errors;if(i?.length){if(i.some(wo))return!1;throw new Error(`Could not request pull request changes: ${Ue(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(t,e,r,n){let o=G(this.config,n),i=encodeURIComponent(t),a=R(n.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:r})})}};var ko="https://api.atlassian.com/ex/jira",tt=100,Ds=s=>{if(!s||s.length===0)return"statusCategory != Done";let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?null:r?"statusCategory = Done":"statusCategory != Done"},Rr=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],As="/rest/api/2/search/jql",$s="/rest/api/2/search",Ir=(s,t,e,r)=>{let n=s.fields.assignee,o=!r,i=(s.fields[t?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:s.id,commentCount:s.fields.comment.comments.length,number:s.key,title:s.fields.summary,url:e?`${e}/browse/${s.key}`:null,closedDate:null,createdDate:new Date(s.fields.created),author:rt(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[rt(n,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:r??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:jo(s.fields.status),statusTransitions:s.transitions?.map(xo)??[],components:s.fields.components?.map(No)??[],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(Qo),fixVersions:s.fields.fixVersions.map(Fo)}},xo=s=>{let t;switch(s.to.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:t}}},No=s=>({description:s.description??null,id:s.id,name:s.name}),Bo=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,rt=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:Bo(s,t,e)}),jo=s=>{let t;switch(s.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:t}},Qo=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}),Fo=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),ue=(s,t,e)=>e?`${t.baseUrl||ko}/${e}`:`${t?.baseUrl||s.baseUrl}`,st=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${ue(s,e,r)}/rest/api/2/field`,headers:R(e.token||s.token)})).body},nt=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${ue(s,r,o)}/rest/api/2/issue/${n}?fields=${Rr.join(",")}&expand=transitions`,headers:R(r.token||s.token)});return{data:Ir(a.body,i,e,o)}},ot=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
|
|
1371
|
+
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,d=p?$s:As,c=new URL(`${ue(s,r,o)}${d}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",tt.toString()),c.searchParams.set("fields",Rr.join(",")),c.searchParams.set("expand","transitions"),n&&(p?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:R(r.token||s.token)}),m=g.body.issues.map(f=>Ir(f,a,e,o)),h=!1,y="";return p?(h=m.length==tt,y=(parseInt(n??"0",10)+m.length).toString()):(h=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:h,endCursor:y}}},Ls=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=L(t?.pageSize,{fallback:tt,max:tt}),l=[...Rr],p=a?.Sprint;p&&l.push(p);let d=!o,c=d?$s:As,g=new URL(`${ue(s,r,o)}${c}`);g.searchParams.set("jql",i.join(" AND ")),g.searchParams.set("maxResults",u.toString()),g.searchParams.set("fields",l.join(",")),g.searchParams.set("expand","transitions"),n&&(d?g.searchParams.set("startAt",n):g.searchParams.set("nextPageToken",n));let m=await s.request({url:g.toString(),headers:R(r.token||s.token)}),h=m.body.issues.map(P=>Ir(P,a,e,o)),y=!1,f="";if(d){let P=parseInt(n??"0",10),v=typeof m.body.startAt=="number"?m.body.startAt:Number.isNaN(P)?0:P,A=m.body.total;y=typeof A=="number"?v+h.length<A:h.length===u,f=(v+h.length).toString()}else y=!!m.body.nextPageToken,f=m.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},it=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:d}=t||{},c=[`project = "${l}"`],g=Ds(t.states);return g&&c.push(g),o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(m=>c.push(`labels = "${m}"`)),Ls(s,{resourceId:p,jql:c,cursor:u,fields:d,pageSize:t.pageSize},e,r)},at=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:d}=t||{},g=["("+l.map(h=>`project = "${h}"`).join(" OR ")+")"],m=Ds(t.states);return m&&g.push(m),o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(h=>g.push(`labels = "${h}"`)),Ls(s,{resourceId:p,jql:g,fields:d,cursor:u,pageSize:t.pageSize},e,r)},ut=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${ue(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},lt=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${ue(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},pt=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${ue(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},dt=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${ue(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:R(e.token||s.token)})).body}};var _e="https://api.atlassian.com/ex/jira",br=100,qe=class extends M{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await st(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||_e}/${e.resourceId}/rest/api/2/myself`,headers:R(r.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||_e}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",br.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,r={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await jr(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},r))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||_e}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",br.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>rt(p,a,!1))}}async getComponentsForJiraProject(e,r={}){return await dt(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await nt(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await it(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await at(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await ot(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await pt(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${r.baseUrl||_e}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await lt(this.config,e,r)}async setIssueLabels(e,r={}){await ut(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||_e}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",br.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var ve=class extends Q{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await st(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:R(e?.token||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:R(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await nt(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await it(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await at(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await ot(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await pt(this.config,e,r)}async setIssueLabels(e,r={}){await ut(this.config,e,r)}async setIssueComponents(e,r={}){await lt(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:R(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await dt(this.config,e,r)}};var Pr=100,ct=class{constructor(){this.set=new Set;this.arr=[]}push(...t){let e=t.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}},ne=async(s,t,e,r)=>{let n=t.token||s.token;if(!n)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},yr=s=>s?s instanceof Date?s:new Date(s):null,zo=`
|
|
1372
1372
|
id
|
|
1373
1373
|
name
|
|
1374
1374
|
description
|
|
@@ -1376,11 +1376,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1376
1376
|
startDate
|
|
1377
1377
|
targetDate
|
|
1378
1378
|
url
|
|
1379
|
-
`,
|
|
1379
|
+
`,Gs=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:yr(s.startDate),targetDate:yr(s.targetDate),url:s.url}),Us=async(s,t,e)=>{let r=`
|
|
1380
1380
|
query GetProjects($first: Int!, $after: String) {
|
|
1381
1381
|
projects(first: $first, after: $after) {
|
|
1382
1382
|
nodes {
|
|
1383
|
-
${
|
|
1383
|
+
${zo}
|
|
1384
1384
|
}
|
|
1385
1385
|
pageInfo {
|
|
1386
1386
|
hasNextPage
|
|
@@ -1388,7 +1388,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1388
1388
|
}
|
|
1389
1389
|
}
|
|
1390
1390
|
}
|
|
1391
|
-
`;return(await ne(s,t,r,{first:Pr,after:e})).projects},
|
|
1391
|
+
`;return(await ne(s,t,r,{first:Pr,after:e})).projects},Mo=`
|
|
1392
1392
|
id
|
|
1393
1393
|
name
|
|
1394
1394
|
number
|
|
@@ -1400,7 +1400,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1400
1400
|
query GetCycles($first: Int!, $after: String) {
|
|
1401
1401
|
cycles(first: $first, after: $after) {
|
|
1402
1402
|
nodes {
|
|
1403
|
-
${
|
|
1403
|
+
${Mo}
|
|
1404
1404
|
}
|
|
1405
1405
|
pageInfo {
|
|
1406
1406
|
hasNextPage
|
|
@@ -1408,7 +1408,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1408
1408
|
}
|
|
1409
1409
|
}
|
|
1410
1410
|
}
|
|
1411
|
-
`;return(await ne(s,t,r,{first:Pr,after:e})).cycles},
|
|
1411
|
+
`;return(await ne(s,t,r,{first:Pr,after:e})).cycles},Wo=`
|
|
1412
1412
|
id
|
|
1413
1413
|
name
|
|
1414
1414
|
color
|
|
@@ -1417,7 +1417,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1417
1417
|
query GetLabels($first: Int!, $after: String) {
|
|
1418
1418
|
projectLabels(first: $first, after: $after) {
|
|
1419
1419
|
nodes {
|
|
1420
|
-
${
|
|
1420
|
+
${Wo}
|
|
1421
1421
|
}
|
|
1422
1422
|
pageInfo {
|
|
1423
1423
|
hasNextPage
|
|
@@ -1430,26 +1430,26 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1430
1430
|
name
|
|
1431
1431
|
key
|
|
1432
1432
|
icon
|
|
1433
|
-
`;function
|
|
1433
|
+
`;function Ho(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var js=`
|
|
1434
1434
|
id
|
|
1435
1435
|
name
|
|
1436
1436
|
avatarUrl
|
|
1437
|
-
`;function Qs(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var
|
|
1437
|
+
`;function Qs(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var Vo=`
|
|
1438
1438
|
id
|
|
1439
1439
|
name
|
|
1440
|
-
`;function
|
|
1440
|
+
`;function Jo(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var Ko=`
|
|
1441
1441
|
id
|
|
1442
1442
|
sortOrder
|
|
1443
1443
|
name
|
|
1444
1444
|
description
|
|
1445
1445
|
status
|
|
1446
1446
|
targetDate
|
|
1447
|
-
`;function
|
|
1447
|
+
`;function Xo(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:gt(s.targetDate)}:null}function Zo(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Yo=`
|
|
1448
1448
|
id
|
|
1449
1449
|
name
|
|
1450
1450
|
color
|
|
1451
1451
|
type
|
|
1452
|
-
`;function
|
|
1452
|
+
`;function ei(s){return s?{id:s.id,name:s.name,color:s.color,category:Zo(s.type)}:null}var qr=`
|
|
1453
1453
|
creator {
|
|
1454
1454
|
${js}
|
|
1455
1455
|
}
|
|
@@ -1462,21 +1462,21 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1462
1462
|
id
|
|
1463
1463
|
identifier
|
|
1464
1464
|
project {
|
|
1465
|
-
${
|
|
1465
|
+
${Vo}
|
|
1466
1466
|
}
|
|
1467
1467
|
team {
|
|
1468
1468
|
${Fs}
|
|
1469
1469
|
}
|
|
1470
1470
|
state {
|
|
1471
|
-
${
|
|
1471
|
+
${Yo}
|
|
1472
1472
|
}
|
|
1473
1473
|
title
|
|
1474
1474
|
updatedAt
|
|
1475
1475
|
url
|
|
1476
1476
|
projectMilestone {
|
|
1477
|
-
${
|
|
1477
|
+
${Ko}
|
|
1478
1478
|
}
|
|
1479
|
-
`;async function wr(s){return{author:Qs(await s.creator),assignees:[Qs(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:gt(s.archivedAt),createdDate:gt(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:
|
|
1479
|
+
`;async function wr(s){return{author:Qs(await s.creator),assignees:[Qs(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:gt(s.archivedAt),createdDate:gt(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:Jo(await s.project,await s.team),state:ei(await s.state),title:s.title,type:null,updatedDate:gt(s.updatedAt),upvoteCount:null,url:s.url,milestone:Xo(await s.projectMilestone)}}var mt=`
|
|
1480
1480
|
nodes {
|
|
1481
1481
|
${qr}
|
|
1482
1482
|
}
|
|
@@ -1515,7 +1515,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1515
1515
|
displayName
|
|
1516
1516
|
}
|
|
1517
1517
|
}
|
|
1518
|
-
`;return(await ne(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await wr(r)}}async getLinearOrganization(t={}){let e=await this.fetchOrganization(t);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(t={}){return{data:(await this.fetchTeams(t)).nodes.map(
|
|
1518
|
+
`;return(await ne(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await wr(r)}}async getLinearOrganization(t={}){let e=await this.fetchOrganization(t);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(t={}){return{data:(await this.fetchTeams(t)).nodes.map(Ho)}}async getProjects(t={},e={}){let r=await Us(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Gs),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await Os(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Ts),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await ks(this.config,e,t.cursor??void 0);return{data:r.nodes.map(_s),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCurrentUser(t={}){return{data:await this.fetchViewer(t)}}async getIssuesForCurrentUser(t,e={}){let{cursor:r}=t,{category:n,cursor:o}=Ns(r),i=await this.fetchViewer(e),a,u,l=new ct,p=async(d,c)=>{if(u||n>d)return;let g=await c(Math.max(Bs-l.length,1),n===d?o:void 0);if(!g)return;let m=await kt(g.nodes.map(wr));l.push(...m),g.pageInfo.hasNextPage&&(a=d,u=g.pageInfo.endCursor)};return await p(1,async(d,c)=>(await this.rawRequest(e,`
|
|
1519
1519
|
query GetAssignedIssues($first: Int!, $after: String) {
|
|
1520
1520
|
viewer {
|
|
1521
1521
|
issues: assignedIssues(first: $first, after: $after) {
|
|
@@ -1593,4 +1593,4 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1593
1593
|
${mt}
|
|
1594
1594
|
}
|
|
1595
1595
|
}
|
|
1596
|
-
`,d=(await this.rawRequest(e,l,{first:Bs,after:i})).data?.issues;return d?{data:await kt(d.nodes.map(wr)),pageInfo:{hasNextPage:d.pageInfo.hasNextPage,endCursor:d.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var Z="https://api.trello.com",Yo=1e3,Y=(s,t)=>({...R(t),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${t}"`}),ei=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),ti=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},Se=class extends M{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||Z}/1/members/me`,headers:Y(t.appKey,e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/members/me/boards?fields=name&filter=open`,headers:Y(t.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/lists`,headers:Y(r,e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||Z}/1/members/${n}`,headers:Y(r,e.token||this.config.token)});return{data:ei(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/members`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(c=>r.push(`label:"${c}"`));let p=`${i?`${i}`:""}${r.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/search?query=${p}&cards_limit=${Yo}&card_members=true`,headers:Y(n,e.token||this.config.token)})).body.cards.map(c=>ti(c,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||Z}/1/cards/${e.id}?${r}`,headers:Y(t,n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:o}=t;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:o}=t,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(t,e={}){let{appKey:r,issue:n,labels:o}=t,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(t,e={}){let{appKey:r,issue:n,archived:o}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?closed=${o}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/labels`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var ht={};H(ht,{default:()=>ri});var ri={};var ft={};H(ft,{default:()=>si});var si={};var Dt={};H(Dt,{decode:()=>vr,decodeV0:()=>ai,encode:()=>ii,validate:()=>oi});var B=(e=>(e.Zero="0",e.One="1",e))(B||{}),j=(e=>(e.PullRequest="pr",e.Issue="issue",e))(j||{}),N=(c=>(c.Azure="azure",c.AzureDevOpsServer="azureDevOpsServer",c.Github="github",c.GithubEnterprise="githubEnterprise",c.Gitlab="gitlab",c.GitlabSelfHosted="gitlabSelfHosted",c.Bitbucket="bitbucket",c.BitbucketServer="bitbucketServer",c.Jira="jira",c.JiraServer="jiraServer",c.Linear="linear",c.Trello="trello",c))(N||{});var Rt=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var It=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var bt=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var yt=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var Pt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var wt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var qt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var vt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Et=class{constructor(){}validate(t){if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.projectId||!t.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider=="jira"?(e.push(""),e.push(t.resourceId)):(e.push(t.domain),e.push("")),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:t[4]==""?null:t[4],accountOrOrgId:null,organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var St=class{constructor(){}validate(t){if(!t.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.accountOrOrgId||!t.projectId||!t.entityId)throw new Error("Missing required fields for Trello issue uniqueId");let e=[];return e.push("trello"),e.push("issue"),e.push("1"),e.push(""),e.push(t.accountOrOrgId),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:t[4],organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var Ct=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new It:new Rt;case"bitbucket":case"bitbucketServer":return t==="pr"?new yt:new bt;case"github":case"githubEnterprise":return t==="pr"?new wt:new Pt;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new vt:new qt;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Et;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new St;default:throw new Error("unknown provider")}},ni=s=>{if(!s.entityType)throw new Error("entityType is required");if(!s.provider)throw new Error("provider is required");if(!s.entityId)throw new Error("entityID is required")},oi=s=>{if(s.version==="0"){ni(s);return}Ct(s.provider,s.entityType).validate(s)},ii=s=>Ct(s.provider,s.entityType).encode(s),vr=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return Ct(t[0],t[1]).decode(t)},ai=(s,t,e)=>{if(!e)throw new Error("entityID is required");try{let r=JSON.parse(e);if(!r||!r.length)throw new Error("Invalid pull request uniqueId");let n=[s,t,"0",...r];return Ct(s,t).decode(n)}catch{return{provider:s,entityType:t,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var At={};H(At,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>Js,CHANGES_REQUESTED_BUCKET_ID:()=>Lr,CONFLICTS_ACTION_CATEGORY:()=>Hs,CONFLICTS_BUCKET_ID:()=>Ar,DRAFT_ACTION_CATEGORY:()=>Zs,DRAFT_BUCKET_ID:()=>Tr,FAILING_CI_ACTION_CATEGORY:()=>Ws,FAILING_CI_BUCKET_ID:()=>Dr,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Vs,NEEDS_MY_REVIEW_BUCKET_ID:()=>$r,OTHER_ACTION_CATEGORY:()=>Ys,OTHER_BUCKET_ID:()=>Or,PINNED_BUCKET_ID:()=>Er,READY_TO_MERGE_ACTION_CATEGORY:()=>zs,READY_TO_MERGE_BUCKET_ID:()=>Sr,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>Ks,REVIEWER_COMMENTED_BUCKET_ID:()=>Ur,SNOOZED_BUCKET_ID:()=>_r,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Ms,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Cr,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>Xs,WAITING_FOR_REVIEW_BUCKET_ID:()=>Gr,getActionablePullRequests:()=>en,groupPullRequestsByAssignee:()=>pi,groupPullRequestsByAuthor:()=>di,groupPullRequestsByGitKrakenTeam:()=>hi,groupPullRequestsByRepo:()=>li,groupPullRequestsByReviewer:()=>ci,groupPullRequestsByWorkspace:()=>gi,groupPullRequestsIntoBuckets:()=>ui});var z=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Er="pinned",Sr="readyToMerge",Cr="unassignedReviewers",Dr="failingCI",Ar="conflicts",$r="needsMyReview",Lr="changesRequested",Ur="reviewerCommented",Gr="waitingForReview",Tr="draft",Or="other",_r="snoozed",zs="readyToMerge",Ms="unassignedReviewers",Ws="failingCI",Hs="conflicts",Vs="needsMyReview",Js="changesRequested",Ks="reviewerCommented",Xs="waitingForReview",Zs="draft",Ys="other",en=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:Ys,priority:1e3,viewer:{canMerge:!1,isAuthor:!1,isAssignee:!1,isReviewer:!1,shouldMerge:!1,shouldAssignReviewer:!1,waitingOnReviews:!1,shouldReview:!1},failingCI:!1,hasConflicts:!1,changeRequestReviewCount:0,codeSuggestionsCount:0,commentReviewCount:0,approvalReviewCount:0}};t&&(o.viewer.isAuthor=r.author?.id===t.id,o.viewer.isAssignee=r.assignees?.some(u=>u.id===t.id)??!1,o.viewer.isReviewer=r.reviews?.some(u=>u.reviewer.id===t.id)??!1),o.viewer.canMerge=r.permissions?.canMerge??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=r.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=r.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=r.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=r.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(u=>u.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(u=>u.type==="snooze")&&(o.viewer.snoozed=!0));let a=e?.codeSuggestionsCountByPrUuid?.[r.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!t||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&r.mergeableState==="MERGEABLE"&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=zs),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=Zs),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=Xs,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=Ks),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Ws),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=Hs),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=Js),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=Ms,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=Vs,o.viewer.shouldReview=!0),o}),ui=(s,t,e)=>{let r={pinned:z(Er,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:z(Sr,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:z(Cr,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:z(Dr,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:z(Ar,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:z($r,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:z(Lr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:z(Ur,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:z(Gr,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:z(Tr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:z(Or,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:z(_r,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=en(s,t,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){r[_r].pullRequests.push(i);return}a.viewer.pinned&&r[Er].pullRequests.push(i),(!t||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(r[Sr].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[Cr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[Dr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[Ar].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[$r].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[Lr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[Ur].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[Gr].pullRequests.push(i),u=!1),a.isDraft&&(r[Tr].pullRequests.push(i),u=!1),u&&r[Or].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},li=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),de(t)},pi=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Ne(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),de(e)},di=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Ne(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),de(e)},ci=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Ne(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),de(e)},mi=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],gi=(s,t)=>{let e="internal-no-workspace",r={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(t.length){let n=t.reduce((o,i)=>(mi(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=vr(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,p=u.reduce((d,c)=>n[c]?d.concat(n[c]):d,[]);p?.length&&p.forEach(d=>{l=!0;let c=d.id;r[c]?r[c].pullRequests.push(o):r[c]={name:d.name,priority:0,pullRequests:[o],id:c,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return de(r)},hi=(s,t,e,r)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(i=>{let a=!1,u=new Set;u.add(i.author?.id),i.assignees?.forEach(l=>u.add(l.id)),i.reviews?.forEach(l=>u.add(l.reviewer.id)),r.forEach(l=>{if(l.members?.some(d=>{let c=t[d.id]?.[e]?.providerID;return c&&u.has(c)})){a=!0;let d=l.id;o[d]?o[d].pullRequests.push(i):o[d]={name:l.name,priority:0,pullRequests:[i],id:d,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,de(o)};var $t={};H($t,{getPullRequestRank:()=>fi});var fi=(s,t,e)=>{let r=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===t&&(n=i.state),i.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":i.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),s.author?.id===t?r+=1e3:s.assignees?.find(i=>i.id===t)?r+=900:n==="REVIEW_REQUESTED"?r+=800:e&&(r+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:o=="CHANGES_REQUESTED"&&(r+=70),r};var Lt={};H(Lt,{default:()=>Ri});var Ri={};var Ut={};H(Ut,{default:()=>Ii});var Ii={};var Gt={};H(Gt,{default:()=>bi});var bi={};var tn=s=>{let t={request:s?.request};return{azureDevOps:new Re({...t,...s?.azureDevOps}),bitbucket:new Ie({...t,...s?.bitbucket}),bitbucketServer:new be({...t,...s?.bitbucketServer}),github:new ye({...t,...s?.github}),gitlab:new we({...t,...s?.gitlab}),jira:new qe({...t,...s?.jira}),jiraServer:new ve({...t,...s?.jiraServer}),linear:new Ee({...t,...s?.linear}),trello:new Se({...t,...s?.trello})}};var rn=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(rn||{});var sn=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(sn||{});var yi=tn;var Pi={azureDevOps:ht,bitbucket:ft,bitbucketServer:We,github:$t,gitlab:Lt,gitProvider:At,jira:Ut,trello:Gt,entityIdentifier:Dt};
|
|
1596
|
+
`,d=(await this.rawRequest(e,l,{first:Bs,after:i})).data?.issues;return d?{data:await kt(d.nodes.map(wr)),pageInfo:{hasNextPage:d.pageInfo.hasNextPage,endCursor:d.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var Z="https://api.trello.com",ti=1e3,Y=(s,t)=>({...R(t),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${t}"`}),ri=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),si=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},Se=class extends M{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||Z}/1/members/me`,headers:Y(t.appKey,e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/members/me/boards?fields=name&filter=open`,headers:Y(t.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/lists`,headers:Y(r,e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||Z}/1/members/${n}`,headers:Y(r,e.token||this.config.token)});return{data:ri(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/members`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(c=>r.push(`label:"${c}"`));let p=`${i?`${i}`:""}${r.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/search?query=${p}&cards_limit=${ti}&card_members=true`,headers:Y(n,e.token||this.config.token)})).body.cards.map(c=>si(c,l||{}))}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||Z}/1/cards/${e.id}?${r}`,headers:Y(t,n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:o}=t;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:o}=t,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(t,e={}){let{appKey:r,issue:n,labels:o}=t,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(t,e={}){let{appKey:r,issue:n,archived:o}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?closed=${o}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/labels`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var ht={};H(ht,{default:()=>ni});var ni={};var ft={};H(ft,{default:()=>oi});var oi={};var Dt={};H(Dt,{decode:()=>vr,decodeV0:()=>li,encode:()=>ui,validate:()=>ai});var B=(e=>(e.Zero="0",e.One="1",e))(B||{}),j=(e=>(e.PullRequest="pr",e.Issue="issue",e))(j||{}),N=(c=>(c.Azure="azure",c.AzureDevOpsServer="azureDevOpsServer",c.Github="github",c.GithubEnterprise="githubEnterprise",c.Gitlab="gitlab",c.GitlabSelfHosted="gitlabSelfHosted",c.Bitbucket="bitbucket",c.BitbucketServer="bitbucketServer",c.Jira="jira",c.JiraServer="jiraServer",c.Linear="linear",c.Trello="trello",c))(N||{});var Rt=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var It=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var bt=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var yt=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var Pt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var wt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var qt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var vt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Et=class{constructor(){}validate(t){if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.projectId||!t.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider=="jira"?(e.push(""),e.push(t.resourceId)):(e.push(t.domain),e.push("")),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:t[4]==""?null:t[4],accountOrOrgId:null,organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var St=class{constructor(){}validate(t){if(!t.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.accountOrOrgId||!t.projectId||!t.entityId)throw new Error("Missing required fields for Trello issue uniqueId");let e=[];return e.push("trello"),e.push("issue"),e.push("1"),e.push(""),e.push(t.accountOrOrgId),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:t[4],organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var Ct=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new It:new Rt;case"bitbucket":case"bitbucketServer":return t==="pr"?new yt:new bt;case"github":case"githubEnterprise":return t==="pr"?new wt:new Pt;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new vt:new qt;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Et;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new St;default:throw new Error("unknown provider")}},ii=s=>{if(!s.entityType)throw new Error("entityType is required");if(!s.provider)throw new Error("provider is required");if(!s.entityId)throw new Error("entityID is required")},ai=s=>{if(s.version==="0"){ii(s);return}Ct(s.provider,s.entityType).validate(s)},ui=s=>Ct(s.provider,s.entityType).encode(s),vr=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return Ct(t[0],t[1]).decode(t)},li=(s,t,e)=>{if(!e)throw new Error("entityID is required");try{let r=JSON.parse(e);if(!r||!r.length)throw new Error("Invalid pull request uniqueId");let n=[s,t,"0",...r];return Ct(s,t).decode(n)}catch{return{provider:s,entityType:t,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var At={};H(At,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>Js,CHANGES_REQUESTED_BUCKET_ID:()=>Lr,CONFLICTS_ACTION_CATEGORY:()=>Hs,CONFLICTS_BUCKET_ID:()=>Ar,DRAFT_ACTION_CATEGORY:()=>Zs,DRAFT_BUCKET_ID:()=>Tr,FAILING_CI_ACTION_CATEGORY:()=>Ws,FAILING_CI_BUCKET_ID:()=>Dr,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Vs,NEEDS_MY_REVIEW_BUCKET_ID:()=>$r,OTHER_ACTION_CATEGORY:()=>Ys,OTHER_BUCKET_ID:()=>Or,PINNED_BUCKET_ID:()=>Er,READY_TO_MERGE_ACTION_CATEGORY:()=>zs,READY_TO_MERGE_BUCKET_ID:()=>Sr,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>Ks,REVIEWER_COMMENTED_BUCKET_ID:()=>Gr,SNOOZED_BUCKET_ID:()=>_r,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Ms,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Cr,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>Xs,WAITING_FOR_REVIEW_BUCKET_ID:()=>Ur,getActionablePullRequests:()=>en,groupPullRequestsByAssignee:()=>ci,groupPullRequestsByAuthor:()=>mi,groupPullRequestsByGitKrakenTeam:()=>Ri,groupPullRequestsByRepo:()=>di,groupPullRequestsByReviewer:()=>gi,groupPullRequestsByWorkspace:()=>fi,groupPullRequestsIntoBuckets:()=>pi});var z=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Er="pinned",Sr="readyToMerge",Cr="unassignedReviewers",Dr="failingCI",Ar="conflicts",$r="needsMyReview",Lr="changesRequested",Gr="reviewerCommented",Ur="waitingForReview",Tr="draft",Or="other",_r="snoozed",zs="readyToMerge",Ms="unassignedReviewers",Ws="failingCI",Hs="conflicts",Vs="needsMyReview",Js="changesRequested",Ks="reviewerCommented",Xs="waitingForReview",Zs="draft",Ys="other",en=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:Ys,priority:1e3,viewer:{canMerge:!1,isAuthor:!1,isAssignee:!1,isReviewer:!1,shouldMerge:!1,shouldAssignReviewer:!1,waitingOnReviews:!1,shouldReview:!1},failingCI:!1,hasConflicts:!1,changeRequestReviewCount:0,codeSuggestionsCount:0,commentReviewCount:0,approvalReviewCount:0}};t&&(o.viewer.isAuthor=r.author?.id===t.id,o.viewer.isAssignee=r.assignees?.some(u=>u.id===t.id)??!1,o.viewer.isReviewer=r.reviews?.some(u=>u.reviewer.id===t.id)??!1),o.viewer.canMerge=r.permissions?.canMerge??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=r.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=r.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=r.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=r.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(u=>u.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(u=>u.type==="snooze")&&(o.viewer.snoozed=!0));let a=e?.codeSuggestionsCountByPrUuid?.[r.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!t||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&r.mergeableState==="MERGEABLE"&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=zs),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=Zs),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=Xs,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=Ks),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Ws),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=Hs),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=Js),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=Ms,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=Vs,o.viewer.shouldReview=!0),o}),pi=(s,t,e)=>{let r={pinned:z(Er,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:z(Sr,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:z(Cr,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:z(Dr,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:z(Ar,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:z($r,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:z(Lr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:z(Gr,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:z(Ur,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:z(Tr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:z(Or,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:z(_r,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=en(s,t,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){r[_r].pullRequests.push(i);return}a.viewer.pinned&&r[Er].pullRequests.push(i),(!t||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(r[Sr].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[Cr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[Dr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[Ar].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[$r].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[Lr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[Gr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[Ur].pullRequests.push(i),u=!1),a.isDraft&&(r[Tr].pullRequests.push(i),u=!1),u&&r[Or].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},di=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),de(t)},ci=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Ne(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),de(e)},mi=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Ne(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),de(e)},gi=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Ne(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),de(e)},hi=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],fi=(s,t)=>{let e="internal-no-workspace",r={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(t.length){let n=t.reduce((o,i)=>(hi(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=vr(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,p=u.reduce((d,c)=>n[c]?d.concat(n[c]):d,[]);p?.length&&p.forEach(d=>{l=!0;let c=d.id;r[c]?r[c].pullRequests.push(o):r[c]={name:d.name,priority:0,pullRequests:[o],id:c,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return de(r)},Ri=(s,t,e,r)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(i=>{let a=!1,u=new Set;u.add(i.author?.id),i.assignees?.forEach(l=>u.add(l.id)),i.reviews?.forEach(l=>u.add(l.reviewer.id)),r.forEach(l=>{if(l.members?.some(d=>{let c=t[d.id]?.[e]?.providerID;return c&&u.has(c)})){a=!0;let d=l.id;o[d]?o[d].pullRequests.push(i):o[d]={name:l.name,priority:0,pullRequests:[i],id:d,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,de(o)};var $t={};H($t,{getPullRequestRank:()=>Ii});var Ii=(s,t,e)=>{let r=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===t&&(n=i.state),i.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":i.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),s.author?.id===t?r+=1e3:s.assignees?.find(i=>i.id===t)?r+=900:n==="REVIEW_REQUESTED"?r+=800:e&&(r+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:o=="CHANGES_REQUESTED"&&(r+=70),r};var Lt={};H(Lt,{default:()=>bi});var bi={};var Gt={};H(Gt,{default:()=>yi});var yi={};var Ut={};H(Ut,{default:()=>Pi});var Pi={};var tn=s=>{let t={request:s?.request};return{azureDevOps:new Re({...t,...s?.azureDevOps}),bitbucket:new Ie({...t,...s?.bitbucket}),bitbucketServer:new be({...t,...s?.bitbucketServer}),github:new ye({...t,...s?.github}),gitlab:new we({...t,...s?.gitlab}),jira:new qe({...t,...s?.jira}),jiraServer:new ve({...t,...s?.jiraServer}),linear:new Ee({...t,...s?.linear}),trello:new Se({...t,...s?.trello})}};var rn=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(rn||{});var sn=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(sn||{});var wi=tn;var qi={azureDevOps:ht,bitbucket:ft,bitbucketServer:We,github:$t,gitlab:Lt,gitProvider:At,jira:Gt,trello:Ut,entityIdentifier:Dt};
|