@gitkraken/provider-apis 0.46.0 → 0.46.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/index.js +148 -148
- package/dist/index.providers.js +138 -138
- package/dist/types/internalTypes/azureDevOps.d.ts +3 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var Dt=Object.defineProperty;var Ns=Object.getOwnPropertyDescriptor;var js=Object.getOwnPropertyNames;var Bs=Object.prototype.hasOwnProperty;var W=(s,r)=>{for(var e in r)Dt(s,e,{get:r[e],enumerable:!0})},Qs=(s,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of js(r))!Bs.call(s,n)&&n!==e&&Dt(s,n,{get:()=>r[n],enumerable:!(t=Ns(r,n))||t.enumerable});return s};var Fs=s=>Qs(Dt({},"__esModule",{value:!0}),s);var zo={};W(zo,{AzureDevOps:()=>pe,AzureDevopsUtils:()=>lt,Bitbucket:()=>de,BitbucketServer:()=>ce,BitbucketServerUtils:()=>_e,BitbucketUtils:()=>pt,EntityIdentifierProviderType:()=>x,EntityIdentifierUtils:()=>Pt,EntityType:()=>_,EntityVersion:()=>k,GitBuildStatusStage:()=>Lr,GitBuildStatusState:()=>Pe,GitDiffLineType:()=>$t,GitHub:()=>me,GitHubIssueCloseReason:()=>xs,GitHubUtils:()=>qt,GitIssueState:()=>Ne,GitLab:()=>he,GitLabUtils:()=>Et,GitMergeStrategy:()=>le,GitProviderUtils:()=>vt,GitPullRequestMergeableState:()=>Y,GitPullRequestReviewState:()=>H,GitPullRequestState:()=>oe,GraphQLErrors:()=>R,Jira:()=>fe,JiraServer:()=>Re,JiraUtils:()=>St,Linear:()=>Ie,PullRequestAsyncStatus:()=>Os,Trello:()=>be,TrelloUtils:()=>Ct,Utils:()=>Mo,default:()=>Fo,isFetch:()=>Ge});module.exports=Fs(zo);var jr=require("diff");var Lr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(Lr||{}),Pe=(p=>(p.ActionRequired="ACTION_REQUIRED",p.Cancelled="CANCELLED",p.Error="ERROR",p.Failed="FAILED",p.Pending="PENDING",p.Running="RUNNING",p.Skipped="SKIPPED",p.Success="SUCCESS",p.Warning="WARNING",p.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",p))(Pe||{}),le=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(le||{}),oe=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(oe||{}),H=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(H||{}),Y=(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))(Y||{}),$t=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))($t||{});var Ur={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},J=s=>!s||s.length===0?null:s.reduce((r,e)=>Ur[e.state]>Ur[r]?e.state:r,"APPROVED"),Te=(s,r)=>s.name||s.username||s.email||r,ie=s=>{let r=Object.values(s).map(e=>e.name).sort((e,t)=>e.localeCompare(t));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=r.indexOf(e.name))}),s};var At=(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))(At||{});var $=100;var Tr=globalThis.fetch;var Ms=async s=>{let r=s.headers.get("content-type")||"",e=null;if(r.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(r.startsWith("text/")||r==="")e=await s.text();else if(r.startsWith("application/vnd.github.raw+json")||r.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${r}`);let t={};s.headers.forEach((o,i)=>{t[i]=o});let n={body:e,headers:t,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},Lt=s=>async({url:r,...e})=>{let t=await s(r,e);return Ms(t)};var Ge=(s,r=!1)=>s.name==="fetch"||r;var F=class{constructor(r){let e=r?.request||Tr;this.config={...r,request:Ge(e,r?.forceIsFetch)?Lt(e):e}}updateConfig(r){this.config={...this.config,...r,request:r.request&&Ge(r.request,r?.forceIsFetch??this.config.forceIsFetch)?Lt(r.request):this.config.request}}},j=class extends F{};var f=(s,r)=>{let e={};return s&&(e.Authorization=`${r?"Basic":"Bearer"} ${s}`),e},Gr=s=>s?s.reduce((r,e)=>(r[e]=!0,r),{}):void 0,se=(s,r,e)=>!s||r.some(t=>s[t])?e:"",Or=async s=>{let r=[],e=!0,t;for(;e;){let n=await s(t);r=r.concat(n.data),e=!!n?.pageInfo?.hasNextPage,t=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return r};async function Ut(s){return(await Promise.allSettled(s)).map(e=>zs(e)).filter(e=>e!=null)}function zs(s,r=void 0){return s?.status==="fulfilled"?s.value:r}var Ws="https://app.vssps.visualstudio.com/_apis",Hs="https://vssps.dev.azure.com/",Js="https://dev.azure.com",w=(s,r={})=>f(r.token||s.token,r.isPAT||s.isPAT),xr=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/"),Tt=(s,r)=>{let e=r.baseUrl||s.baseUrl||Ws;return e=e.replace(/\/$/,""),e},C=(s,r)=>{let e=r.baseUrl||s.baseUrl||Js;return e=e.replace(/\/$/,""),e},Gt=(s,r)=>{let e=r.baseUrl||s.baseUrl||Hs;return e=e.replace(/\/$/,""),e};var Vs={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Ks=s=>{if(typeof s!="string")return s;let r=s.charAt(0).toUpperCase()+s.slice(1);return At[r]??0},Xs=new Set([2,3,4,5]),Ys={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},ae=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Oe=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Zs=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"}},Ot=(s,r,e,t,n,o)=>`${s}|${r}|${e}|${t}|${n}|${o}`,kr=s=>{let r=s.split("|");if(r.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:r[0],project:r[1],repoName:r[2],prId:r[3],threadId:r[4],commentId:r[5]}},_r=(s,r,e,t,n)=>`${s}|${r}|${e}|${t}|${n}`,xt=s=>{let r=s.split("|");if(r.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:r[0],project:r[1],repoName:r[2],prId:r[3],threadId:r[4]}},ve=(s,r)=>{let e=[],t=[];return r.reviewers.forEach(n=>{let o={reviewer:ae(n),state:Ys[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),t.push(o)}),{id:r.pullRequestId.toString(),title:r.title,description:r.description??null,number:r.codeReviewId,state:Vs[r.status],isDraft:r.isDraft,commentCount:null,upvoteCount:null,author:ae(r.createdBy),createdDate:new Date(r.creationDate),updatedDate:new Date(r.closedDate||r.creationDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.closedDate&&r.status==="completed"?new Date(r.closedDate):null,repository:{id:r.repository.id,name:r.repository.name,project:r.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Oe(r.targetRefName),oid:r.lastMergeTargetCommit.commitId},headRef:{name:Oe(r.sourceRefName),oid:r.lastMergeSourceCommit.commitId},url:xr(r),assignees:r.reviewers.map(ae),reviews:t,reviewDecision:J(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:r.forkSource?{id:r.forkSource.repository.id,name:r.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:null}:{id:r.repository.id,name:r.repository.name,project:r.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:Zs(r.mergeStatus),labels:r.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},Nr=(s,r)=>({id:r.id,name:r.name,namespace:s,project:r.project.name,projectId:r.project.id,webUrl:r.webUrl,httpsUrl:r.remoteUrl,sshUrl:r.sshUrl,defaultBranch:r.defaultBranch?{name:Oe(r.defaultBranch)}:null,permissions:null}),en=(s,r,e,t)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=t[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:r,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()}))??[]}},pe=class extends j{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let n=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.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,t,n);return this.inflightUserIds.set(n,a),a}async fetchCurrentUserId(e,t,n){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(n,o.data.id),o.data.id}finally{this.inflightUserIds.delete(n)}}getRepoApiUrl(e,t,n,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(n)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let n=`${Tt(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:n,headers:w(this.config,t)});return{data:{id:o.body.id,name:o.body.displayName,username:o.body.displayName,email:o.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(e,t={}){let o=(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:w(this.config,t)})).body.authorizedUser;if(o.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:o.id,name:o.providerDisplayName,username:o.providerDisplayName,email:o.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:w(this.config,t)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,t={}){let n=`${Tt(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:n,headers:w(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let n=`${C(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:n,headers:w(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let n=new URL(`${C(this.config,t)}/${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:w(this.config,t)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({id:a.id,name:a.name,namespace:e.namespace}))}}async getAzureProjectScopeDescriptor(e,t={}){let{namespace:n,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${Gt(this.config,t)}/${encodeURIComponent(n)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:w(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:n,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${Gt(this.config,t)}/${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:w(this.config,t)}),l=u.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:l||null,hasNextPage:!!l},data:u.body.value.map(p=>({avatarUrl:p._links?.avatar?.href??null,descriptor:p.descriptor??null,email:p.mailAddress??null,name:p.displayName??null,storageKeyURL:p._links?.storageKey?.href??null,username:p.displayName??null}))}}async getAccountFromAzureGraphAccount(e,t={}){let{azureGraphAccount: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:w(this.config,t)});return{data:{avatarUrl:n.avatarUrl,email:n.email,id:o.body.value,name:n.name,username:n.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let n=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);n.push(i.data)}return{data:n}}async getRepo(e,t={}){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,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:w(this.config,t)});return{data:Nr(e.namespace,n.body)}}async getRepos(e,t={}){let n=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);n.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:n,errors:o}}async getReposForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:w(this.config,t)})).body.value.map(o=>Nr(e.namespace,o))}}async getRefs(e,t,n={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${C(this.config,n)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",$.toString()),t.cursor&&o.searchParams.set("continuationToken",t.cursor);let i=await this.config.request({url:o.toString(),headers:w(this.config,n)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Oe(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,t={}){return this.getRefs("heads",e,t)}async getTags(e,t={}){return this.getRefs("tags",e,t)}async getPullRequestsForRepoBase(e,t={},n=100){let{page:o,repo:i,assigneeLogins:a,authorLogin:u}=e||{},l=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let p="searchCriteria.status=1";return a&&a.length&&(p+=`&searchCriteria.reviewerId=${a[0]}`),u&&(p+=`&searchCriteria.creatorId=${u}`),await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${p}&%24top=${n}&%24skip=${(l-1)*n}`,headers:w(this.config,t)})}async getPullRequestsForRepo(e,t={}){let o=e.page||1,i=await this.getPullRequestsForRepoBase(e,t,100);return{pageInfo:{hasNextPage:i.body.value.length===100,nextPage:o+1},data:i.body.value.map(a=>ve(e.repo.namespace,a))}}async getPullRequestsForRepos(e,t={}){if(!e.repos.every(i=>i.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:n}=e||{},o=[];return await Promise.all(n.map(async i=>{try{(await this.getPullRequestsForRepoBase({repo:i,...e},t)).body.value.forEach(u=>{o.push(ve(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getPullRequestsForProjectBase(e,t={},n=100){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,repo:p}=e;if(p?.project&&p.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,d=new URL(`${C(this.config,t)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return d.searchParams.set("searchCriteria.status","1"),d.searchParams.set("$top",n.toString()),d.searchParams.set("$skip",((c-1)*n).toString()),p?.id&&p?.project===i&&d.searchParams.set("searchCriteria.repositoryId",p.id),u&&u.length&&d.searchParams.set("searchCriteria.reviewerId",u[0]),l&&d.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:d.toString(),headers:w(this.config,t)})}async getPullRequestsForProject(e,t={}){let o=e.page||1,i=await this.getPullRequestsForProjectBase(e,t,100);return{pageInfo:{hasNextPage:i?.body.value.length===100,nextPage:o+1},data:i?.body.value.map(a=>ve(e.namespace,a))||[]}}async getPullRequestsForProjects(e,t={}){let{projects:n}=e||{},o=[];return await Promise.all(n.map(async i=>{try{(!e.repo||e.repo.project&&e.repo.project===i.project)&&(await this.getPullRequestsForProjectBase({...i,...e},t))?.body.value.forEach(u=>{o.push(ve(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getAzurePullRequestLastMergeStatus(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:n,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...w(this.config,t)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,t,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:t,headers:{...w(this.config,n),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:n}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(n,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){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),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){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,t)}/${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:{...w(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,t={}){let{pullRequest: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,t)}/${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:{...w(this.config,t)}})}async setPullRequestLabels(e,t={}){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},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:n,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:n,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(n,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){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,t)}/${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:{...w(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,t={}){let{pullRequest:n,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${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:{...w(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){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},t);for(let i of n.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:n,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:n,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},p=n||1,c=200,d=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];i&&d.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&d.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&d.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(h=>d.push(`[System.Tags] Contains '${h}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${d.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...w(this.config,t),"Content-Type":"application/json"}}),I=m.body.workItems.slice((p-1)*c,c*p).map(h=>h.id);if(I.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let y=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:I,$expand:"Links"}),method:"POST",headers:{...w(this.config,t),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:m.body.workItems.length>c*p,nextPage:p+1},data:y.body.value.map(h=>en(e.namespace,e.project,h,l||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:n,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=c=>{let d="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${c.projectId}/${c.id}`;return Object.keys(i).map(m=>({securityNamespaceId:d,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,t)}/${encodeURIComponent(n)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...w(this.config,t),"Content-Type":"application/json"}})).body.evaluations.reduce((c,d)=>{let[,g,m]=d.token.split("/"),I=`${g}/${m}`,y=i[d.permissions];for(let h of y)c[I]===void 0&&(c[I]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),d.value===!1&&(c[I][h]=!1);return c},{})}}async decorateReposWithPermissions(e,t={}){let{namespace:n,repos:o}=e,i=await this.getPermissionsForRepos({namespace:n,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,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(t),headers:{...w(this.config,n),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:n,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(n,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:n,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(n,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){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,t)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...w(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...w(this.config,t)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,t={}){let{repo: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,t)}/pullrequests/${o}?api-version=7.1`,headers:w(this.config,t)});return{data:ve(n.namespace,i.body)}}async getMergeBase(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:w(this.config,t)});if(!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,t={}){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,t)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...w(this.config,t),Accept:"application/octet-stream"}});return{data:new Blob([n.body])}}async getPullRequestDiff(e,t={}){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,t),o=w(this.config,t),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,c=u.body.value;if(c.length===0)return"";let d=c[c.length-1],m=(await this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations/${d.id}/changes?api-version=7.1`,headers:o})).body.changeEntries;if(m.length===0)return"";let I=5,y=[],h=new TextDecoder,v=q=>q instanceof ArrayBuffer?h.decode(q):typeof q=="string"?q:"",D=async(q,ye)=>{try{let we=await this.config.request({url:`${n}/items?path=${encodeURIComponent(q)}&versionDescriptor[version]=${encodeURIComponent(ye)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return v(we.body)}catch{return""}},N=1,E=8,S=16;for(let q=0;q<m.length;q+=I){let ye=m.slice(q,q+I),we=await Promise.all(ye.map(async z=>{let Ae=z.item.path,Le=(z.changeType&N)!==0,Ue=(z.changeType&E)!==0,$r=(z.changeType&S)!==0&&z.item.originalPath?z.item.originalPath:Ae,Ar=Ae,[ks,_s]=await Promise.all([Le?Promise.resolve(""):D($r,l),Ue?Promise.resolve(""):D(Ar,p)]);return(0,jr.createTwoFilesPatch)(`a${$r}`,`b${Ar}`,ks,_s)}));y.push(...we)}return y.join(`
|
|
2
|
-
`)}getPullRequestWriteHeaders(e){return{...w(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,n,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(n)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,n,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${t}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:n,commentType:1}],status:1})})}async getCommentsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=w(this.config,t),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:Ot(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?ae(l.author):null,body:l.content||"",createdAt:l.publishedDate?new Date(l.publishedDate):null,url:""});return{data:a,pageInfo:{hasNextPage:!1,endCursor:null}}}async addCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,t)}async addInlineCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t),o=this.getPullRequestWriteHeaders(t);if(e.threadId){let p=xt(e.threadId),c=e.pullRequest.repository.owner.login,d=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(p.namespace!==c||p.project!==d||p.repoName!==g||p.prId!==m)throw new Error(`Azure thread ID context mismatch: threadId targets ${p.namespace}/${p.project}/${p.repoName} pull request ${p.prId}, but input.pullRequest targets ${c}/${d}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${n}/pullRequests/${e.pullRequest.id}/threads/${p.threadId}?api-version=7.1`,headers:w(this.config,t)})).body.comments?.find(v=>v.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${p.threadId}.`);let h=await this.config.request({method:"POST",url:`${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 Ot(c,d,g,Number(m),Number(p.threadId),h.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let l=await this.config.request({method:"POST",url:`${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 _r(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,t={}){let n=kr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({content:e.body})})}async editInlineComment(e,t={}){return this.editComment(e,t)}async deleteComment(e,t={}){let n=kr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:w(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let n=xt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let n=xt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:1})})}async approvePullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(n,t);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,t),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,t):null])}async requestPullRequestChanges(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(n,t);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,t),await this.setReviewerVote(o,e.pullRequest.id,i,-5,t)}async commentOnPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,t)}async getReviewsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(n,o,i,t),l=w(this.config,t),[p,c]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:l}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:l})]),d=(h,v)=>Ot(n,o,i,a,h,v),g=h=>_r(n,o,i,a,h),m=new Map;for(let h of c.body.value){if(h.isDeleted)continue;let v=h.comments.filter(O=>!O.isDeleted&&O.commentType!=="system"),D=v.find(O=>O.parentCommentId===0)??v[0];if(!D)continue;let N=D.author?.id;if(!N)continue;let E=v.filter(O=>O.id!==D.id),S=h.threadContext,q=S?.rightFileStart?{side:"RIGHT",start:S.rightFileStart,end:S.rightFileEnd}:S?.leftFileStart?{side:"LEFT",start:S.leftFileStart,end:S.leftFileEnd}:null,ye=q?.end?.line??q?.start.line??null,we=q?.start&&q.end&&q.start.line!==q.end.line?q.start.line:null,z=S?.filePath??"",Ae=z.startsWith("/")?z.slice(1):z,Le={id:d(h.id,D.id),author:D.author?ae(D.author):null,body:D.content??"",createdAt:D.publishedDate?new Date(D.publishedDate):null,url:"",diffLines:[],filename:Ae,replies:E.map(O=>({id:d(h.id,O.id),author:O.author?ae(O.author):null,body:O.content??"",createdAt:O.publishedDate?new Date(O.publishedDate):null,url:""})),isOutdated:!1,isResolved:Xs.has(Ks(h.status)),line:ye,startLine:we,side:q?.side??null,threadId:g(h.id)},Ue=m.get(N);Ue?Ue.push(Le):m.set(N,[Le])}let I=[],y=new Set;for(let h of p.body.value){if(h.hasDeclined)continue;let v=h.vote??0,D=m.get(h.id);v===0&&!D?.length||(I.push({id:h.id,author:ae(h),body:"",createdAt:null,url:"",reviewComments:D??[]}),y.add(h.id))}for(let[h,v]of m){if(y.has(h)||!v.length)continue;let D=v[0].author;D&&I.push({id:h,author:D,body:"",createdAt:null,url:"",reviewComments:v})}return{data:I}}};var A=(s,r={})=>f(r.token||s.token,r.isPAT||s.isPAT);var U="https://api.bitbucket.org/2.0",tn={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},xe={owner:4,admin:3,contributor:2,member:1},ke=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}),Br=s=>{let r=s.links.clone,e=r?.find(n=>n.name==="ssh"),t=r?.find(n=>n.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},kt=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(r=>r.name==="https")?.href??null,sshUrl:s.links.clone.find(r=>r.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),_t=s=>{let r=s.id,e=s.participants?.map(t=>{let n="REVIEW_REQUESTED";return t.approved?n="APPROVED":t.state==="changes_requested"?n="CHANGES_REQUESTED":t.participated_on!==null&&(n="COMMENTED"),{reviewer:ke(t.user),state:n}})??[];return{id:r.toString(),title:s.title,description:s.description,number:r,state:tn[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:ke(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:Br(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:J(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:Br(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},rn=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}}},sn=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}}},de=class extends F{async refreshToken(r){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 ${r.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${r.refreshToken}`})).body}}async getCurrentUser(r={},e={}){let t=await this.config.request({url:`${U}/user`,headers:A(this.config,e)});return{data:ke(t.body)}}async getUserForCommit(r,e={}){let n=(await this.config.request({url:`${U}/repositories/${r.repo.namespace}/${r.repo.name}/commit/${r.oid}`,headers:A(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(r,e={}){let t=await this.config.request({url:`${U}/repositories/${r.namespace}/${r.name}`,headers:A(this.config,e)});return{data:kt(t.body)}}async getRepos(r,e={}){let t=[],n=[];return await Promise.all(r.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForWorkspace(r,e={}){let t=new URL(`${U}/repositories/${encodeURIComponent(r.workspace)}`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen",$.toString()),r.minimumRole&&t.searchParams.set("role",r.minimumRole);let n=await this.config.request({url:t.toString(),headers:A(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(kt)}}async getAllReposForWorkspace(r,e={}){let t=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:r.workspace,minimumRole:r.minimumRole,page:n},e);t.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(r,e={}){let t=new Map,n=[],o=xe[r.minimumRole||"member"];o<=xe.admin&&n.push("admin"),o<=xe.contributor&&n.push("contributor"),o<=xe.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:r.workspace,minimumRole:a},e);for(let u of i)t.has(u.id)||t.set(u.id,a)}return{data:i.map(a=>{let u=t.get(a.id)||"member";return{...a,permissions:sn(u)}})}}async getReposForCurrentUser(r,e={}){let t=new URL(`${U}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",$.toString()),r.cursor&&t.searchParams.set("after",r.cursor);let n=await this.config.request({url:t.toString(),headers:A(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(kt)}}async getBranches(r,e={}){let t=new URL(`${U}/repositories/${r.repo.namespace}/${r.repo.name}/refs/branches`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen",$.toString());let n=await this.config.request({url:t.toString(),headers:A(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(r,e={}){let t=new URL(`${U}/repositories/${r.repo.namespace}/${r.repo.name}/refs/tags`);t.searchParams.set("pagelen",$.toString()),r.cursor&&t.searchParams.set("page",r.cursor);let n=await this.config.request({url:t.toString(),headers:A(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(r={},e={}){let t=new URL(`${U}/user/workspaces`);t.searchParams.set("page",r?.page?.toString()||"1"),t.searchParams.set("pagelen","50"),r?.administrator!==void 0&&t.searchParams.set("administrator",r.administrator.toString());let n=await this.config.request({url:t.toString(),headers:A(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(r,e={}){let t=new URL(`${U}/user/permissions/workspaces`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","50");let n=await this.config.request({url:t.toString(),headers:A(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(r,e={}){let t=new URL(`${U}/workspaces/${r.workspaceSlug}/pullrequests/${r.userId}`);if(t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","50"),r.repos&&r.repos.length>0){let i=`state = "open" AND (${r.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let n=await this.config.request({url:t.toString(),headers:A(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(_t)}}async getPullRequestsForRepoBase(r,e={}){let t=new URL(`${U}/repositories/${encodeURI(r.repo.namespace)}/${encodeURI(r.repo.name)}/pullrequests?state=OPEN`),n=[];r.reviewerId&&n.push(`reviewers.uuid="${r.reviewerId}"`),r.authorLogin&&n.push(`author.uuid="${r.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(r.useOrFilter?" OR ":" AND ")})`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:A(this.config,e)})}async getPullRequestsForRepo(r,e={}){let t=[],n=await this.getPullRequestsForRepoBase(r,e);n.body.values.forEach(i=>{t.push(_t(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:t}}async getPullRequestsForRepos(r,e={}){let t=[];return await Promise.all(r.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...r},e)).body.values.forEach(i=>{t.push(_t(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(r,e={}){let t=new URL(`${U}/workspaces/${encodeURI(r.workspace)}/members`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:A(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>ke(i.user))}}async getReposPermissionsForCurrentUser(r,e={}){let t=new URL(`${U}/user/permissions/repositories`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:A(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]:rn(a.permission)}),{})}}async decorateReposWithPermissions(r,e={}){let t={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);t={...o.data,...t},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:r.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(r,e={}){let{pullRequest:t}=r;if(!(await this.config.request({method:"POST",url:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:A(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(r,e={}){let{pullRequest:t,mergeStrategy:n}=r,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:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...A(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(r,e={}){let{pullRequest:t,reviewers:n}=r,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:`${U}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...A(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var _e={};W(_e,{normalizePermissions:()=>Nt,restApiPullRequestToCommonPullRequest:()=>nn});var nn=s=>qe(s),Nt=s=>s?s.find(r=>r.permission==="USER_ADMIN"||r.permission==="PROJECT_ADMIN"||r.permission==="ADMIN"||r.permission==="SYS_ADMIN"||r.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(r=>r.permission==="REPO_WRITE"||r.permission==="REPO_CREATE"||r.permission==="PROJECT_CREATE"||r.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Ee=s=>{let r=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(r&&`${r}/avatar.png`),id:s.id.toString(),username:s.name,url:r}},qe=s=>{let r={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=s.reviewers.map(u=>({reviewer:Ee(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:r[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:Ee(s.author.user),assignees:null,reviews:t,reviewDecision:J(t),repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&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}},Qr=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(r=>r.name==="https"||r.name==="http")?.href??null,sshUrl:s.links.clone.find(r=>r.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),ce=class extends j{getBaseUrl(r){let e=r.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(r){return f(r.token||this.config.token)}async getCurrentUser(r={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=t,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:c,name:d,slug:g})=>i?i===c:a===d||a===p||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Ee(l)}}async getUserForCommit(r,e){let{repo:t,oid:n}=r,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Ee(o.body.author)}}async getRepo(r,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}`,headers:this.getRequestHeaders(e)});return{data:Qr(t.body)}}async getRepos(r,e={}){let t=[],n=[];return await Promise.all(r.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForCurrentUser(r,e={}){let t=r.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Qr)}}async getRepoPermissionsForUsername(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${r.repo.namespace}/repos/${r.repo.name}/permissions/search?filterText=${r.username}`);try{let n=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:Nt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(r,e={}){return await Promise.all(r.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:r.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(r.repo.namespace)}/repos/${encodeURI(r.repo.name)}/pull-requests?state=OPEN`);return t.searchParams.set("start",r.page?.toString()||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(r,e={}){let t=[],n=await this.getPullRequestsForRepoBase(r,e);n.body.values.forEach(i=>{if(r.authorLogin&&i.author.user.name!==r.authorLogin)return null;t.push(qe(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:t}}async getPullRequestsForRepos(r,e={}){let t=[];return await Promise.all(r.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...r},e)).body.values.forEach(i=>{if(r.authorLogin&&i.author.user.name!==r.authorLogin)return null;t.push(qe(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",r.page?.toString()||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.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(qe)}}async closePullRequest(r,e={}){let{pullRequest:t}=r;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(r,e={}){let{pullRequest:t,mergeStrategyId:n}=r;if(r.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:n,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(r={}){let e=await this.config.request({url:`${this.getBaseUrl(r)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(r),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(r,e={}){let{pullRequest:t,reviewers:n}=r;if(t.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:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(r.project)}/permissions/users`);t.searchParams.set("start",r.page?.toString()||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.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=>Ee(i.user))}}};var ss=require("js-base64");var Ne=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Ne||{});var R=class extends Error{constructor(e,t){let n=t?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=t??[]}};var on={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]},Fr=15,Mr=100,Se={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},T=s=>!!s,V=(s,r)=>{let e=on[r];for(let t=0;t<3;t++){if(s[t]>e[t])return!0;if(s[t]<e[t])return!1}return!0},Be="https://api.github.com",an=`${Be}/graphql`,Qe=`
|
|
1
|
+
"use strict";var $t=Object.defineProperty;var Bs=Object.getOwnPropertyDescriptor;var Qs=Object.getOwnPropertyNames;var Fs=Object.prototype.hasOwnProperty;var z=(s,r)=>{for(var e in r)$t(s,e,{get:r[e],enumerable:!0})},Ms=(s,r,e,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of Qs(r))!Fs.call(s,n)&&n!==e&&$t(s,n,{get:()=>r[n],enumerable:!(t=Bs(r,n))||t.enumerable});return s};var zs=s=>Ms($t({},"__esModule",{value:!0}),s);var Ho={};z(Ho,{AzureDevOps:()=>me,AzureDevopsUtils:()=>lt,Bitbucket:()=>ge,BitbucketServer:()=>he,BitbucketServerUtils:()=>_e,BitbucketUtils:()=>dt,EntityIdentifierProviderType:()=>x,EntityIdentifierUtils:()=>Pt,EntityType:()=>N,EntityVersion:()=>_,GitBuildStatusStage:()=>Lr,GitBuildStatusState:()=>qe,GitDiffLineType:()=>At,GitHub:()=>fe,GitHubIssueCloseReason:()=>xs,GitHubUtils:()=>qt,GitIssueState:()=>Ne,GitLab:()=>Ie,GitLabUtils:()=>Et,GitMergeStrategy:()=>ce,GitProviderUtils:()=>vt,GitPullRequestMergeableState:()=>X,GitPullRequestReviewState:()=>W,GitPullRequestState:()=>ie,GraphQLErrors:()=>R,Jira:()=>be,JiraServer:()=>ye,JiraUtils:()=>St,Linear:()=>we,PullRequestAsyncStatus:()=>Os,Trello:()=>Pe,TrelloUtils:()=>Ct,Utils:()=>Wo,default:()=>zo,isFetch:()=>Ge});module.exports=zs(Ho);var jr=require("diff");var Lr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(Lr||{}),qe=(d=>(d.ActionRequired="ACTION_REQUIRED",d.Cancelled="CANCELLED",d.Error="ERROR",d.Failed="FAILED",d.Pending="PENDING",d.Running="RUNNING",d.Skipped="SKIPPED",d.Success="SUCCESS",d.Warning="WARNING",d.OptionalActionRequired="OPTIONAL_ACTION_REQUIRED",d))(qe||{}),ce=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ce||{}),ie=(t=>(t.Open="OPEN",t.Closed="CLOSED",t.Merged="MERGED",t))(ie||{}),W=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(W||{}),X=(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))(X||{}),At=(t=>(t.ADDED="ADDED",t.DELETED="DELETED",t.UNMODIFIED="UNMODIFIED",t))(At||{});var Ur={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},H=s=>!s||s.length===0?null:s.reduce((r,e)=>Ur[e.state]>Ur[r]?e.state:r,"APPROVED"),Te=(s,r)=>s.name||s.username||s.email||r,ae=s=>{let r=Object.values(s).map(e=>e.name).sort((e,t)=>e.localeCompare(t));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=r.indexOf(e.name))}),s};var Lt=(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))(Lt||{});var $=100;var Tr=globalThis.fetch;var Ws=async s=>{let r=s.headers.get("content-type")||"",e=null;if(r.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(r.startsWith("text/")||r==="")e=await s.text();else if(r.startsWith("application/vnd.github.raw+json")||r.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${r}`);let t={};s.headers.forEach((o,i)=>{t[i]=o});let n={body:e,headers:t,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},Ut=s=>async({url:r,...e})=>{let t=await s(r,e);return Ws(t)};var Ge=(s,r=!1)=>s.name==="fetch"||r;var F=class{constructor(r){let e=r?.request||Tr;this.config={...r,request:Ge(e,r?.forceIsFetch)?Ut(e):e}}updateConfig(r){this.config={...this.config,...r,request:r.request&&Ge(r.request,r?.forceIsFetch??this.config.forceIsFetch)?Ut(r.request):this.config.request}}},j=class extends F{};var f=(s,r)=>{let e={};return s&&(e.Authorization=`${r?"Basic":"Bearer"} ${s}`),e},Gr=s=>s?s.reduce((r,e)=>(r[e]=!0,r),{}):void 0,re=(s,r,e)=>!s||r.some(t=>s[t])?e:"",Or=async s=>{let r=[],e=!0,t;for(;e;){let n=await s(t);r=r.concat(n.data),e=!!n?.pageInfo?.hasNextPage,t=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return r};async function Tt(s){return(await Promise.allSettled(s)).map(e=>Hs(e)).filter(e=>e!=null)}function Hs(s,r=void 0){return s?.status==="fulfilled"?s.value:r}var Js="https://app.vssps.visualstudio.com/_apis",Vs="https://vssps.dev.azure.com/",Ks="https://dev.azure.com",P=(s,r={})=>f(r.token||s.token,r.isPAT||s.isPAT),xr=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/"),Gt=(s,r)=>{let e=r.baseUrl||s.baseUrl||Js;return e=e.replace(/\/$/,""),e},C=(s,r)=>{let e=r.baseUrl||s.baseUrl||Ks;return e=e.replace(/\/$/,""),e},Ot=(s,r)=>{let e=r.baseUrl||s.baseUrl||Vs;return e=e.replace(/\/$/,""),e};var Xs={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Ys=s=>{if(typeof s!="string")return s;let r=s.charAt(0).toUpperCase()+s.slice(1);return Lt[r]??0},Zs=new Set([2,3,4,5]),en={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},ue=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Oe=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,tn=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"}},xt=(s,r,e,t,n,o)=>`${s}|${r}|${e}|${t}|${n}|${o}`,kr=s=>{let r=s.split("|");if(r.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:r[0],project:r[1],repoName:r[2],prId:r[3],threadId:r[4],commentId:r[5]}},_r=(s,r,e,t,n)=>`${s}|${r}|${e}|${t}|${n}`,kt=s=>{let r=s.split("|");if(r.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:r[0],project:r[1],repoName:r[2],prId:r[3],threadId:r[4]}},Ee=(s,r)=>{let e=[],t=[];return r.reviewers.forEach(n=>{let o={reviewer:ue(n),state:en[n.vote??0]||"REVIEW_REQUESTED"};n.isRequired&&e.push(o),t.push(o)}),{id:r.pullRequestId.toString(),title:r.title,description:r.description??null,number:r.codeReviewId,state:Xs[r.status],isDraft:r.isDraft,commentCount:null,upvoteCount:null,author:ue(r.createdBy),createdDate:new Date(r.creationDate),updatedDate:new Date(r.closedDate||r.creationDate),closedDate:r.closedDate?new Date(r.closedDate):null,mergedDate:r.closedDate&&r.status==="completed"?new Date(r.closedDate):null,repository:{id:r.repository.id,name:r.repository.name,project:r.repository.project.name,owner:{login:s},remoteInfo:null},headCommit:{buildStatuses:null},baseRef:{name:Oe(r.targetRefName),oid:r.lastMergeTargetCommit.commitId},headRef:{name:Oe(r.sourceRefName),oid:r.lastMergeSourceCommit.commitId},url:xr(r),assignees:r.reviewers.map(ue),reviews:t,reviewDecision:H(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:r.forkSource?{id:r.forkSource.repository.id,name:r.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:null}:{id:r.repository.id,name:r.repository.name,project:r.repository.project.name,owner:{login:s},remoteInfo:null},mergeableState:tn(r.mergeStatus),labels:r.labels?.map(n=>({color:null,description:null,id:n.id,name:n.name}))??[],permissions:null}},Nr=(s,r)=>({id:r.id,name:r.name,namespace:s,project:r.project.name,projectId:r.project.id,webUrl:r.webUrl,httpsUrl:r.remoteUrl,sshUrl:r.sshUrl,defaultBranch:r.defaultBranch?{name:Oe(r.defaultBranch)}:null,permissions:null}),rn=(s,r,e,t)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=t[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:r,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()}))??[]}},me=class extends j{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,t){let n=JSON.stringify([e,t.token??null,t.isPAT??this.config.isPAT??!1,t.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,t,n);return this.inflightUserIds.set(n,a),a}async fetchCurrentUserId(e,t,n){try{let o=await this.getCurrentUserForInstance({namespace:e},t);return this.cachedUserIds.set(n,o.data.id),o.data.id}finally{this.inflightUserIds.delete(n)}}getRepoApiUrl(e,t,n,o){return`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(t)}/_apis/git/repositories/${encodeURIComponent(n)}`}async getCurrentUser(e={},t={}){if(t.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let n=`${Gt(this.config,t)}/profile/profiles/me`,o=await this.config.request({url:n,headers:P(this.config,t)});return{data:{id:o.body.id,name:o.body.displayName,username:o.body.displayName,email:o.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(e,t={}){let o=(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:P(this.config,t)})).body.authorizedUser;if(o.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:o.id,name:o.providerDisplayName,username:o.providerDisplayName,email:o.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:P(this.config,t)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,t={}){let n=`${Gt(this.config,t)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:n,headers:P(this.config,t)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,t={}){let n=`${C(this.config,t)}/_apis/projectCollections`;return{data:(await this.config.request({url:n,headers:P(this.config,t)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,t={}){let n=new URL(`${C(this.config,t)}/${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:P(this.config,t)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({id:a.id,name:a.name,namespace:e.namespace}))}}async getAzureProjectScopeDescriptor(e,t={}){let{namespace:n,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${Ot(this.config,t)}/${encodeURIComponent(n)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:P(this.config,t)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,t={}){let{namespace:n,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${Ot(this.config,t)}/${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:P(this.config,t)}),l=u.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:l||null,hasNextPage:!!l},data:u.body.value.map(d=>({avatarUrl:d._links?.avatar?.href??null,descriptor:d.descriptor??null,email:d.mailAddress??null,name:d.displayName??null,storageKeyURL:d._links?.storageKey?.href??null,username:d.displayName??null}))}}async getAccountFromAzureGraphAccount(e,t={}){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:P(this.config,t)});return{data:{avatarUrl:n.avatarUrl,email:n.email,id:o.body.value,name:n.name,username:n.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,t={}){let n=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},t);n.push(i.data)}return{data:n}}async getRepo(e,t={}){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,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:P(this.config,t)});return{data:Nr(e.namespace,n.body)}}async getRepos(e,t={}){let n=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,t);n.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:n,errors:o}}async getReposForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:P(this.config,t)})).body.value.map(o=>Nr(e.namespace,o))}}async getRefs(e,t,n={}){if(!t.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${C(this.config,n)}/${encodeURIComponent(t.repo.namespace)}/${encodeURIComponent(t.repo.project)}/_apis/git/repositories/${encodeURIComponent(t.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",$.toString()),t.cursor&&o.searchParams.set("continuationToken",t.cursor);let i=await this.config.request({url:o.toString(),headers:P(this.config,n)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Oe(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,t={}){return this.getRefs("heads",e,t)}async getTags(e,t={}){return this.getRefs("tags",e,t)}async getPullRequestsForRepoBase(e,t={},n=100){let{page:o,repo:i,assigneeLogins:a,authorLogin:u}=e||{},l=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let d="searchCriteria.status=1";return a&&a.length&&(d+=`&searchCriteria.reviewerId=${a[0]}`),u&&(d+=`&searchCriteria.creatorId=${u}`),await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${d}&%24top=${n}&%24skip=${(l-1)*n}`,headers:P(this.config,t)})}async getPullRequestsForRepo(e,t={}){let o=e.page||1,i=await this.getPullRequestsForRepoBase(e,t,100);return{pageInfo:{hasNextPage:i.body.value.length===100,nextPage:o+1},data:i.body.value.map(a=>Ee(e.repo.namespace,a))}}async getPullRequestsForRepos(e,t={}){if(!e.repos.every(i=>i.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:n}=e||{},o=[];return await Promise.all(n.map(async i=>{try{(await this.getPullRequestsForRepoBase({repo:i,...e},t)).body.value.forEach(u=>{o.push(Ee(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getPullRequestsForProjectBase(e,t={},n=100){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,repo:d}=e;if(d?.project&&d.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,p=new URL(`${C(this.config,t)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return p.searchParams.set("searchCriteria.status","1"),p.searchParams.set("$top",n.toString()),p.searchParams.set("$skip",((c-1)*n).toString()),d?.id&&d?.project===i&&p.searchParams.set("searchCriteria.repositoryId",d.id),u&&u.length&&p.searchParams.set("searchCriteria.reviewerId",u[0]),l&&p.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:p.toString(),headers:P(this.config,t)})}async getPullRequestsForProject(e,t={}){let o=e.page||1,i=await this.getPullRequestsForProjectBase(e,t,100);return{pageInfo:{hasNextPage:i?.body.value.length===100,nextPage:o+1},data:i?.body.value.map(a=>Ee(e.namespace,a))||[]}}async getPullRequestsForProjects(e,t={}){let{projects:n}=e||{},o=[];return await Promise.all(n.map(async i=>{try{(!e.repo||e.repo.project&&e.repo.project===i.project)&&(await this.getPullRequestsForProjectBase({...i,...e},t))?.body.value.forEach(u=>{o.push(Ee(i.namespace,u))})}catch(a){if(a.statusCode!==404&&a.statusCode!==401)throw a}})),{data:o}}async getAzurePullRequestLastMergeStatus(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:n,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...P(this.config,t)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,t,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:t,headers:{...P(this.config,n),"Content-Type":"application/json"}})}async closePullRequest(e,t={}){let{pullRequest:n}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(n,JSON.stringify(o),t)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,t={}){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),t)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,t={}){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,t)}/${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:{...P(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,t={}){let{pullRequest: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,t)}/${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:{...P(this.config,t)}})}async setPullRequestLabels(e,t={}){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},t);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:n,label:a},t)}async setPullRequestAsDraft(e,t={}){let{pullRequest:n,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(n,JSON.stringify(i),t)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,t={}){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,t)}/${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:{...P(this.config,t),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,t={}){let{pullRequest:n,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,t)}/${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:{...P(this.config,t),Accept:"application/json"}})}async setPullRequestReviewers(e,t={}){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},t);for(let i of n.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:n,reviewer:i},t)}async getIssuesForAzureProject(e,t={}){let{page:n,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},d=n||1,c=200,p=["[Microsoft.VSTS.Common.ClosedDate] = ''","[System.TeamProject] = @project","[Microsoft.VSTS.Common.ResolvedDate] = ''"];i&&p.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&p.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&p.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(h=>p.push(`[System.Tags] Contains '${h}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${p.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...P(this.config,t),"Content-Type":"application/json"}}),I=m.body.workItems.slice((d-1)*c,c*d).map(h=>h.id);if(I.length==0)return{pageInfo:{hasNextPage:!1,nextPage:null},data:[]};let y=await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:I,$expand:"Links"}),method:"POST",headers:{...P(this.config,t),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:m.body.workItems.length>c*d,nextPage:d+1},data:y.body.value.map(h=>rn(e.namespace,e.project,h,l||{}))}}async getPermissionsForRepos(e,t={}){let{namespace:n,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=c=>{let p="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${c.projectId}/${c.id}`;return Object.keys(i).map(m=>({securityNamespaceId:p,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,t)}/${encodeURIComponent(n)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...P(this.config,t),"Content-Type":"application/json"}})).body.evaluations.reduce((c,p)=>{let[,g,m]=p.token.split("/"),I=`${g}/${m}`,y=i[p.permissions];for(let h of y)c[I]===void 0&&(c[I]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),p.value===!1&&(c[I][h]=!1);return c},{})}}async decorateReposWithPermissions(e,t={}){let{namespace:n,repos:o}=e,i=await this.getPermissionsForRepos({namespace:n,repos:o},t);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,t,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(t),headers:{...P(this.config,n),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,t={}){let{issue:n,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(n,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,t={}){let{issue:n,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(n,i,t)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,t={}){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,t)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,t={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...P(this.config,t)}})).body.value}}async getLabelsForProject(e,t={}){let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,t)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...P(this.config,t)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,t={}){let{repo: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,t)}/pullrequests/${o}?api-version=7.1`,headers:P(this.config,t)});return{data:Ee(n.namespace,i.body)}}async getMergeBase(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:P(this.config,t)});if(!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,t={}){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,t)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...P(this.config,t),Accept:"application/octet-stream"}});return{data:new Blob([n.body])}}async getPullRequestDiff(e,t={}){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,t),o=P(this.config,t),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,d=a.body.lastMergeSourceCommit.commitId,c=u.body.value;if(c.length===0)return"";let p=c[c.length-1],g=1e3,m=[],I=0;for(;;){let E=(await this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations/${p.id}/changes?api-version=7.1&$top=${g}&$skip=${I}`,headers:o})).body.changeEntries??[];if(E.length===0||(m.push(...E),E.length<g))break;I+=E.length}if(m.length===0)return"";let y=5,h=[],q=new TextDecoder,D=w=>w instanceof ArrayBuffer?q.decode(w):typeof w=="string"?w:"",k=async(w,E)=>{try{let ne=await this.config.request({url:`${n}/items?path=${encodeURIComponent(w)}&versionDescriptor[version]=${encodeURIComponent(E)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return D(ne.body)}catch{return""}},S=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let E=w.toLowerCase().split(",").map(ne=>ne.trim());return{add:E.includes("add"),rename:E.includes("rename"),delete:E.includes("delete")}};for(let w=0;w<m.length;w+=y){let E=m.slice(w,w+y),ne=await Promise.all(E.map(async de=>{let{add:pe,rename:Dt,delete:oe}=S(de.changeType),ve=de.originalPath??de.item.originalPath,U=de.item.path,Ue=oe?U??ve??"":U??"",Ar=Dt||oe?ve??Ue:Ue,[ks,_s]=await Promise.all([pe?Promise.resolve(""):k(Ar,l),oe?Promise.resolve(""):k(Ue,d)]),Ns=pe?"/dev/null":`a${Ar}`,js=oe?"/dev/null":`b${Ue}`;return(0,jr.createTwoFilesPatch)(Ns,js,ks,_s)}));h.push(...ne)}return h.join(`
|
|
2
|
+
`)}getPullRequestWriteHeaders(e){return{...P(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,t,n,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${t}/reviewers/${encodeURIComponent(n)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,t,n,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${t}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:n,commentType:1}],status:1})})}async getCommentsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,t),o=P(this.config,t),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:xt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?ue(l.author):null,body:l.content||"",createdAt:l.publishedDate?new Date(l.publishedDate):null,url:""});return{data:a,pageInfo:{hasNextPage:!1,endCursor:null}}}async addCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,t)}async addInlineCommentToPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t),o=this.getPullRequestWriteHeaders(t);if(e.threadId){let d=kt(e.threadId),c=e.pullRequest.repository.owner.login,p=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(d.namespace!==c||d.project!==p||d.repoName!==g||d.prId!==m)throw new Error(`Azure thread ID context mismatch: threadId targets ${d.namespace}/${d.project}/${d.repoName} pull request ${d.prId}, but input.pullRequest targets ${c}/${p}/${g} pull request ${m}.`);let y=(await this.config.request({url:`${n}/pullRequests/${e.pullRequest.id}/threads/${d.threadId}?api-version=7.1`,headers:P(this.config,t)})).body.comments?.find(q=>q.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${d.threadId}.`);let h=await this.config.request({method:"POST",url:`${n}/pullRequests/${e.pullRequest.id}/threads/${d.threadId}/comments?api-version=7.1`,headers:o,body:JSON.stringify({content:e.comment,parentCommentId:y.id,commentType:1})});return xt(c,p,g,Number(m),Number(d.threadId),h.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let l=await this.config.request({method:"POST",url:`${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 _r(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,t={}){let n=kr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({content:e.body})})}async editInlineComment(e,t={}){return this.editComment(e,t)}async deleteComment(e,t={}){let n=kr(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:P(this.config,t)})}async deleteInlineComment(e,t={}){return this.deleteComment(e,t)}async resolveReviewThread(e,t={}){let n=kt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,t={}){let n=kt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,t);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(t),body:JSON.stringify({status:1})})}async approvePullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(n,t);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,t),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,t):null])}async requestPullRequestChanges(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,t),i=await this.getCurrentUserId(n,t);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,t),await this.setReviewerVote(o,e.pullRequest.id,i,-5,t)}async commentOnPullRequest(e,t={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,t);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,t)}async getReviewsForPullRequest(e,t={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(n,o,i,t),l=P(this.config,t),[d,c]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:l}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:l})]),p=(h,q)=>xt(n,o,i,a,h,q),g=h=>_r(n,o,i,a,h),m=new Map;for(let h of c.body.value){if(h.isDeleted)continue;let q=h.comments.filter(U=>!U.isDeleted&&U.commentType!=="system"),D=q.find(U=>U.parentCommentId===0)??q[0];if(!D)continue;let k=D.author?.id;if(!k)continue;let S=q.filter(U=>U.id!==D.id),w=h.threadContext,E=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,ne=E?.end?.line??E?.start.line??null,de=E?.start&&E.end&&E.start.line!==E.end.line?E.start.line:null,pe=w?.filePath??"",Dt=pe.startsWith("/")?pe.slice(1):pe,oe={id:p(h.id,D.id),author:D.author?ue(D.author):null,body:D.content??"",createdAt:D.publishedDate?new Date(D.publishedDate):null,url:"",diffLines:[],filename:Dt,replies:S.map(U=>({id:p(h.id,U.id),author:U.author?ue(U.author):null,body:U.content??"",createdAt:U.publishedDate?new Date(U.publishedDate):null,url:""})),isOutdated:!1,isResolved:Zs.has(Ys(h.status)),line:ne,startLine:de,side:E?.side??null,threadId:g(h.id)},ve=m.get(k);ve?ve.push(oe):m.set(k,[oe])}let I=[],y=new Set;for(let h of d.body.value){if(h.hasDeclined)continue;let q=h.vote??0,D=m.get(h.id);q===0&&!D?.length||(I.push({id:h.id,author:ue(h),body:"",createdAt:null,url:"",reviewComments:D??[]}),y.add(h.id))}for(let[h,q]of m){if(y.has(h)||!q.length)continue;let D=q[0].author;D&&I.push({id:h,author:D,body:"",createdAt:null,url:"",reviewComments:q})}return{data:I}}};var A=(s,r={})=>f(r.token||s.token,r.isPAT||s.isPAT);var T="https://api.bitbucket.org/2.0",sn={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},xe={owner:4,admin:3,contributor:2,member:1},ke=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}),Br=s=>{let r=s.links.clone,e=r?.find(n=>n.name==="ssh"),t=r?.find(n=>n.name==="https");return e&&t?{cloneUrlHTTPS:t.href,cloneUrlSSH:e.href}:null},_t=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(r=>r.name==="https")?.href??null,sshUrl:s.links.clone.find(r=>r.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),Nt=s=>{let r=s.id,e=s.participants?.map(t=>{let n="REVIEW_REQUESTED";return t.approved?n="APPROVED":t.state==="changes_requested"?n="CHANGES_REQUESTED":t.participated_on!==null&&(n="COMMENTED"),{reviewer:ke(t.user),state:n}})??[];return{id:r.toString(),title:s.title,description:s.description,number:r,state:sn[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:ke(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:Br(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:H(e),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:Br(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},nn=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}}},on=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}}},ge=class extends F{async refreshToken(r){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 ${r.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${r.refreshToken}`})).body}}async getCurrentUser(r={},e={}){let t=await this.config.request({url:`${T}/user`,headers:A(this.config,e)});return{data:ke(t.body)}}async getUserForCommit(r,e={}){let n=(await this.config.request({url:`${T}/repositories/${r.repo.namespace}/${r.repo.name}/commit/${r.oid}`,headers:A(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(r,e={}){let t=await this.config.request({url:`${T}/repositories/${r.namespace}/${r.name}`,headers:A(this.config,e)});return{data:_t(t.body)}}async getRepos(r,e={}){let t=[],n=[];return await Promise.all(r.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForWorkspace(r,e={}){let t=new URL(`${T}/repositories/${encodeURIComponent(r.workspace)}`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen",$.toString()),r.minimumRole&&t.searchParams.set("role",r.minimumRole);let n=await this.config.request({url:t.toString(),headers:A(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(_t)}}async getAllReposForWorkspace(r,e={}){let t=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:r.workspace,minimumRole:r.minimumRole,page:n},e);t.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return t}async getAllReposForWorkspaceWithPermissions(r,e={}){let t=new Map,n=[],o=xe[r.minimumRole||"member"];o<=xe.admin&&n.push("admin"),o<=xe.contributor&&n.push("contributor"),o<=xe.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:r.workspace,minimumRole:a},e);for(let u of i)t.has(u.id)||t.set(u.id,a)}return{data:i.map(a=>{let u=t.get(a.id)||"member";return{...a,permissions:on(u)}})}}async getReposForCurrentUser(r,e={}){let t=new URL(`${T}/repositories`);t.searchParams.set("role","member"),t.searchParams.set("pagelen",$.toString()),r.cursor&&t.searchParams.set("after",r.cursor);let n=await this.config.request({url:t.toString(),headers:A(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(_t)}}async getBranches(r,e={}){let t=new URL(`${T}/repositories/${r.repo.namespace}/${r.repo.name}/refs/branches`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen",$.toString());let n=await this.config.request({url:t.toString(),headers:A(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(r,e={}){let t=new URL(`${T}/repositories/${r.repo.namespace}/${r.repo.name}/refs/tags`);t.searchParams.set("pagelen",$.toString()),r.cursor&&t.searchParams.set("page",r.cursor);let n=await this.config.request({url:t.toString(),headers:A(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(r={},e={}){let t=new URL(`${T}/user/workspaces`);t.searchParams.set("page",r?.page?.toString()||"1"),t.searchParams.set("pagelen","50"),r?.administrator!==void 0&&t.searchParams.set("administrator",r.administrator.toString());let n=await this.config.request({url:t.toString(),headers:A(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(r,e={}){let t=new URL(`${T}/user/permissions/workspaces`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","50");let n=await this.config.request({url:t.toString(),headers:A(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(r,e={}){let t=new URL(`${T}/workspaces/${r.workspaceSlug}/pullrequests/${r.userId}`);if(t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","50"),r.repos&&r.repos.length>0){let i=`state = "open" AND (${r.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`;t.searchParams.set("q",i)}let n=await this.config.request({url:t.toString(),headers:A(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Nt)}}async getPullRequestsForRepoBase(r,e={}){let t=new URL(`${T}/repositories/${encodeURI(r.repo.namespace)}/${encodeURI(r.repo.name)}/pullrequests?state=OPEN`),n=[];r.reviewerId&&n.push(`reviewers.uuid="${r.reviewerId}"`),r.authorLogin&&n.push(`author.uuid="${r.authorLogin}"`);let o='state="OPEN"';return n.length&&(o+=` AND (${n.join(r.useOrFilter?" OR ":" AND ")})`),t.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","50"),t.searchParams.set("q",o),await this.config.request({url:t.toString(),headers:A(this.config,e)})}async getPullRequestsForRepo(r,e={}){let t=[],n=await this.getPullRequestsForRepoBase(r,e);n.body.values.forEach(i=>{t.push(Nt(i))});let o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:t}}async getPullRequestsForRepos(r,e={}){let t=[];return await Promise.all(r.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...r},e)).body.values.forEach(i=>{t.push(Nt(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getAccountsForWorkspace(r,e={}){let t=new URL(`${T}/workspaces/${encodeURI(r.workspace)}/members`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:A(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>ke(i.user))}}async getReposPermissionsForCurrentUser(r,e={}){let t=new URL(`${T}/user/permissions/repositories`);t.searchParams.set("page",r.page?.toString()||"1"),t.searchParams.set("pagelen","100");let n=await this.config.request({url:t.toString(),headers:A(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]:nn(a.permission)}),{})}}async decorateReposWithPermissions(r,e={}){let t={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);t={...o.data,...t},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:r.repos.map(o=>({...o,permissions:t[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(r,e={}){let{pullRequest:t}=r;if(!(await this.config.request({method:"POST",url:`${T}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/decline`,headers:A(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(r,e={}){let{pullRequest:t,mergeStrategy:n}=r,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:`${T}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}/merge`,body:JSON.stringify(i),headers:{...A(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(r,e={}){let{pullRequest:t,reviewers:n}=r,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:`${T}/repositories/${t.repository.owner.login}/${t.repository.name}/pullrequests/${t.id}`,body:JSON.stringify(o),headers:{...A(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var _e={};z(_e,{normalizePermissions:()=>jt,restApiPullRequestToCommonPullRequest:()=>an});var an=s=>Se(s),jt=s=>s?s.find(r=>r.permission==="USER_ADMIN"||r.permission==="PROJECT_ADMIN"||r.permission==="ADMIN"||r.permission==="SYS_ADMIN"||r.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(r=>r.permission==="REPO_WRITE"||r.permission==="REPO_CREATE"||r.permission==="PROJECT_CREATE"||r.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Ce=s=>{let r=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(r&&`${r}/avatar.png`),id:s.id.toString(),username:s.name,url:r}},Se=s=>{let r={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},t=s.reviewers.map(u=>({reviewer:Ce(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:r[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:Ce(s.author.user),assignees:null,reviews:t,reviewDecision:H(t),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}},Qr=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(r=>r.name==="https"||r.name==="http")?.href??null,sshUrl:s.links.clone.find(r=>r.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),he=class extends j{getBaseUrl(r){let e=r.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(r){return f(r.token||this.config.token)}async getCurrentUser(r={},e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=t,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:d,id:c,name:p,slug:g})=>i?i===c:a===p||a===d||a===g);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Ce(l)}}async getUserForCommit(r,e){let{repo:t,oid:n}=r,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Ce(o.body.author)}}async getRepo(r,e={}){let t=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}`,headers:this.getRequestHeaders(e)});return{data:Qr(t.body)}}async getRepos(r,e={}){let t=[],n=[];return await Promise.all(r.map(async o=>{try{let i=await this.getRepo(o,e);t.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:t,errors:n}}async getReposForCurrentUser(r,e={}){let t=r.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${t}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(Qr)}}async getRepoPermissionsForUsername(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${r.repo.namespace}/repos/${r.repo.name}/permissions/search?filterText=${r.username}`);try{let n=await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)});return{data:jt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(r,e={}){return await Promise.all(r.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:r.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(r.repo.namespace)}/repos/${encodeURI(r.repo.name)}/pull-requests?state=OPEN`);return t.searchParams.set("start",r.page?.toString()||"0"),t.searchParams.set("limit","50"),await this.config.request({url:t.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(r,e={}){let t=[],n=await this.getPullRequestsForRepoBase(r,e);n.body.values.forEach(i=>{if(r.authorLogin&&i.author.user.name!==r.authorLogin)return null;t.push(Se(i))});let o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:t}}async getPullRequestsForRepos(r,e={}){let t=[];return await Promise.all(r.repos.map(async n=>{try{(await this.getPullRequestsForRepoBase({repo:n,...r},e)).body.values.forEach(i=>{if(r.authorLogin&&i.author.user.name!==r.authorLogin)return null;t.push(Se(i))})}catch(o){if(o.statusCode!==404&&o.statusCode!==401)throw o}})),{data:t}}async getPullRequestsForCurrentUser(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);t.searchParams.set("state","OPEN"),t.searchParams.set("start",r.page?.toString()||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.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(Se)}}async closePullRequest(r,e={}){let{pullRequest:t}=r;if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/decline`,body:JSON.stringify({version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(r,e={}){let{pullRequest:t,mergeStrategyId:n}=r;if(r.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(t.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}/merge`,body:JSON.stringify({strategyId:n,version:t.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(r={}){let e=await this.config.request({url:`${this.getBaseUrl(r)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(r),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(r,e={}){let{pullRequest:t,reviewers:n}=r;if(t.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:t.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${t.repository.owner.login}/repos/${t.repository.name}/pull-requests/${t.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(r,e={}){let t=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(r.project)}/permissions/users`);t.searchParams.set("start",r.page?.toString()||"0"),t.searchParams.set("limit","50");let n=await this.config.request({url:t.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=>Ce(i.user))}}};var ss=require("js-base64");var Ne=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(Ne||{});var R=class extends Error{constructor(e,t){let n=t?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=t??[]}};var un={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]},Fr=15,Mr=100,De={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},G=s=>!!s,J=(s,r)=>{let e=un[r];for(let t=0;t<3;t++){if(s[t]>e[t])return!0;if(s[t]<e[t])return!1}return!0},Be="https://api.github.com",ln=`${Be}/graphql`,Qe=`
|
|
3
3
|
description
|
|
4
4
|
dueOn
|
|
5
5
|
id
|
|
@@ -7,7 +7,7 @@ number
|
|
|
7
7
|
state
|
|
8
8
|
title
|
|
9
9
|
url
|
|
10
|
-
`,
|
|
10
|
+
`,dn=`
|
|
11
11
|
... on CheckRun {
|
|
12
12
|
completedAt
|
|
13
13
|
conclusion
|
|
@@ -21,16 +21,16 @@ color
|
|
|
21
21
|
description
|
|
22
22
|
id
|
|
23
23
|
name
|
|
24
|
-
`,zr=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.")},
|
|
24
|
+
`,zr=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.")},pn=(s,r)=>{let e=r.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),zr(e),je.test(e)&&(e=e.replace(je,"")),`${e}/api/graphql`):ln},le=(s,r)=>{let e=r.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),zr(e),je.test(e)&&(e=e.replace(je,"")),`${e}/api/v3`):Be},b=(s,r,e)=>{let t=f(e.token||s.token);return t["X-Github-Next-Global-ID"]="1",t["Content-Type"]="application/json",t.Accept="application/vnd.github.merge-info-preview+json",s.request({url:pn(s,e),method:"POST",headers:t,body:JSON.stringify(r)})},cn={user:!0,"user:email":!0,"read:user":!0},Y=s=>s.some(r=>cn[r]),B=(s=!1,r=!1,e)=>`
|
|
25
25
|
__typename
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
${r?
|
|
31
|
-
${
|
|
32
|
-
${
|
|
33
|
-
`,
|
|
26
|
+
${re(e,["graphQLId"],"id")}
|
|
27
|
+
${re(e,["id"],"databaseId")}
|
|
28
|
+
${re(e,["name"],"name")}
|
|
29
|
+
${re(e,["name","username"],"login")}
|
|
30
|
+
${r?re(e,["email"],"email"):""}
|
|
31
|
+
${re(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
|
|
32
|
+
${re(e,["url"],"url")}
|
|
33
|
+
`,mn=(s=!1)=>`
|
|
34
34
|
latestReviews(first: 100) {
|
|
35
35
|
nodes {
|
|
36
36
|
author {
|
|
@@ -38,7 +38,7 @@ latestReviews(first: 100) {
|
|
|
38
38
|
${B(!1,s)}
|
|
39
39
|
}
|
|
40
40
|
... on EnterpriseUserAccount {
|
|
41
|
-
${
|
|
41
|
+
${Bt(!1)}
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
44
|
state
|
|
@@ -51,7 +51,7 @@ databaseId
|
|
|
51
51
|
login
|
|
52
52
|
avatarUrl${s?"(size: $avatarSize)":""}
|
|
53
53
|
url
|
|
54
|
-
`,
|
|
54
|
+
`,Bt=(s=!1)=>`
|
|
55
55
|
__typename
|
|
56
56
|
id
|
|
57
57
|
login
|
|
@@ -59,7 +59,7 @@ avatarUrl${s?"(size: $avatarSize)":""}
|
|
|
59
59
|
url
|
|
60
60
|
`,Me=(s,r=!1,e)=>`
|
|
61
61
|
id
|
|
62
|
-
${!e||
|
|
62
|
+
${!e||J(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
63
63
|
number
|
|
64
64
|
title
|
|
65
65
|
body
|
|
@@ -72,7 +72,7 @@ author {
|
|
|
72
72
|
${Wr(!1)}
|
|
73
73
|
}
|
|
74
74
|
... on EnterpriseUserAccount {
|
|
75
|
-
${
|
|
75
|
+
${Bt(!1)}
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
78
|
commits(last: 1) {
|
|
@@ -85,7 +85,7 @@ commits(last: 1) {
|
|
|
85
85
|
contexts(first: 100) {
|
|
86
86
|
totalCount
|
|
87
87
|
nodes {
|
|
88
|
-
${!e||
|
|
88
|
+
${!e||J(e,"CHECK_RUN")?dn:""}
|
|
89
89
|
... on StatusContext {
|
|
90
90
|
context
|
|
91
91
|
createdAt
|
|
@@ -152,7 +152,7 @@ assignees(first: 100) {
|
|
|
152
152
|
}
|
|
153
153
|
reviewRequests(first: 100) {
|
|
154
154
|
nodes {
|
|
155
|
-
${!e||
|
|
155
|
+
${!e||J(e,"AS_CODE_OWNER")?"asCodeOwner":""}
|
|
156
156
|
requestedReviewer {
|
|
157
157
|
... on User {
|
|
158
158
|
${B(!1,r)}
|
|
@@ -160,7 +160,7 @@ reviewRequests(first: 100) {
|
|
|
160
160
|
}
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
|
-
${!e||
|
|
163
|
+
${!e||J(e,"LATEST_REVIEWS")?mn(r):""}
|
|
164
164
|
additions
|
|
165
165
|
deletions
|
|
166
166
|
changedFiles
|
|
@@ -174,10 +174,10 @@ labels(first: 100) {
|
|
|
174
174
|
${Fe}
|
|
175
175
|
}
|
|
176
176
|
}
|
|
177
|
-
${!e||
|
|
178
|
-
`,
|
|
177
|
+
${!e||J(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
|
|
178
|
+
`,gn=(s=!1,r)=>`
|
|
179
179
|
id
|
|
180
|
-
${!r||
|
|
180
|
+
${!r||J(r,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
181
181
|
title
|
|
182
182
|
author {
|
|
183
183
|
... on User {
|
|
@@ -187,7 +187,7 @@ author {
|
|
|
187
187
|
${Wr(!1)}
|
|
188
188
|
}
|
|
189
189
|
... on EnterpriseUserAccount {
|
|
190
|
-
${
|
|
190
|
+
${Bt(!1)}
|
|
191
191
|
}
|
|
192
192
|
}
|
|
193
193
|
closedAt
|
|
@@ -223,7 +223,7 @@ labels(first: 100) {
|
|
|
223
223
|
${Fe}
|
|
224
224
|
}
|
|
225
225
|
}
|
|
226
|
-
`,
|
|
226
|
+
`,hn={"-linked":"-linked",archived:"archived",assignee:"assignee",author:"author",base:"base",closed:"closed",commenter:"commenter",comments:"comments",created:"created",draft:"draft",head:"head",label:"label",language:"language",linked:"linked",in:"in",interactions:"interactions",involves:"involves",is:"is",mentions:"mentions",merged:"merged",milestone:"milestone",no:"no",org:"org",project:"project",reactions:"reactions",repo:"repo",review:"review","reviewed-by":"reviewed-by","review-requested":"review-requested",state:"state",status:"status",team:"team","team-review-requested":"team-review-requested",type:"type",updated:"updated",user:"user","user-review-requested":"user-review-requested"},fn=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Qt=s=>{let r=[];return(s.match(fn)??[]).forEach(t=>{if(t.includes(":")&&t!="is:closed"){let n=t.split(":")[0];hn[n]&&r.push(t)}}),r},Ft=(s,r,e,t)=>{let n=s==="issue";return{query:`
|
|
227
227
|
query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
228
228
|
search(type:ISSUE query:$query first: ${t.maxPageSize} after:$after) {
|
|
229
229
|
pageInfo {
|
|
@@ -232,18 +232,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
232
232
|
}
|
|
233
233
|
nodes {
|
|
234
234
|
... on ${n?"Issue":"PullRequest"} {
|
|
235
|
-
${n?
|
|
235
|
+
${n?gn(t.supportsEmail,t.enterpriseVersion??null):Me(t.supportsDrafts??!1,t.supportsEmail,t.enterpriseVersion??null)}
|
|
236
236
|
}
|
|
237
237
|
}
|
|
238
238
|
}
|
|
239
|
-
}`,variables:{query:`is:${s} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${r}`,after:e}}},
|
|
239
|
+
}`,variables:{query:`is:${s} is:open ${t.includeFromArchivedRepos?"":"archived:false"} ${r}`,after:e}}},Rn="Field 'isDraft' doesn't exist on type 'PullRequest'",ze=(s=[])=>s.some(r=>r?.message===Rn),In=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,bn=`
|
|
240
240
|
\
|
|
241
|
-
+`,Hr=(s,r,e,t)=>{let n=
|
|
241
|
+
+`,Hr=(s,r,e,t)=>{let n=In.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(bn,`
|
|
242
242
|
+`).split(`
|
|
243
|
-
`).slice(1),u=o-1,l=i-1,
|
|
243
|
+
`).slice(1),u=o-1,l=i-1,d=a.map(g=>{let m,I;switch(g[0]){case"-":{m="DELETED",u+=1,I=`${g.slice(1)}
|
|
244
244
|
`;break}case"+":{m="ADDED",l+=1,I=`${g.slice(1)}
|
|
245
245
|
`;break}default:m="UNMODIFIED",l+=1,u+=1,I=`${g}
|
|
246
|
-
`}return{line:I,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),c=e,
|
|
246
|
+
`}return{line:I,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),c=e,p=r;if(c!==null&&p!==null&&t!==null&&c<p){let g=0,m=d.length,I=t==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<d.length;y++){let q=d[y][I];q===c?g=y:q===p&&(m=y)}d=d.slice(g,m+1)}return d},Jr=s=>{let r=s.author;return r||(r=De),{author:{id:"databaseId"in r?r.databaseId.toString():r.id,graphQLId:r.id,name:("name"in r?r.name:r.login)??r.login,username:r.login,email:("email"in r?r.email:null)??null,avatarUrl:r.avatarUrl,url:r.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 Vr=`mutation DeleteIssueComment(
|
|
247
247
|
$issueCommentId: ID!
|
|
248
248
|
) {
|
|
249
249
|
deleteIssueComment(input: {
|
|
@@ -355,7 +355,7 @@ query GetPullRequestComments(
|
|
|
355
355
|
}
|
|
356
356
|
}
|
|
357
357
|
}
|
|
358
|
-
`;var
|
|
358
|
+
`;var Mt=`
|
|
359
359
|
id
|
|
360
360
|
databaseId
|
|
361
361
|
owner {
|
|
@@ -368,10 +368,10 @@ defaultBranchRef {
|
|
|
368
368
|
name
|
|
369
369
|
}
|
|
370
370
|
viewerPermission
|
|
371
|
-
`,
|
|
371
|
+
`,yn={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},wn={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},Pn={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},vn={OPEN:"OPEN",CLOSED:"CLOSED"},qn=["ADMIN","MAINTAIN","TRIAGE","WRITE"],Ht=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),En=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:En(s.viewerPermission)}),Sn=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),rs=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:Sn(s.permissions)}),Cn=s=>({path:s.path,isDirectory:s.type==="tree"}),Dn={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},$n={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},M=(s,r=$n)=>{let e={};return r.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),r.graphQLId&&(e.graphQLId=s.id),r.name&&(e.name=s.name??s.login),r.username&&(e.username=s.login),r.email&&(e.email=s.email??null),r.avatarUrl&&(e.avatarUrl=s.avatarUrl),r.url&&(e.url=s.url),e},An=(s,r)=>{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"}[r]},Ln=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],Wt=s=>{let r=null;s.author?r=s.author:r=De;let e=(s.reviewRequests?.nodes||[]).filter(G).filter(i=>!i.asCodeOwner),t=s.headRepository?.url;t&&!t.endsWith(".git")&&(t=`${t}.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:M(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(G).map(i=>{let a=De;return i.author&&i.author.__typename&&(a=i.author),{reviewer:M(a),state:yn[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:Dn[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:r&&r.__typename?M(r):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:s.repository.sshUrl}},headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:t,cloneUrlSSH:s.headRepository.sshUrl}}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(G)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(G).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Ln(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:An(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:s.headRef?{name:s.headRef.name,oid:s.headRef.target?.oid??null}:null,baseRef:s.baseRef?{name:s.baseRef.name,oid:s.baseRef.target?.oid??null}:null,url:s.url,updatedDate:new Date(s.updatedAt),closedDate:s.closedAt?new Date(s.closedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees.nodes?s.assignees.nodes.filter(G).map(i=>M(i)):null,reviews:o,reviewDecision:H(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:Pn[s.mergeStateStatus]??wn[s.mergeable],milestone:s.milestone?Jt(s.milestone):null,labels:s.labels?.nodes?.filter(G).map(Ht)??[],permissions:{canMerge:qn.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Un=s=>{let{id:r,comments:e,isOutdated:t,isResolved:n,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:d}=s,c=e.nodes?.[0];if(!c)return null;let{author:p,body:g,databaseId:m,fullDatabaseId:I,id:y,path:h,publishedAt:q,url:D}=c,k=o??u,S=i??l,w=a??d;return{author:p?{avatarUrl:p.avatarUrl,email:null,name:p.login}:null,body:g,createdAt:q?new Date(q):null,diffLines:Hr(c.diffHunk,k,S,w),id:I??m.toString(),isOutdated:t,isResolved:n,graphQLId:y,threadId:r,filename:h,replies:e.nodes?.filter(G).slice(1).map(Tn)??[],url:D,line:k,startLine:S,side:w}},Tn=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}),Gn=s=>{let r=null;return s.author?r=s.author:r=De,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:r&&r.__typename?M(r):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:vn[s.state],color:null},type:null,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login}},url:s.url,updatedDate:new Date(s.updatedAt),assignees:s.assignees.nodes?.filter(G).map(e=>M(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?Jt(s.milestone):null,labels:s.labels?.nodes?.filter(G).map(Ht)??[]}},Jt=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}),fe=class extends j{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let t=e.token||this.config.token;if(!t)return[];let n=this._scopesCache[t];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[t]=n}return n}async getEnterpriseVersion(e){let t=e.baseUrl||this.config.baseUrl;if(!t)return null;let n=this._enterpriseVersionsCache[t];if(!n){let o=await this.config.request({url:`${le(this.config,e)}/meta`,headers:f(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[t]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,t,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(Be)?e:t?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(t)}`:""}async getCurrentUser(e={},t={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=Gr(e.fields),o=await this.getScopes(t),i=await b(this.config,{query:`
|
|
372
372
|
query getCurrentUser {
|
|
373
373
|
viewer {
|
|
374
|
-
${B(!1,
|
|
374
|
+
${B(!1,Y(o),n)}
|
|
375
375
|
}
|
|
376
376
|
}
|
|
377
377
|
`},t),a=i.body.data?.viewer;if(!a)throw new R("Current user not found.",i.body.errors);return{data:M(a,n)}}async getAccountsForRepo(e,t={}){let n=await this.getScopes(t),{repo:{namespace:o,name:i},cursor:a}=e,u=await b(this.config,{query:`
|
|
@@ -379,7 +379,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
|
|
|
379
379
|
repository(owner: $owner, name: $name) {
|
|
380
380
|
assignableUsers(first: $first, after: $cursor) {
|
|
381
381
|
nodes {
|
|
382
|
-
${B(!1,
|
|
382
|
+
${B(!1,Y(n))}
|
|
383
383
|
}
|
|
384
384
|
pageInfo {
|
|
385
385
|
endCursor
|
|
@@ -434,12 +434,12 @@ mutation createCommitOnBranch(
|
|
|
434
434
|
}
|
|
435
435
|
}
|
|
436
436
|
}
|
|
437
|
-
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([
|
|
437
|
+
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([d,c])=>({contents:ss.Base64.encode(c),path:d})),deletions:o.map(d=>({path:d}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},t);if(!l.body.data)throw new R("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,t={}){let n=await this.getScopes(t),o=await b(this.config,{query:`
|
|
438
438
|
query getAccountForEmail($query: String! $avatarSize: Int) {
|
|
439
439
|
search(query: $query, type: USER, first: 1) {
|
|
440
440
|
nodes {
|
|
441
441
|
... on User {
|
|
442
|
-
${B(!0,
|
|
442
|
+
${B(!0,Y(n))}
|
|
443
443
|
}
|
|
444
444
|
}
|
|
445
445
|
}
|
|
@@ -447,7 +447,7 @@ query getAccountForEmail($query: String! $avatarSize: Int) {
|
|
|
447
447
|
`,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},t),i=o.body.data?.search?.nodes?.[0];if(!i)throw new R("Could not find user via email",o.body.errors);return{data:M({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getAccountForUsername(e,t={}){let n=await this.getScopes(t),o=await b(this.config,{query:`
|
|
448
448
|
query getUserForUsername($login: String! $avatarSize: Int) {
|
|
449
449
|
user(login: $login) {
|
|
450
|
-
${B(!0,
|
|
450
|
+
${B(!0,Y(n))}
|
|
451
451
|
}
|
|
452
452
|
}
|
|
453
453
|
`,variables:{login:e.username,avatarSize:e.avatarSize}},t),i=o.body.data?.user;if(!i)throw new R("Could not find user via username",o.body.errors);return{data:M({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)})}}async getOrgsForCurrentUser(e={},t={}){let n=await b(this.config,{query:`
|
|
@@ -488,19 +488,19 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
|
488
488
|
`,variables:{cursor:e.cursor,first:$,login:e.org}},t);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new R("Could not read the members of the organization",n.body.errors);let o=n.body.data?.viewer.organization?.membersWithRole.nodes||[];return{pageInfo:{hasNextPage:n.body.data?.viewer.organization?.membersWithRole.pageInfo.hasNextPage??!1,endCursor:n.body.data?.viewer.organization?.membersWithRole.pageInfo.endCursor??null},data:o.map(i=>M({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,t)}))}}async getRepo(e,t={}){let n=await b(this.config,{query:`
|
|
489
489
|
query getRepo($owner: String!, $name: String!) {
|
|
490
490
|
repository(owner: $owner, name: $name) {
|
|
491
|
-
${
|
|
491
|
+
${Mt}
|
|
492
492
|
}
|
|
493
493
|
}
|
|
494
|
-
`,variables:{owner:e.namespace,name:e.name}},t);if(!n.body.data?.repository)throw new R(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:
|
|
495
|
-
getRepo_${
|
|
496
|
-
${
|
|
494
|
+
`,variables:{owner:e.namespace,name:e.name}},t);if(!n.body.data?.repository)throw new R(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:zt(n.body.data.repository)}}async getRepos(e,t={}){let n=e.map(({namespace:u,name:l},d)=>`
|
|
495
|
+
getRepo_${d}: repository(owner: "${u}", name: "${l}") {
|
|
496
|
+
${Mt}
|
|
497
497
|
}
|
|
498
498
|
`).join(`
|
|
499
499
|
`),o=await b(this.config,{query:`
|
|
500
500
|
query batchGetRepos {
|
|
501
501
|
${n}
|
|
502
502
|
}
|
|
503
|
-
`},t);if(!o.body.data)throw new R("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let
|
|
503
|
+
`},t);if(!o.body.data)throw new R("Could not fetch repos",o.body.errors);let i=[],a=[];return e.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(zt(d)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,t,n,o){let i=[];for(let c=0;c<t;c++)i.push(n(e+c));let a=await Promise.all(i),u=[];for(let c of a){if(!c.body)throw new Error(c.statusText||"Unknown error");u=u.concat(c.body.map(p=>o(p)))}let l=a.every(c=>c.body.length===100),d=e+t;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?d:null}}}async getReposForCurrentUser(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${le(this.config,t)}/user/repos?${n.toString()}&page=${i}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,rs)}async getReposForOrg(e,t={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${le(this.config,t)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,n,rs)}async getReposForUsernames(e,t={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await b(this.config,{query:`
|
|
504
504
|
query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
505
505
|
search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
|
|
506
506
|
pageInfo {
|
|
@@ -509,12 +509,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
|
509
509
|
}
|
|
510
510
|
nodes {
|
|
511
511
|
... on Repository {
|
|
512
|
-
${
|
|
512
|
+
${Mt}
|
|
513
513
|
}
|
|
514
514
|
}
|
|
515
515
|
}
|
|
516
516
|
}
|
|
517
|
-
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:$}},t);if(!n.body.data)throw new R("Could not fetch repos for usernames",n.body.errors);let o=n.body.data.search.nodes||[];return{pageInfo:n.body.data.search.pageInfo,data:o.map(
|
|
517
|
+
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:$}},t);if(!n.body.data)throw new R("Could not fetch repos for usernames",n.body.errors);let o=n.body.data.search.nodes||[];return{pageInfo:n.body.data.search.pageInfo,data:o.map(zt)}}async getReposForOwners(e,t={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},t)}async getRefs(e,t,n={}){let o=await b(this.config,{query:`
|
|
518
518
|
query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
|
|
519
519
|
repository(owner: $owner, name: $name) {
|
|
520
520
|
refs(refPrefix: $refPrefix first: $first after: $cursor) {
|
|
@@ -574,7 +574,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
574
574
|
}
|
|
575
575
|
}
|
|
576
576
|
}
|
|
577
|
-
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=n.body.data?.repository;if(!o)throw new R("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new R("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new R("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,t={}){let n=await this.config.request({url:`${
|
|
577
|
+
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},t),o=n.body.data?.repository;if(!o)throw new R("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new R("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new R("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,t={}){let n=await this.config.request({url:`${le(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...f(t.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async getMergeBase(e,t={}){return{data:(await this.config.request({url:`${le(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:f(t.token||this.config.token)})).body.merge_base_commit.sha}}async searchPullRequests(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=Y(o),a=d=>{let c=d&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Ft("pr",c,e.cursor,{maxPageSize:e.maxPageSize??Fr,supportsEmail:i,supportsDrafts:d,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos})},u=await b(this.config,a(!0),t);u.body.errors&&ze(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not search pull requests",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(G).map(Wt)||[]}}async searchIssues(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=Y(o),a=await b(this.config,Ft("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??Mr,enterpriseVersion:n}),t),{data:u}=a.body;if(!u)throw new R("Could not search issues",a.body.errors);return{pageInfo:{hasNextPage:u.search.pageInfo.hasNextPage,endCursor:u.search.pageInfo.endCursor},data:u.search.nodes?.filter(G).map(Gn)||[]}}async getPullRequestsAssociatedWithUser(e,t={}){let n=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{n.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{n.push(`label:"${o}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async getPullRequestsForRepos(e,t={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:d,labelNames:c,maxPageSize:p}=e,g=Qt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),d&&g.push(`mentions:${d}`),c&&c.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:p},t)}async getPullRequestForRepo(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=Y(o),a=c=>({query:`query getPullRequest(
|
|
578
578
|
$owner: String!
|
|
579
579
|
$name: String!
|
|
580
580
|
$number: Int!
|
|
@@ -587,7 +587,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
587
587
|
${Me(c,i,n)}
|
|
588
588
|
}
|
|
589
589
|
}
|
|
590
|
-
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),t);u.body.errors&&ze(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not fetch pull request by number",u.body.errors);let
|
|
590
|
+
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),t);u.body.errors&&ze(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not fetch pull request by number",u.body.errors);let d=u.body.data?.repository.pullRequest;return{data:d?Wt(d):null}}async getPullRequestByGraphQLId(e,t={}){let n=await this.getEnterpriseVersion(t),o=await this.getScopes(t),i=Y(o),a=c=>({query:`query getPullRequest(
|
|
591
591
|
$graphQLId: ID!
|
|
592
592
|
) {
|
|
593
593
|
node(id: $graphQLId) {
|
|
@@ -595,7 +595,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
595
595
|
${Me(c,i,n)}
|
|
596
596
|
}
|
|
597
597
|
}
|
|
598
|
-
}`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),t);u.body.errors&&ze(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not fetch pull request by id",u.body.errors);let
|
|
598
|
+
}`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),t);u.body.errors&&ze(u.body.errors)&&(this.config.baseUrl||t.baseUrl)&&(u=await b(this.config,a(!1),t));let{data:l}=u.body;if(!l)throw new R("Could not fetch pull request by id",u.body.errors);let d=u.body.data?.node;return{data:d?Wt(d):null}}async closePullRequest(e,t={}){let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
|
|
599
599
|
closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
|
|
600
600
|
pullRequest {
|
|
601
601
|
id
|
|
@@ -706,7 +706,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
706
706
|
}
|
|
707
707
|
}
|
|
708
708
|
}
|
|
709
|
-
}`,
|
|
709
|
+
}`,d=await b(this.config,{query:l,variables:{pullRequestId:n.graphQLId,body:o,path:i,line:a,side:u}},t);if(!d.body.data?.addPullRequestReview?.pullRequestReview?.id)throw new R("Could not add inline comment to pull request",d.body.errors);return d.body.data?.addPullRequestReview?.pullRequestReview?.comments?.nodes?.[0]?.id}async setPullRequestMilestone(e,t={}){let{pullRequest:n,milestone:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestMilestone($pullRequestGraphQLId: ID!, $milestoneGraphQLId: ID) {
|
|
710
710
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, milestoneId: $milestoneGraphQLId }) {
|
|
711
711
|
pullRequest {
|
|
712
712
|
id
|
|
@@ -730,7 +730,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
730
730
|
id
|
|
731
731
|
}
|
|
732
732
|
}
|
|
733
|
-
}`,
|
|
733
|
+
}`,d=await b(this.config,{query:l,variables:{pullRequestGraphQLId:o,reviewerGraphQLIds:u}},t);if(!d.body.data?.requestReviews?.pullRequest?.id)throw new R("Could not set pull request reviewers",d.body.errors)}async reRequestPullRequestReviews(e,t={}){let{pullRequest:{reviews:n,graphQLId:o},reviewers:i}=e;if(!o)throw new Error('GitHub requires "graphQLId" for this function.');if(!n)throw new Error('GitHub requires "reviews" for this function.');let a=[];for(let d of i){if(!d.graphQLId)throw new Error('GitHub requires reviwer "graphQLId" for this function.');if(!n.find(c=>c.reviewer.graphQLId===d.graphQLId))throw new Error("Can only re-request review from existing reviewer.");a.push(d.graphQLId)}let u=`mutation SetPullRequestReviewers($pullRequestGraphQLId: ID!, $reviewerGraphQLIds: [ID!]!) {
|
|
734
734
|
requestReviews(input: { pullRequestId: $pullRequestGraphQLId, userIds: $reviewerGraphQLIds, union: true }) {
|
|
735
735
|
pullRequest {
|
|
736
736
|
id
|
|
@@ -770,7 +770,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
770
770
|
login
|
|
771
771
|
}
|
|
772
772
|
body
|
|
773
|
-
${!n||
|
|
773
|
+
${!n||J(n,"PR_REVIEW_COMMENT_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
774
774
|
diffHunk
|
|
775
775
|
id
|
|
776
776
|
path
|
|
@@ -790,7 +790,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
790
790
|
login
|
|
791
791
|
}
|
|
792
792
|
body
|
|
793
|
-
${!n||
|
|
793
|
+
${!n||J(n,"PR_REVIEW_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
794
794
|
id
|
|
795
795
|
publishedAt
|
|
796
796
|
url
|
|
@@ -798,13 +798,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
798
798
|
}
|
|
799
799
|
}
|
|
800
800
|
}
|
|
801
|
-
}`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),
|
|
801
|
+
}`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},t),d=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(G).reduce((p,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return p;let m=g.comments.nodes[0].pullRequestReview,I=Un(g);return I&&(p[m.id]||(p[m.id]=[]),p[m.id].push(I)),p},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(G).filter(p=>d[p.id]).map(p=>({author:p.author?{avatarUrl:p.author.avatarUrl,email:null,name:p.author.login}:null,body:p.body,createdAt:p.publishedAt?new Date(p.publishedAt):null,id:p.fullDatabaseId??p.databaseId.toString(),graphQLId:p.id,reviewComments:d[p.id],url:p.url}))??[]}}async getCommentsForPullRequest(e,t={}){let n=await this.getEnterpriseVersion(t),o=!n||J(n,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,d=await b(this.config,{query:ts(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:$}},t),c=d.body.data?.repository;if(!c)throw new R("Could not fetch pull request comments",d.body.errors);return{data:c.pullRequest.comments.nodes?.filter(G).map(Jr)??[],pageInfo:c.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,t={}){let[n,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(p=>{i.push(`label:"${p}"`)});let[a,u]=await Promise.all([n==="null"?null:this.searchIssues({query:`author:${e.username} ${i.join(" ")}`,cursor:n,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)]),l={},d=[],c=p=>{l[p.id]||(l[p.id]=!0,d.push(p))};return a?.data.forEach(c),u?.data.forEach(c),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:d}}async setPullRequestLabels(e,t={}){let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
|
|
802
802
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
|
|
803
803
|
pullRequest {
|
|
804
804
|
id
|
|
805
805
|
}
|
|
806
806
|
}
|
|
807
|
-
}`,a=await b(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new R("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let n=
|
|
807
|
+
}`,a=await b(this.config,{query:i,variables:{pullRequestGraphQLId:n.graphQLId,labelGraphQLIds:o.map(u=>{if(!u.graphQLId)throw new Error('GitHub requires label "graphQLId" for this function.');return u.graphQLId})}},t);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new R("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,t={}){let n=Qt(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:d}=e;return e.repos.forEach(c=>{n.push(`repo:${c.namespace}/${c.name}`)}),i&&i.forEach(c=>{n.push(`assignee:${c}`)}),a&&n.push(`updated:<${a}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),d&&d.forEach(c=>{n.push(`label:"${c}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},t)}async closeIssueWithReason(e,t={}){let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
|
|
808
808
|
closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
|
|
809
809
|
issue {
|
|
810
810
|
id
|
|
@@ -854,7 +854,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
854
854
|
}
|
|
855
855
|
}
|
|
856
856
|
}
|
|
857
|
-
`,variables:{owner:n,name:o,cursor:i,first:$}},t);if(!a.body.data)throw new R("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(
|
|
857
|
+
`,variables:{owner:n,name:o,cursor:i,first:$}},t);if(!a.body.data)throw new R("Could not fetch milestones",a.body.errors);return{pageInfo:a.body.data.repository.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.milestones?.nodes?.map(Jt)??[]}}async getLabelsForRepo(e,t={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await b(this.config,{query:`
|
|
858
858
|
query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
859
859
|
repository(owner: $owner, name: $name) {
|
|
860
860
|
labels(first: $first, after: $cursor) {
|
|
@@ -868,7 +868,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
868
868
|
}
|
|
869
869
|
}
|
|
870
870
|
}
|
|
871
|
-
`,variables:{owner:n,name:o,cursor:i,first:$}},t);if(!a.body.data)throw new R("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(
|
|
871
|
+
`,variables:{owner:n,name:o,cursor:i,first:$}},t);if(!a.body.data)throw new R("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(Ht)??[]}}async getTreeForRepo(e,t={}){let n=await this.config.request({url:`${le(this.config,t)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...f(t.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(Cn)}}};var On="https://gitlab.com/api/v4",xn="https://gitlab.com/api/graphql",Vt=/\/api\/v\d+$/,ns=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.")},L=(s,r)=>{let e=r.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),ns(e),Vt.test(e)||(e=e+"/api/v4"),e):On},kn=(s,r)=>{let e=r.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),ns(e),Vt.test(e)&&(e=e.replace(Vt,"")),`${e}/api/graphql`):xn},v=(s,r,e)=>{let t=f(e.token||s.token);return s.request({url:kn(s,e),method:"POST",headers:{...t,"Content-Type":"application/json"},body:JSON.stringify(r)})},$e=s=>s?.map(r=>`"${r.message}"`).join(", ");var nr=s=>s.split("/").slice(0,-1).join("/"),or=s=>s.split("/").at(-1)??"",We=s=>({id:s.id.replace(Re,""),graphQLId:s.id,namespace:nr(s.fullPath),name:or(s.fullPath),webUrl:s.webUrl}),He=s=>({id:s.id.replace(Re,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:nr(s.fullPath),name:or(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),_n={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Nn={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var is="gid://gitlab/User/",Re="gid://gitlab/Project/",jn="gid://gitlab/MergeRequest/",Bn="gid://gitlab/Issue/",Qn="gid://gitlab/ProjectLabel/",Fn="gid://gitlab/Milestone/",Mn="gid://gitlab/Ci::Build/",ir=`
|
|
872
872
|
description
|
|
873
873
|
dueDate
|
|
874
874
|
id
|
|
@@ -877,7 +877,7 @@ startDate
|
|
|
877
877
|
state
|
|
878
878
|
title
|
|
879
879
|
webPath
|
|
880
|
-
`,
|
|
880
|
+
`,Kt=`
|
|
881
881
|
id
|
|
882
882
|
fullPath
|
|
883
883
|
webUrl
|
|
@@ -891,25 +891,25 @@ userPermissions {
|
|
|
891
891
|
downloadCode
|
|
892
892
|
pushCode
|
|
893
893
|
}
|
|
894
|
-
`,
|
|
894
|
+
`,Z=`
|
|
895
895
|
id
|
|
896
896
|
name
|
|
897
897
|
username
|
|
898
898
|
publicEmail
|
|
899
899
|
avatarUrl
|
|
900
900
|
webUrl
|
|
901
|
-
`,
|
|
901
|
+
`,ar=`
|
|
902
902
|
color
|
|
903
903
|
description
|
|
904
904
|
id
|
|
905
905
|
title
|
|
906
|
-
`,
|
|
906
|
+
`,Xt=`
|
|
907
907
|
author {
|
|
908
|
-
${
|
|
908
|
+
${Z}
|
|
909
909
|
}
|
|
910
910
|
assignees {
|
|
911
911
|
nodes {
|
|
912
|
-
${
|
|
912
|
+
${Z}
|
|
913
913
|
}
|
|
914
914
|
}
|
|
915
915
|
closedAt
|
|
@@ -920,7 +920,7 @@ id
|
|
|
920
920
|
iid
|
|
921
921
|
labels {
|
|
922
922
|
nodes {
|
|
923
|
-
${
|
|
923
|
+
${ar}
|
|
924
924
|
}
|
|
925
925
|
}
|
|
926
926
|
state
|
|
@@ -931,9 +931,9 @@ upvotes
|
|
|
931
931
|
userNotesCount
|
|
932
932
|
webUrl
|
|
933
933
|
milestone {
|
|
934
|
-
${
|
|
934
|
+
${ir}
|
|
935
935
|
}
|
|
936
|
-
`,
|
|
936
|
+
`,zn=`
|
|
937
937
|
stages {
|
|
938
938
|
nodes {
|
|
939
939
|
jobs {
|
|
@@ -949,11 +949,11 @@ stages {
|
|
|
949
949
|
name
|
|
950
950
|
}
|
|
951
951
|
}
|
|
952
|
-
`,
|
|
952
|
+
`,Yt=(s,r,e)=>`
|
|
953
953
|
id
|
|
954
954
|
state
|
|
955
955
|
author {
|
|
956
|
-
${
|
|
956
|
+
${Z}
|
|
957
957
|
}
|
|
958
958
|
diffRefs {
|
|
959
959
|
baseSha
|
|
@@ -979,12 +979,12 @@ targetBranch
|
|
|
979
979
|
sourceBranch
|
|
980
980
|
assignees {
|
|
981
981
|
nodes {
|
|
982
|
-
${
|
|
982
|
+
${Z}
|
|
983
983
|
}
|
|
984
984
|
}
|
|
985
985
|
reviewers {
|
|
986
986
|
nodes {
|
|
987
|
-
${
|
|
987
|
+
${Z}
|
|
988
988
|
mergeRequestInteraction {
|
|
989
989
|
approved
|
|
990
990
|
reviewState
|
|
@@ -994,25 +994,25 @@ reviewers {
|
|
|
994
994
|
mergeStatusEnum
|
|
995
995
|
labels {
|
|
996
996
|
nodes {
|
|
997
|
-
${
|
|
997
|
+
${ar}
|
|
998
998
|
}
|
|
999
999
|
}
|
|
1000
1000
|
${s?"project { id httpUrlToRepo fullPath sshUrlToRepo webUrl archived } sourceProject { id httpUrlToRepo fullPath sshUrlToRepo webUrl }":""}
|
|
1001
|
-
${r?`milestone { ${
|
|
1002
|
-
${e?`headPipeline { ${
|
|
1003
|
-
`,
|
|
1001
|
+
${r?`milestone { ${ir} }`:""}
|
|
1002
|
+
${e?`headPipeline { ${zn} }`:""}
|
|
1003
|
+
`,O=s=>`${s.namespace}/${s.name}`,Wn=s=>`${s.namespace}/${s.name}`,Hn=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),Jn=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),Zt=s=>({id:s.id.replace(Re,""),graphQLId:s.id,namespace:nr(s.fullPath),name:or(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:Jn(s.userPermissions)}),Vn=s=>({path:s.path,isDirectory:s.type==="tree"}),Kn={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Je=(s,r,e)=>!r&&s?.startsWith("/")?`https://gitlab.com${s}`:r&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,ee=(s,r,e)=>{let t=Je(s.avatarUrl,r,e);return{id:s.id.replace(is,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:t,url:s.webUrl}},ur=s=>({color:s.color,description:s.description,id:s.id.replace(Qn,""),graphQLId:s.id,name:s.title}),Xn=(s,r)=>s?s==="FAILED"&&r?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[s]:null,Yn=(s,r,e)=>{let t={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:ee(s,r,e),state:s.mergeRequestInteraction?.reviewState?t[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},er=(s,r,e,t,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>Yn(i,t,n)):null;return{id:s.id.replace(jn,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:Kn[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?ee(s.author,t,n):null,createdDate:new Date(s.createdAt),isDraft:s.draft,repository:{id:r.id,graphQLId:r.graphQLId,name:r.name,owner:{login:r.namespace},remoteInfo:r.httpsUrl&&r.sshUrl?{cloneUrlHTTPS:r.httpsUrl,cloneUrlSSH:r.sshUrl}:null},headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:s.headPipeline?.stages?.nodes?.flatMap(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:Xn(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${r.webUrl}/-/jobs/${a.id.replace(Mn,"")}`}))??[])??[]},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=>ee(i,t,n)):null,reviews:o,reviewDecision:H(o),additions:s.diffStatsSummary?.additions||0,deletions:s.diffStatsSummary?.deletions||0,fileCount:s.diffStatsSummary?.fileCount||0,commitCount:s.commitCount||0,mergeableState:Nn[s.mergeStatusEnum],milestone:s.milestone?lr(s.milestone,r.webUrl):null,labels:s.labels?.nodes?.map(ur)??[],permissions:null}},tr=(s,r,e,t)=>({author:ee(s.author,e,t),assignees:s.assignees.nodes.map(n=>ee(n,e,t)),commentCount:s.userNotesCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:s.description,graphQLId:s.id,id:s.id.replace(Bn,""),labels:s.labels?.nodes?.map(ur)??[],number:s.iid,repository:{id:r.id.replace(Re,""),graphQLId:r.id,name:r.name,owner:{login:r.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?lr(s.milestone,r.webUrl):null}),lr=(s,r)=>({id:s.id.replace(Fn,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${r}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),Zn=s=>Buffer.from(JSON.stringify(s),"utf8").toString("base64"),eo=(s,r)=>{if(!s)return{page:1,perPage:r};try{let e=JSON.parse(Buffer.from(s,"base64").toString("utf8")),t=typeof e.page=="number"&&e.page>0?e.page:1,n=typeof e.perPage=="number"&&e.perPage>0?e.perPage:r;return{page:t,perPage:n}}catch{return{page:1,perPage:r}}},to=(s,r,e)=>({id:s.id.toString(),graphQLId:`${is}${s.id}`,name:s.name,username:s.username,email:s.email??null,avatarUrl:Je(s.avatar_url,r,e),url:s.web_url}),os=(s,r,e)=>({avatarUrl:Je(s.avatar_url,r,e)??"",email:null,name:s.name}),ro=s=>s?.new_line!=null?"RIGHT":s?.old_line!=null?"LEFT":null,so=s=>{let r=s.old_path||s.new_path,e=s.new_path||s.old_path,t=[`diff --git a/${r} b/${e}`];return s.new_file&&s.b_mode?t.push(`new file mode ${s.b_mode}`):s.deleted_file&&s.a_mode?t.push(`deleted file mode ${s.a_mode}`):s.a_mode&&s.b_mode&&s.a_mode!==s.b_mode&&(t.push(`old mode ${s.a_mode}`),t.push(`new mode ${s.b_mode}`)),s.renamed_file&&(t.push(`rename from ${s.old_path}`),t.push(`rename to ${s.new_path}`)),s.diff&&s.diff.length>0?(t.push(`--- ${s.new_file?"/dev/null":`a/${r}`}`),t.push(`+++ ${s.deleted_file?"/dev/null":`b/${e}`}`),`${t.join(`
|
|
1004
1004
|
`)}
|
|
1005
1005
|
${s.diff.endsWith(`
|
|
1006
1006
|
`)?s.diff:`${s.diff}
|
|
1007
1007
|
`}`):`${t.join(`
|
|
1008
1008
|
`)}
|
|
1009
|
-
`},as="|",
|
|
1009
|
+
`},as="|",sr=(s,r,e,t)=>[s,r,e.toString(),t.toString()].join(as),no=s=>{let r=s.split(as);if(r.length!==4)throw new Error("Invalid GitLab comment ID format \u2014 expected a composite ID produced by getCommentsForPullRequest or addInlineCommentToPullRequest.");return{namespace:r[0],name:r[1],mergeRequestIid:r[2],noteId:r[3]}},rr=(s,r,e,t)=>({author:s.author?to(s.author,r,e):null,body:s.body,createdAt:s.created_at?new Date(s.created_at):null,id:sr(t.namespace,t.name,t.mergeRequestIid,s.id),url:""}),Ie=class extends j{getIsSelfHosted(r){return!!r.baseUrl||!!this.config.baseUrl}async getCurrentUser(r={},e={}){let n=(await v(this.config,{query:`
|
|
1010
1010
|
query getCurrentUser {
|
|
1011
1011
|
currentUser {
|
|
1012
|
-
${
|
|
1012
|
+
${Z}
|
|
1013
1013
|
}
|
|
1014
1014
|
}
|
|
1015
|
-
`},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:
|
|
1015
|
+
`},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:ee(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(r,e={}){let t=O(r.repo),o=(await v(this.config,{query:`
|
|
1016
1016
|
query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
1017
1017
|
project(fullPath: $fullPath) {
|
|
1018
1018
|
repository {
|
|
@@ -1028,21 +1028,21 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
|
1028
1028
|
}
|
|
1029
1029
|
}
|
|
1030
1030
|
}
|
|
1031
|
-
`,variables:{fullPath:t,oid:r.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Je(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(r,e={}){let n=(await
|
|
1031
|
+
`,variables:{fullPath:t,oid:r.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=Je(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(r,e={}){let n=(await v(this.config,{query:`
|
|
1032
1032
|
query getAccountForEmail($email: String!) {
|
|
1033
1033
|
users(search: $email) {
|
|
1034
1034
|
nodes {
|
|
1035
|
-
${
|
|
1035
|
+
${Z}
|
|
1036
1036
|
}
|
|
1037
1037
|
}
|
|
1038
1038
|
}
|
|
1039
|
-
`,variables:{email:r.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:
|
|
1039
|
+
`,variables:{email:r.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:ee(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(r,e={}){let n=(await v(this.config,{query:`
|
|
1040
1040
|
query getAccountForUsername($username: String!) {
|
|
1041
1041
|
user(username: $username) {
|
|
1042
|
-
${
|
|
1042
|
+
${Z}
|
|
1043
1043
|
}
|
|
1044
1044
|
}
|
|
1045
|
-
`,variables:{username:r.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:
|
|
1045
|
+
`,variables:{username:r.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:ee(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(r,e={}){let{repo:{namespace:t,name:n},cursor:o}=r,i=await v(this.config,{query:`
|
|
1046
1046
|
query getAccountsForRepo(
|
|
1047
1047
|
$fullPath: ID!
|
|
1048
1048
|
$after: String
|
|
@@ -1053,7 +1053,7 @@ query getAccountsForRepo(
|
|
|
1053
1053
|
projectMembers(after: $after) {
|
|
1054
1054
|
nodes {
|
|
1055
1055
|
user {
|
|
1056
|
-
${
|
|
1056
|
+
${Z}
|
|
1057
1057
|
}
|
|
1058
1058
|
}
|
|
1059
1059
|
pageInfo {
|
|
@@ -1063,22 +1063,22 @@ query getAccountsForRepo(
|
|
|
1063
1063
|
}
|
|
1064
1064
|
}
|
|
1065
1065
|
}
|
|
1066
|
-
`,variables:{fullPath:`${t}/${n}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>
|
|
1066
|
+
`,variables:{fullPath:`${t}/${n}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>ee(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(r,e={}){let t=O(r),n=await v(this.config,{query:`
|
|
1067
1067
|
query getRepo($fullPath: ID!) {
|
|
1068
1068
|
project(fullPath: $fullPath) {
|
|
1069
|
-
${
|
|
1069
|
+
${Kt}
|
|
1070
1070
|
}
|
|
1071
1071
|
}
|
|
1072
|
-
`,variables:{fullPath:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:
|
|
1072
|
+
`,variables:{fullPath:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);return{data:Zt(n.body.data.project)}}async getReposBase(r,e={}){let n=r.map(O).map((u,l)=>`
|
|
1073
1073
|
getRepo_${l}: project(fullPath: "${u}") {
|
|
1074
|
-
${
|
|
1074
|
+
${Kt}
|
|
1075
1075
|
}
|
|
1076
1076
|
`).join(`
|
|
1077
|
-
`),o=await
|
|
1077
|
+
`),o=await v(this.config,{query:`
|
|
1078
1078
|
query batchGetRepos {
|
|
1079
1079
|
${n}
|
|
1080
1080
|
}
|
|
1081
|
-
`},e);if(!o.body.data)throw new Error(
|
|
1081
|
+
`},e);if(!o.body.data)throw new Error($e(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return r.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(Zt(d)):a.push({input:u})}),{data:i,errors:a}}async getRepos(r,e={}){let t=[];for(let i=0;i<r.length;i+=15)t.push(r.slice(i,i+15));return(await Promise.all(t.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(r,e={}){let t=await v(this.config,{query:`
|
|
1082
1082
|
query getReposForCurrentUser($after: String) {
|
|
1083
1083
|
projects(membership: true first: 100 after: $after) {
|
|
1084
1084
|
pageInfo {
|
|
@@ -1086,11 +1086,11 @@ query getReposForCurrentUser($after: String) {
|
|
|
1086
1086
|
hasNextPage
|
|
1087
1087
|
}
|
|
1088
1088
|
nodes {
|
|
1089
|
-
${
|
|
1089
|
+
${Kt}
|
|
1090
1090
|
}
|
|
1091
1091
|
}
|
|
1092
1092
|
}
|
|
1093
|
-
`,variables:{after:r.cursor}},e);if(!t.body.data?.projects)throw new Error(
|
|
1093
|
+
`,variables:{after:r.cursor}},e);if(!t.body.data?.projects)throw new Error($e(t.body.errors)||t.statusText||"Unknown error");let n=t.body.data?.projects?.nodes||[];return{pageInfo:t.body.data?.projects?.pageInfo,data:n.map(Zt)}}async getRefs(r,e,t={}){let n=O(e.repo),o=new URL(`${L(this.config,t)}/projects/${encodeURIComponent(n)}/repository/${r}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",$.toString());let i=await this.config.request({url:o.toString(),headers:f(t.token||this.config.token)}),a=i.headers["x-next-page"];return{pageInfo:{hasNextPage:!!a,nextPage:a?parseInt(a,10):null},data:i.body.map(u=>({name:u.name,commit:{oid:u.commit.id,authoredDate:new Date(u.commit.authored_date),committedDate:new Date(u.commit.committed_date)}}))}}async getBranches(r,e={}){return this.getRefs("branches",r,e)}async getTags(r,e={}){return this.getRefs("tags",r,e)}async getBlame(r,e={}){let t=O(r.repo),n=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(r.path)}/blame`);n.searchParams.set("ref",r.ref);let o=await this.config.request({url:n.toString(),headers:f(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(r,e={}){let t="";r.repo?.id?t=`projectId:"${r.repo.id}"`:r.repo?.namespace&&r.repo?.name&&(t=`projectPath:"${r.repo.namespace}/${r.repo.name}"`);let n=_n[r.association],o=await v(this.config,{query:`
|
|
1094
1094
|
query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
|
|
1095
1095
|
user(username: $username) {
|
|
1096
1096
|
${n}(state:opened first:100 after:$cursor labels: $labelNames${t?` ${t}`:""}) {
|
|
@@ -1099,12 +1099,12 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
|
|
|
1099
1099
|
hasNextPage
|
|
1100
1100
|
}
|
|
1101
1101
|
nodes {
|
|
1102
|
-
${
|
|
1102
|
+
${Yt(!0,!0,!0)}
|
|
1103
1103
|
}
|
|
1104
1104
|
}
|
|
1105
1105
|
}
|
|
1106
1106
|
}
|
|
1107
|
-
`,variables:{username:r.username,cursor:r.cursor,labelNames:r.labelNames}},e);if(!o.body.data)throw new Error(
|
|
1107
|
+
`,variables:{username:r.username,cursor:r.cursor,labelNames:r.labelNames}},e);if(!o.body.data)throw new Error($e(o.body.errors)||o.statusText||"Unknown error");if(!o.body.data.user)throw new Error("User not found");let i=o.body.data.user[n];if(!i)throw new Error("Unexpected response");return{pageInfo:i.pageInfo,data:i.nodes?.filter(a=>r.includeFromArchivedRepos||!a.project.archived).map(a=>er(a,He(a.project),He(a.sourceProject),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[]}}async getPullRequestsAssociatedWithUser(r,e={}){let[t,n,o]=r.cursor?.split(";")||[void 0,void 0,void 0],i=t?.split("-")||[],a=n?.split("-")||[],u=o?.split("-")||[],l=[],d=[],c=[],p=0;do{let S=r.repos&&r.repos[p];i[p]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:r.username,association:"authored",cursor:i[p],includeFromArchivedRepos:r.includeFromArchivedRepos,labelNames:r.labelNames,...S&&{repo:S}},e)),a[p]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:r.username,association:"assigned",cursor:a[p],includeFromArchivedRepos:r.includeFromArchivedRepos,labelNames:r.labelNames,...S&&{repo:S}},e)),u[p]==="null"?c.push(null):c.push(this.getPullRequestsForUser({username:r.username,association:"reviewRequested",cursor:u[p],includeFromArchivedRepos:r.includeFromArchivedRepos,labelNames:r.labelNames,...S&&{repo:S}},e)),p++}while(p<(r.repos?.length||0));let g=[l,d,c].flat(),m=await Promise.all(g),I={},y=[],h=S=>{I[S.id]||(I[S.id]=!0,y.push(S))},q=!1,k=m.map((S,w)=>{let E="";return S&&S.data.forEach(h),S?.pageInfo.hasNextPage?(q=!0,E+=`${S.pageInfo.endCursor||"null"}`):E+="null",r.repos?.length&&(w+1)%r.repos.length!==0?E+="-":w+1<m.length&&(E+=";"),E}).join("");return{pageInfo:{hasNextPage:q,endCursor:k},data:y}}getVariablesForPullRequests(r){let{updatedBefore:e,isDraft:t,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=r||{},u={},l=[],d=[],c=(p,g,m)=>{l.push(`$${p}: ${m}`),d.push(`${p}: $${p}`),u[p]=g};return e&&c("updatedBefore",e,"Time"),n&&c("authorUsername",n,"String"),o&&c("assigneeUsername",o[0],"String"),i&&c("labelName",i,"[String]"),t!=null&&c("draft",t,"Boolean"),a&&c("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:d}}async getPullRequestsForRepoBase(r,e={},t){let{cursor:n,repo:o}=r||{},i=O(o),{variables:a,variableTypes:u,mergeRequestArguments:l}=this.getVariablesForPullRequests(r),d={fullPath:i,...a},c=await v(this.config,{query:`
|
|
1108
1108
|
query getPullRequestsForRepo(
|
|
1109
1109
|
$fullPath: ID!
|
|
1110
1110
|
$after: String
|
|
@@ -1129,19 +1129,19 @@ query getPullRequestsForRepo(
|
|
|
1129
1129
|
hasNextPage
|
|
1130
1130
|
}
|
|
1131
1131
|
nodes {
|
|
1132
|
-
${
|
|
1132
|
+
${Yt(!1,!0,!0)}
|
|
1133
1133
|
}
|
|
1134
1134
|
}
|
|
1135
1135
|
}
|
|
1136
1136
|
}
|
|
1137
|
-
`,variables:{...
|
|
1137
|
+
`,variables:{...d,after:n}},e),p=[],g=c.body.data?.project;if(!t&&g?.archived)return{pageInfo:null,data:[]};let m=We(g||{id:"",fullPath:"",webUrl:""});return(g?.mergeRequests?.nodes||[]).forEach(y=>{p.push(er(y,m,null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.mergeRequests?.pageInfo,data:p}}async getPullRequestsForRepo(r,e={}){return this.getPullRequestsForRepoBase(r,e,!1)}async getPullRequestsForRepos(r,e={}){let{repos:t,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=r;return{data:(await Promise.all(t.map(c=>this.getPullRequestsForRepoBase({repo:c,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l},e,r.includeFromArchivedRepos??!1)))).flatMap(c=>c.data)}}async closePullRequest(r,e={}){let{pullRequest:t}=r,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
|
|
1138
1138
|
mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
|
|
1139
1139
|
errors,
|
|
1140
1140
|
mergeRequest {
|
|
1141
1141
|
id
|
|
1142
1142
|
}
|
|
1143
1143
|
}
|
|
1144
|
-
}`,i=(await
|
|
1144
|
+
}`,i=(await v(this.config,{query:n,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString()}},e)).body.data?.mergeRequestUpdate;if(!i?.mergeRequest?.id||i?.errors?.length!==0)throw new Error("Could not close pull request")}async mergePullRequest(r,e={}){let{pullRequest:t,mergeStrategy:n}=r;if(!t.headRef?.oid)throw new Error('GitLab requires "headRef.oid" for this function.');let o=`mutation MergePullRequest(
|
|
1145
1145
|
$fullPath: ID!,
|
|
1146
1146
|
$pullRequestId: String!,
|
|
1147
1147
|
$expectedSourceSha: String!,
|
|
@@ -1158,59 +1158,59 @@ query getPullRequestsForRepo(
|
|
|
1158
1158
|
id
|
|
1159
1159
|
}
|
|
1160
1160
|
}
|
|
1161
|
-
}`,a=(await
|
|
1161
|
+
}`,a=(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),expectedSourceSha:t.headRef.oid,squash:n==="SQUASH"}},e)).body.data?.mergeRequestAccept;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not merge pull request")}async setPullRequestMilestone(r,e={}){let{pullRequest:t,milestone:n}=r;if(!t.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation SetPullRequestMilestone($fullPath: ID!, $pullRequestId: String!, $milestoneGraphQLId: MilestoneID) {
|
|
1162
1162
|
mergeRequestSetMilestone(input: { projectPath: $fullPath, iid: $pullRequestId, milestoneId: $milestoneGraphQLId }) {
|
|
1163
1163
|
errors,
|
|
1164
1164
|
mergeRequest {
|
|
1165
1165
|
id
|
|
1166
1166
|
}
|
|
1167
1167
|
}
|
|
1168
|
-
}`,i=await
|
|
1168
|
+
}`,i=await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),milestoneGraphQLId:n?.graphQLId}},e),a=i.body.data?.mergeRequestSetMilestone;if(!a?.mergeRequest?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of pull request")}async setPullRequestAsDraft(r,e={}){let{pullRequest:t,isDraft:n}=r,o=`mutation MergeRequestSetDraft($fullPath: ID!, $pullRequestId: String!, $isDraft: Boolean!) {
|
|
1169
1169
|
mergeRequestSetDraft(input: { projectPath: $fullPath, iid: $pullRequestId, draft: $isDraft }) {
|
|
1170
1170
|
errors,
|
|
1171
1171
|
mergeRequest {
|
|
1172
1172
|
id
|
|
1173
1173
|
}
|
|
1174
1174
|
}
|
|
1175
|
-
}`,a=(await
|
|
1175
|
+
}`,a=(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),isDraft:n}},e)).body.data?.mergeRequestSetDraft;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request as draft")}async setPullRequestReviewers(r,e={}){let{pullRequest:t,reviewers:n}=r,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires reviewer "username" for this function.');return l.username}),i=`mutation MergeRequestSetReviewers($fullPath: ID!, $pullRequestId: String!, $reviewerUsernames: [String!]!) {
|
|
1176
1176
|
mergeRequestSetReviewers(input: { projectPath: $fullPath, iid: $pullRequestId, reviewerUsernames: $reviewerUsernames }) {
|
|
1177
1177
|
errors,
|
|
1178
1178
|
mergeRequest {
|
|
1179
1179
|
id
|
|
1180
1180
|
}
|
|
1181
1181
|
}
|
|
1182
|
-
}`,u=(await
|
|
1182
|
+
}`,u=(await v(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUsernames:o}},e)).body.data?.mergeRequestSetReviewers;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReview(r,e={}){let{pullRequest:t,reviewer:n}=r;if(!n.graphQLId)throw new Error('GitLab requires reviwer "graphQLId" for this function.');let o=`mutation MergeRequestReviewerRereview($fullPath: ID!, $pullRequestId: String!, $reviewerUserId: UserID!) {
|
|
1183
1183
|
mergeRequestReviewerRereview(input: { projectPath: $fullPath, iid: $pullRequestId, userId: $reviewerUserId }) {
|
|
1184
1184
|
errors,
|
|
1185
1185
|
mergeRequest {
|
|
1186
1186
|
id
|
|
1187
1187
|
}
|
|
1188
1188
|
}
|
|
1189
|
-
}`,a=(await
|
|
1189
|
+
}`,a=(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),reviewerUserId:n.graphQLId}},e)).body.data?.mergeRequestReviewerRereview;if(!a?.mergeRequest?.id||a?.errors?.length!==0)throw new Error("Could not set pull request reviewers")}async reRequestPullRequestReviews(r,e={}){let{pullRequest:t,reviewers:n}=r,o=t.reviews;if(!o)throw new Error('GitLab requires "reviews" for this function.');let i=n.filter(a=>o.find(u=>u.reviewer.graphQLId===a.graphQLId));await Promise.all(i.map(a=>this.reRequestPullRequestReview({pullRequest:t,reviewer:a},e)))}async setPullRequestAssignees(r,e={}){let{pullRequest:t,assignees:n}=r,o=n.map(l=>{if(!l.username)throw new Error('GitLab requires assignee "username" for this function.');return l.username}),i=`mutation MergeRequestSetAssignees($fullPath: ID!, $pullRequestId: String!, $assigneeUsernames: [String!]!) {
|
|
1190
1190
|
mergeRequestSetAssignees(input: { projectPath: $fullPath, iid: $pullRequestId, assigneeUsernames: $assigneeUsernames }) {
|
|
1191
1191
|
errors,
|
|
1192
1192
|
mergeRequest {
|
|
1193
1193
|
id
|
|
1194
1194
|
}
|
|
1195
1195
|
}
|
|
1196
|
-
}`,u=(await
|
|
1196
|
+
}`,u=(await v(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),assigneeUsernames:o}},e)).body.data?.mergeRequestSetAssignees;if(!u?.mergeRequest?.id||u?.errors?.length!==0)throw new Error("Could not set pull request assignees")}async setPullRequestLabels(r,e={}){let{pullRequest:t,labels:n}=r,o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires "graphQLId" for labels in this function.');return u.graphQLId}),i=`mutation SetPullRequestLabels($fullPath: ID!, $pullRequestId: String!, $labelGraphQLIds: [LabelID!]!) {
|
|
1197
1197
|
mergeRequestSetLabels(input: { projectPath: $fullPath, iid: $pullRequestId, labelIds: $labelGraphQLIds }) {
|
|
1198
1198
|
mergeRequest {
|
|
1199
1199
|
id
|
|
1200
1200
|
}
|
|
1201
1201
|
}
|
|
1202
|
-
}`;if(!(await
|
|
1202
|
+
}`;if(!(await v(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,pullRequestId:t.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(r,e={}){let t=Wn(r),n=await v(this.config,{query:`
|
|
1203
1203
|
query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
1204
1204
|
project(fullPath: $projectId) {
|
|
1205
1205
|
id
|
|
1206
1206
|
fullPath
|
|
1207
1207
|
webUrl
|
|
1208
1208
|
issue(iid: $issueNumber) {
|
|
1209
|
-
${
|
|
1209
|
+
${Xt}
|
|
1210
1210
|
}
|
|
1211
1211
|
}
|
|
1212
1212
|
}
|
|
1213
|
-
`,variables:{issueNumber:r.number,projectId:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${r.number} not found`);return{data:
|
|
1213
|
+
`,variables:{issueNumber:r.number,projectId:t}},e);if(!n.body.data?.project)throw new Error(`Repository ${t} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${r.number} not found`);return{data:tr(n.body.data.project.issue,We(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(r){let{updatedBefore:e,authorLogin:t,assigneeLogins:n,labelNames:o}=r||{},i={},a=[],u=[],l=(d,c,p)=>{a.push(`$${d}: ${p}`),u.push(`${d}: $${d}`),i[d]=c};return e&&l("updatedBefore",e,"Time"),t&&l("authorUsername",t,"String"),n&&l("assigneeUsername",n[0],"String"),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(r,e={}){let{cursor:t,repo:n}=r||{},o=O(n),{variables:i,variableTypes:a,issueArguments:u}=this.getVariablesForIssues(r),l={fullPath:o,...i},d=`
|
|
1214
1214
|
query GetIssuesFromProject(
|
|
1215
1215
|
$fullPath: ID!
|
|
1216
1216
|
$after: String
|
|
@@ -1230,7 +1230,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1230
1230
|
${u.length?u.join(" "):""}
|
|
1231
1231
|
) {
|
|
1232
1232
|
nodes {
|
|
1233
|
-
${
|
|
1233
|
+
${Xt}
|
|
1234
1234
|
}
|
|
1235
1235
|
pageInfo {
|
|
1236
1236
|
endCursor
|
|
@@ -1238,7 +1238,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1238
1238
|
}
|
|
1239
1239
|
}
|
|
1240
1240
|
}
|
|
1241
|
-
}`,c=await
|
|
1241
|
+
}`,c=await v(this.config,{query:d,variables:{...l,after:t}},e),p=[],g=c.body.data?.project,m=We(g||{id:"",fullPath:"",webUrl:""});return(g?.issues?.nodes||[]).forEach(y=>{p.push(tr(y,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:g?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:p.sort((y,h)=>(y.updatedDate||y.createdDate).getTime()-(h.updatedDate||h.createdDate).getTime())}}async getIssuesForRepos(r,e={}){let{cursor:t}=r||{},n=r.repoIds.map(g=>g.toString().startsWith(Re)?g:`${Re}${g}`),{variables:o,variableTypes:i,mergeRequestArguments:a}=this.getVariablesForPullRequests(r),u={projectIds:n,...o},l=`
|
|
1242
1242
|
query GetIssuesFromProject(
|
|
1243
1243
|
$projectIds: [ID!]
|
|
1244
1244
|
$after: String
|
|
@@ -1264,24 +1264,24 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1264
1264
|
${a.length?a.join(" "):""}
|
|
1265
1265
|
) {
|
|
1266
1266
|
nodes {
|
|
1267
|
-
${
|
|
1267
|
+
${Xt}
|
|
1268
1268
|
}
|
|
1269
1269
|
}
|
|
1270
1270
|
}
|
|
1271
1271
|
}
|
|
1272
|
-
}`,
|
|
1272
|
+
}`,d=await v(this.config,{query:l,variables:{...u,after:t}},e),c=[];return(d.body.data?.projects?.nodes||[]).forEach(g=>{if(!r.includeFromArchivedRepos&&g.archived)return;let m=We(g);(g.issues?.nodes||[]).forEach(y=>c.push(tr(y,m,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:d.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:c.sort((g,m)=>(g.updatedDate||g.createdDate).getTime()-(m.updatedDate||m.createdDate).getTime())}}async setIssueState(r,e={}){let{issue:t,state:n}=r;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
|
|
1273
1273
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
|
|
1274
1274
|
issue {
|
|
1275
1275
|
id
|
|
1276
1276
|
}
|
|
1277
1277
|
}
|
|
1278
|
-
}`;if(!(await
|
|
1278
|
+
}`;if(!(await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,status:n==="OPEN"?"REOPEN":"CLOSE"}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue status")}async closeIssue(r,e={}){await this.setIssueState({...r,state:"CLOSED"},e)}async reOpenIssue(r,e={}){await this.setIssueState({...r,state:"OPEN"},e)}async setIssueLabels(r,e={}){let{issue:t,labels:n}=r;if(!t.repository)throw new Error('GitLab requires a "repository" for this function.');let o=n.map(u=>{if(!u.graphQLId)throw new Error('GitLab requires label "graphQLId" for this function.');return u.graphQLId}),i=`mutation SetIssueLabels($fullPath: ID!, $issueId: String!, $labelGraphQLIds: [ID!]) {
|
|
1279
1279
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, labelIds: $labelGraphQLIds }) {
|
|
1280
1280
|
issue {
|
|
1281
1281
|
id
|
|
1282
1282
|
}
|
|
1283
1283
|
}
|
|
1284
|
-
}`;if(!(await
|
|
1284
|
+
}`;if(!(await v(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,labelGraphQLIds:o}},e)).body.data?.updateIssue?.issue?.id)throw new Error("Could not set issue labels")}async setIssueMilestone(r,e={}){let{issue:t,milestone:n}=r;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueMilestone($fullPath: ID!, $issueId: String!, $milestoneId: ID) {
|
|
1285
1285
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, milestoneId: $milestoneId }) {
|
|
1286
1286
|
errors
|
|
1287
1287
|
issue {
|
|
@@ -1291,14 +1291,14 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1291
1291
|
}
|
|
1292
1292
|
}
|
|
1293
1293
|
}
|
|
1294
|
-
}`,i=await
|
|
1294
|
+
}`,i=await v(this.config,{query:o,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,milestoneId:n?.id??null}},e),a=i.body.data?.updateIssue;if(!a?.issue?.id||i.body.errors||a?.errors?.length!==0)throw new Error("Could not set milestone of issue")}async setIssueAssignees(r,e={}){let{issue:t,assignees:n}=r;if(!t.repository)throw new Error('GitLab requires "repository" for this function.');let o=n.map(l=>l.username),i=`mutation SetIssueAssignees($fullPath: ID!, $issueId: String!, $assigneeUsernames: [String!]!) {
|
|
1295
1295
|
issueSetAssignees(input: { projectPath: $fullPath, iid: $issueId, assigneeUsernames: $assigneeUsernames }) {
|
|
1296
1296
|
errors,
|
|
1297
1297
|
issue {
|
|
1298
1298
|
id
|
|
1299
1299
|
}
|
|
1300
1300
|
}
|
|
1301
|
-
}`,u=(await
|
|
1301
|
+
}`,u=(await v(this.config,{query:i,variables:{fullPath:`${t.repository.owner.login}/${t.repository.name}`,issueId:t.number,assigneeUsernames:o}},e)).body.data?.issueSetAssignees;if(!u?.issue?.id||u?.errors?.length!==0)throw new Error("Could not set issue assignees")}async getMilestonesForRepo(r,e={}){let{repo:{namespace:t,name:n},cursor:o}=r,i=await v(this.config,{query:`
|
|
1302
1302
|
query getLabelsForRepo(
|
|
1303
1303
|
$fullPath: ID!
|
|
1304
1304
|
$after: String
|
|
@@ -1309,7 +1309,7 @@ query getLabelsForRepo(
|
|
|
1309
1309
|
webUrl
|
|
1310
1310
|
milestones(after: $after) {
|
|
1311
1311
|
nodes {
|
|
1312
|
-
${
|
|
1312
|
+
${ir}
|
|
1313
1313
|
}
|
|
1314
1314
|
pageInfo {
|
|
1315
1315
|
endCursor
|
|
@@ -1318,7 +1318,7 @@ query getLabelsForRepo(
|
|
|
1318
1318
|
}
|
|
1319
1319
|
}
|
|
1320
1320
|
}
|
|
1321
|
-
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>
|
|
1321
|
+
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>lr(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(r,e={}){let{repo:{namespace:t,name:n},cursor:o}=r,i=await v(this.config,{query:`
|
|
1322
1322
|
query getLabelsForRepo(
|
|
1323
1323
|
$fullPath: ID!
|
|
1324
1324
|
$after: String
|
|
@@ -1328,7 +1328,7 @@ query getLabelsForRepo(
|
|
|
1328
1328
|
) {
|
|
1329
1329
|
labels(after: $after) {
|
|
1330
1330
|
nodes {
|
|
1331
|
-
${
|
|
1331
|
+
${ar}
|
|
1332
1332
|
}
|
|
1333
1333
|
pageInfo {
|
|
1334
1334
|
endCursor
|
|
@@ -1337,7 +1337,7 @@ query getLabelsForRepo(
|
|
|
1337
1337
|
}
|
|
1338
1338
|
}
|
|
1339
1339
|
}
|
|
1340
|
-
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(
|
|
1340
|
+
`,variables:{fullPath:`${t}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(ur)??[]}}async getTreeForRepo(r,e={}){let t=O(r.repo),n=new URL(r.cursor??`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",r.branch);let o=await this.config.request({url:n.toString(),headers:f(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(Vn),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(r,e={}){let t=O(r.repo),o=(await v(this.config,{query:`
|
|
1341
1341
|
query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
|
|
1342
1342
|
project(fullPath: $fullPath) {
|
|
1343
1343
|
id
|
|
@@ -1347,7 +1347,7 @@ query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
|
|
|
1347
1347
|
webUrl
|
|
1348
1348
|
archived
|
|
1349
1349
|
mergeRequest(iid: $iid) {
|
|
1350
|
-
${
|
|
1350
|
+
${Yt(!1,!0,!0)}
|
|
1351
1351
|
sourceProject {
|
|
1352
1352
|
id
|
|
1353
1353
|
httpUrlToRepo
|
|
@@ -1358,15 +1358,15 @@ query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
|
|
|
1358
1358
|
}
|
|
1359
1359
|
}
|
|
1360
1360
|
}
|
|
1361
|
-
`,variables:{fullPath:t,iid:r.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=He(o),u=i.sourceProject?He(i.sourceProject):null;return{data:
|
|
1361
|
+
`,variables:{fullPath:t,iid:r.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=He(o),u=i.sourceProject?He(i.sourceProject):null;return{data:er(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getFileContents(r,e={}){let t=O(r.repo),n=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/files/${encodeURIComponent(r.path)}/raw`);n.searchParams.set("ref",r.ref);let o=await this.config.request({url:n.toString(),headers:f(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(r,e={}){let t=O(r.repo),{page:n,perPage:o}=eo(r.cursor,$),i=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/merge_requests/${r.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:f(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,d={namespace:r.repo.namespace,name:r.repo.name,mergeRequestIid:r.pullRequestNumber},c=a.body.filter(m=>!m.system&&!m.position).map(m=>rr(m,u,l,d)),p=!!a.headers["x-next-page"],g=p?Zn({page:n+1,perPage:o}):null;return{data:c,pageInfo:{endCursor:g,hasNextPage:p}}}async getReviewsForPullRequest(r,e={}){let t=O(r.repo),n=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=f(e.token||this.config.token),a=L(this.config,e),u=encodeURIComponent(t),[l,d]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${r.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(t,r.pullRequestId,e)]),c=(l.body.approved_by??[]).map(m=>m?.user).filter(m=>!!m).map(m=>{let I=os(m,n,o),y=`approval-${m.id}`;return{author:I,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),p={namespace:r.repo.namespace,name:r.repo.name,mergeRequestIid:r.pullRequestId},g=d.filter(m=>m.notes.some(I=>!I.system&&!!I.position)).map(m=>{let I=m.notes.filter(w=>!w.system),h=I.filter(w=>!!w.position)[0];if(!h)return null;let q=I.filter(w=>w.id!==h.id).map(w=>rr(w,n,o,p)),k={...rr(h,n,o,p),diffLines:[],filename:h.position?.new_path??h.position?.old_path??"",line:h.position?.new_line??h.position?.old_line??null,startLine:h.position?.line_range?.start?.new_line??null,side:ro(h.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:q};return{author:h.author?os(h.author,n,o):null,body:h.body??"",createdAt:h.created_at?new Date(h.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[k],url:""}}).filter(m=>m!==null);return{data:[...c,...g]}}async getPullRequestDiff(r,e={}){let t=O(r.repo),n=encodeURIComponent(t),o=L(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${n}/merge_requests/${r.pullRequestId}/diffs`,e)).map(so).join("")}async getMergeBase(r,e={}){let t=O(r.repo),n=new URL(`${L(this.config,e)}/projects/${encodeURIComponent(t)}/repository/merge_base`);n.searchParams.append("refs[]",r.base),n.searchParams.append("refs[]",r.head);let i=(await this.config.request({url:n.toString(),headers:f(e.token||this.config.token)})).body?.id;if(!i)throw new Error("No merge base found between the specified commits.");return{data:i}}async fetchAllMergeRequestDiscussions(r,e,t){let n=L(this.config,t),o=encodeURIComponent(r);return this.fetchAllPagedGitLabREST(`${n}/projects/${o}/merge_requests/${e}/discussions`,t)}async fetchAllPagedGitLabREST(r,e){let t=f(e.token||this.config.token),n=[],o=1,i=50;for(;o<=i;){let a=new URL(r);a.searchParams.set("page",o.toString()),a.searchParams.set("per_page",$.toString());let u=await this.config.request({url:a.toString(),headers:t});n.push(...u.body);let l=u.headers["x-next-page"];if(!l)break;let d=parseInt(`${l}`,10);if(Number.isNaN(d))break;o=d}return n}async addCommentToPullRequest(r,e={}){let{pullRequest:t,comment:n}=r;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`,i=`${L(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...f(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:n})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(r,e={}){let{pullRequest:t,comment:n,path:o,line:i,side:a="RIGHT",threadId:u}=r;if(!n?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${t.repository.owner.login}/${t.repository.name}`,d=encodeURIComponent(l),c=L(this.config,e),p={...f(e.token||this.config.token),"Content-Type":"application/json"};if(u){let q=await this.config.request({method:"POST",url:`${c}/projects/${d}/merge_requests/${t.number}/discussions/${encodeURIComponent(u)}/notes`,headers:p,body:JSON.stringify({body:n})});return q.body?.id!=null?sr(t.repository.owner.login,t.repository.name,t.number,q.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let m=(await this.config.request({url:`${c}/projects/${d}/merge_requests/${t.number}`,headers:f(e.token||this.config.token)})).body?.diff_refs;if(!m?.base_sha||!m?.start_sha||!m?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let I={position_type:"text",base_sha:m.base_sha,start_sha:m.start_sha,head_sha:m.head_sha,new_path:o,old_path:o};a==="RIGHT"?I.new_line=i:I.old_line=i;let h=(await this.config.request({method:"POST",url:`${c}/projects/${d}/merge_requests/${t.number}/discussions`,headers:p,body:JSON.stringify({body:n,position:I})})).body?.notes?.[0]?.id;return h!=null?sr(t.repository.owner.login,t.repository.name,t.number,h):void 0}getNoteUrl(r,e){if(!r)throw new Error('GitLab requires "commentId" for this function.');let{namespace:t,name:n,mergeRequestIid:o,noteId:i}=no(r);return`${L(this.config,e)}/projects/${encodeURIComponent(`${t}/${n}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(r,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(r,e),headers:f(e.token||this.config.token)})}async deleteComment(r,e={}){await this.deleteNote(r.commentId,e)}async deleteInlineComment(r,e={}){await this.deleteNote(r.commentId,e)}async editNote(r,e,t){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(r,t),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(r,e={}){await this.editNote(r.commentId,r.body,e)}async editInlineComment(r,e={}){await this.editNote(r.commentId,r.body,e)}async resolveReviewThread(r,e={}){await this.setReviewThreadResolved(r,!0,e)}async unresolveReviewThread(r,e={}){await this.setReviewThreadResolved(r,!1,e)}async setReviewThreadResolved(r,e,t){if(!r.repo||r.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!r.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let n=O(r.repo),o=new URL(`${L(this.config,t)}/projects/${encodeURIComponent(n)}/merge_requests/${r.pullRequestNumber}/discussions/${encodeURIComponent(r.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:f(t.token||this.config.token)})}async approvePullRequest(r,e={}){let{pullRequest:t,comment:n}=r,o=`${t.repository.owner.login}/${t.repository.name}`,i=L(this.config,e),a=encodeURIComponent(o),u=f(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${t.number}/approve`,method:"POST",headers:u}),n&&n.trim()!==""&&await this.postMergeRequestNote(o,t.number,n,e)}async commentOnPullRequest(r,e={}){let{pullRequest:t,comment:n}=r;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;await this.postMergeRequestNote(o,t.number,n,e)}async requestPullRequestChanges(r,e={}){let{pullRequest:t,comment:n}=r;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${t.repository.owner.login}/${t.repository.name}`;if(!await this.tryRequestChangesMutation(o,t.number,e)){let u=`${L(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${t.number}`,l=f(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:l})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:l})}await this.postMergeRequestNote(o,t.number,n,e)}async tryRequestChangesMutation(r,e,t){let n=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
|
|
1362
1362
|
mergeRequestRequestChanges(input: { projectPath: $fullPath, iid: $pullRequestId }) {
|
|
1363
1363
|
errors
|
|
1364
1364
|
mergeRequest {
|
|
1365
1365
|
id
|
|
1366
1366
|
}
|
|
1367
1367
|
}
|
|
1368
|
-
}`,o=await
|
|
1369
|
-
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(h=>u.push(`labels = "${h}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,p=!o,c=p?ls:us,d=new URL(`${ne(s,t,o)}${c}`);d.searchParams.set("jql",l),d.searchParams.set("maxResults",Ve.toString()),d.searchParams.set("fields",lr.join(",")),d.searchParams.set("expand","transitions"),n&&(p?d.searchParams.set("startAt",n):d.searchParams.set("nextPageToken",n));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>pr(h,a,e,o)),I=!1,y="";return p?(I=m.length==Ve,y=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},ps=async(s,r,e,t={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=r||{},u=[...lr],l=a?.Sprint;l&&u.push(l);let p=!o,c=p?ls:us,d=new URL(`${ne(s,t,o)}${c}`);d.searchParams.set("jql",i.join(" AND ")),d.searchParams.set("maxResults",Ve.toString()),d.searchParams.set("fields",u.join(",")),d.searchParams.set("expand","transitions"),n&&(p?d.searchParams.set("startAt",n):d.searchParams.set("nextPageToken",n));let g=await s.request({url:d.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>pr(h,a,e,o)),I=!1,y="";return p?(I=m.length==Ve,y=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},et=async(s,r,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:p,fields:c}=r||{},d=[`project = "${l}"`,"statusCategory != Done"];return o&&d.push(`creator in ("${o}")`),n&&n.length!==0&&d.push(`assignee in ("${n.join('", "')}")`),i&&d.push(`comment ~ "${i}"`),a&&a.forEach(g=>d.push(`labels = "${g}"`)),ps(s,{resourceId:p,jql:d,cursor:u,fields:c},e,t)},tt=async(s,r,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:p,fields:c}=r||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),ps(s,{resourceId:p,jql:g,fields:c,cursor:u},e,t)},rt=async(s,r,e={})=>{let{issue:t,labels:n}=r;if(!t.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:`${ne(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},st=async(s,r,e={})=>{let{issue:t,components:n}=r;if(!t.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:`${ne(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},nt=async(s,r,e={})=>{let{issue:t,status:n}=r;if(!t.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:`${ne(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},ot=async(s,r,e={})=>{let{resourceId:t,projectIdOrKey:n}=r,o=new URL(`${ne(s,e,t)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:f(e.token||s.token)})).body}};var De="https://api.atlassian.com/ex/jira",dr=100,fe=class extends F{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Xe(this.config,e,t);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let n=t.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let n=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||De}/${e.resourceId}/rest/api/2/myself`,headers:f(t.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let t=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:f(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let n=new URL(`${t.baseUrl||De}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",dr.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Or(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,t={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},t),u=new URL(`${t.baseUrl||De}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",dr.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(p=>p.accountType!=="app"&&p.active).map(p=>Ke(p,a,!1))}}async getComponentsForJiraProject(e,t={}){return await ot(this.config,e,t)}async getIssue(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ye(this.config,{...e,fields:n},o,t)}async getIssuesForProject(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await et(this.config,{...e,fields:n},o,t)}async getIssuesForProjects(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await tt(this.config,{...e,fields:n},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ze(this.config,{...e,fields:n},o,t)}async setIssueStatus(e,t={}){await nt(this.config,e,t)}async setIssueAssignee(e,t={}){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:`${t.baseUrl||De}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await st(this.config,e,t)}async setIssueLabels(e,t={}){await rt(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:n,cursor:o}=e,i=new URL(`${t.baseUrl||De}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",dr.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var Re=class extends j{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let n=await Xe(this.config,{},e);this._issueFieldsCache[t]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:f(e?.token||this.config.token)});return{data:{name:t.body.displayName,email:t.body.emailAddress,avatarUrl:t.body.avatarUrls["48x48"],id:t.body.key,username:t.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:f(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ye(this.config,{...e,fields:o},n,t)}async getIssuesForProject(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await et(this.config,{...e,fields:o},n,t)}async getIssuesForProjects(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await tt(this.config,{...e,fields:o},n,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ze(this.config,{...e,fields:o},n,t)}async setIssueStatus(e,t={}){await nt(this.config,e,t)}async setIssueLabels(e,t={}){await rt(this.config,e,t)}async setIssueComponents(e,t={}){await st(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:f(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,t={}){return await ot(this.config,e,t)}};var mr=100,it=class{constructor(){this.set=new Set;this.arr=[]}push(...r){let e=r.filter(t=>!this.set.has(t.id));this.arr.push(...e),e.forEach(t=>this.set.add(t.id))}get length(){return this.arr.length}get items(){return this.arr}},re=async(s,r,e,t)=>{let n=r.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:t})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},cr=s=>s?s instanceof Date?s:new Date(s):null,po=`
|
|
1368
|
+
}`,o=await v(this.config,{query:n,variables:{fullPath:r,pullRequestId:e.toString()}},t),i=o.body.errors;if(i?.length){if(i.some(Hn))return!1;throw new Error(`Could not request pull request changes: ${$e(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(r,e,t,n){let o=L(this.config,n),i=encodeURIComponent(r),a=f(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:t})})}};var oo="https://api.atlassian.com/ex/jira",Ve=100,dr=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],us="/rest/api/2/search/jql",ls="/rest/api/2/search",pr=(s,r,e,t)=>{let n=s.fields.assignee,o=!t,i=(s.fields[r?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:s.id,commentCount:s.fields.comment.comments.length,number:s.key,title:s.fields.summary,url:e?`${e}/browse/${s.key}`:null,closedDate:null,createdDate:new Date(s.fields.created),author:Ke(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[Ke(n,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:t??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:lo(s.fields.status),statusTransitions:s.transitions?.map(io)??[],components:s.fields.components?.map(ao)??[],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(po),fixVersions:s.fields.fixVersions.map(co)}},io=s=>{let r;switch(s.to.statusCategory.name){case"To Do":r="TO_DO";break;case"In Progress":r="IN_PROGRESS";break;default:r="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:r}}},ao=s=>({description:s.description??null,id:s.id,name:s.name}),uo=(s,r,e)=>e&&s.name?`${r}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${r}/jira/people/${s.accountId}`,Ke=(s,r,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:uo(s,r,e)}),lo=s=>{let r;switch(s.statusCategory.name){case"To Do":r="TO_DO";break;case"In Progress":r="IN_PROGRESS";break;default:r="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:r}},po=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}),co=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),se=(s,r,e)=>e?`${r.baseUrl||oo}/${e}`:`${r?.baseUrl||s.baseUrl}`,Xe=async(s,r,e={})=>{let{resourceId:t}=r;return(await s.request({url:`${se(s,e,t)}/rest/api/2/field`,headers:f(e.token||s.token)})).body},Ye=async(s,r,e,t={})=>{let{number:n,resourceId:o,fields:i}=r||{},a=await s.request({url:`${se(s,t,o)}/rest/api/2/issue/${n}?fields=${dr.join(",")}&expand=transitions`,headers:f(t.token||s.token)});return{data:pr(a.body,i,e,o)}},Ze=async(s,r,e,t={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=r||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
|
|
1369
|
+
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(h=>u.push(`labels = "${h}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,d=!o,c=d?ls:us,p=new URL(`${se(s,t,o)}${c}`);p.searchParams.set("jql",l),p.searchParams.set("maxResults",Ve.toString()),p.searchParams.set("fields",dr.join(",")),p.searchParams.set("expand","transitions"),n&&(d?p.searchParams.set("startAt",n):p.searchParams.set("nextPageToken",n));let g=await s.request({url:p.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>pr(h,a,e,o)),I=!1,y="";return d?(I=m.length==Ve,y=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},ds=async(s,r,e,t={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=r||{},u=[...dr],l=a?.Sprint;l&&u.push(l);let d=!o,c=d?ls:us,p=new URL(`${se(s,t,o)}${c}`);p.searchParams.set("jql",i.join(" AND ")),p.searchParams.set("maxResults",Ve.toString()),p.searchParams.set("fields",u.join(",")),p.searchParams.set("expand","transitions"),n&&(d?p.searchParams.set("startAt",n):p.searchParams.set("nextPageToken",n));let g=await s.request({url:p.toString(),headers:f(t.token||s.token)}),m=g.body.issues.map(h=>pr(h,a,e,o)),I=!1,y="";return d?(I=m.length==Ve,y=(parseInt(n??"0",10)+m.length).toString()):(I=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:I,endCursor:y}}},et=async(s,r,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:d,fields:c}=r||{},p=[`project = "${l}"`,"statusCategory != Done"];return o&&p.push(`creator in ("${o}")`),n&&n.length!==0&&p.push(`assignee in ("${n.join('", "')}")`),i&&p.push(`comment ~ "${i}"`),a&&a.forEach(g=>p.push(`labels = "${g}"`)),ds(s,{resourceId:d,jql:p,cursor:u,fields:c},e,t)},tt=async(s,r,e,t={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:d,fields:c}=r||{},g=["("+l.map(m=>`project = "${m}"`).join(" OR ")+")","statusCategory != Done"];return o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(m=>g.push(`labels = "${m}"`)),ds(s,{resourceId:d,jql:g,fields:c,cursor:u},e,t)},rt=async(s,r,e={})=>{let{issue:t,labels:n}=r;if(!t.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:`${se(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},st=async(s,r,e={})=>{let{issue:t,components:n}=r;if(!t.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:`${se(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},nt=async(s,r,e={})=>{let{issue:t,status:n}=r;if(!t.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:`${se(s,e,t.project.resourceId??void 0)}/rest/api/2/issue/${t.id}/transitions`,body:JSON.stringify(o),headers:{...f(e.token||s.token),"Content-Type":"application/json"}})},ot=async(s,r,e={})=>{let{resourceId:t,projectIdOrKey:n}=r,o=new URL(`${se(s,e,t)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:f(e.token||s.token)})).body}};var Ae="https://api.atlassian.com/ex/jira",cr=100,be=class extends F{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,t={}){if(!this._issueFieldsCache[e.resourceId]){let n=await Xe(this.config,e,t);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,t={}){let n=t.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(t),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,t={}){let n=await this.getResourceUrl({resourceId:e.resourceId},t),o=await this.config.request({url:`${t.baseUrl||Ae}/${e.resourceId}/rest/api/2/myself`,headers:f(t.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let t=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:f(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=t.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,t={}){let n=new URL(`${t.baseUrl||Ae}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",cr.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,t={}){let n=[];return await Promise.all(e.resourceIds.map(async o=>{try{return await Or(i=>this.getJiraProjectsForResource({resourceId:o,cursor:i},t))}catch{return[]}})).then((...o)=>{o.forEach(i=>{n=n.concat(...i)})}),{data:n}}async getAccountsForJiraProject(e,t={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},t),u=new URL(`${t.baseUrl||Ae}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",cr.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},data:l.body.filter(d=>d.accountType!=="app"&&d.active).map(d=>Ke(d,a,!1))}}async getComponentsForJiraProject(e,t={}){return await ot(this.config,e,t)}async getIssue(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ye(this.config,{...e,fields:n},o,t)}async getIssuesForProject(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await et(this.config,{...e,fields:n},o,t)}async getIssuesForProjects(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await tt(this.config,{...e,fields:n},o,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},t),o=await this.getResourceUrl({resourceId:e.resourceId},t);return await Ze(this.config,{...e,fields:n},o,t)}async setIssueStatus(e,t={}){await nt(this.config,e,t)}async setIssueAssignee(e,t={}){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:`${t.baseUrl||Ae}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...f(t.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,t={}){await st(this.config,e,t)}async setIssueLabels(e,t={}){await rt(this.config,e,t)}async getLabelsForResource(e,t={}){let{resourceId:n,cursor:o}=e,i=new URL(`${t.baseUrl||Ae}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",cr.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:f(t.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var ye=class extends j{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let t=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[t]){let n=await Xe(this.config,{},e);this._issueFieldsCache[t]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[t]??null}async getCurrentUser(e={}){let t=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:f(e?.token||this.config.token)});return{data:{name:t.body.displayName,email:t.body.emailAddress,avatarUrl:t.body.avatarUrls["48x48"],id:t.body.key,username:t.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:f(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ye(this.config,{...e,fields:o},n,t)}async getIssuesForProject(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await et(this.config,{...e,fields:o},n,t)}async getIssuesForProjects(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await tt(this.config,{...e,fields:o},n,t)}async getIssuesForResourceForCurrentUser(e,t={}){let n=e.resourceUrl||t.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(t);return await Ze(this.config,{...e,fields:o},n,t)}async setIssueStatus(e,t={}){await nt(this.config,e,t)}async setIssueLabels(e,t={}){await rt(this.config,e,t)}async setIssueComponents(e,t={}){await st(this.config,e,t)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:f(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,t={}){return await ot(this.config,e,t)}};var gr=100,it=class{constructor(){this.set=new Set;this.arr=[]}push(...r){let e=r.filter(t=>!this.set.has(t.id));this.arr.push(...e),e.forEach(t=>this.set.add(t.id))}get length(){return this.arr.length}get items(){return this.arr}},te=async(s,r,e,t)=>{let n=r.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:t})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},mr=s=>s?s instanceof Date?s:new Date(s):null,mo=`
|
|
1370
1370
|
id
|
|
1371
1371
|
name
|
|
1372
1372
|
description
|
|
@@ -1374,11 +1374,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1374
1374
|
startDate
|
|
1375
1375
|
targetDate
|
|
1376
1376
|
url
|
|
1377
|
-
`,
|
|
1377
|
+
`,ps=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:mr(s.startDate),targetDate:mr(s.targetDate),url:s.url}),cs=async(s,r,e)=>{let t=`
|
|
1378
1378
|
query GetProjects($first: Int!, $after: String) {
|
|
1379
1379
|
projects(first: $first, after: $after) {
|
|
1380
1380
|
nodes {
|
|
1381
|
-
${
|
|
1381
|
+
${mo}
|
|
1382
1382
|
}
|
|
1383
1383
|
pageInfo {
|
|
1384
1384
|
hasNextPage
|
|
@@ -1386,7 +1386,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1386
1386
|
}
|
|
1387
1387
|
}
|
|
1388
1388
|
}
|
|
1389
|
-
`;return(await
|
|
1389
|
+
`;return(await te(s,r,t,{first:gr,after:e})).projects},go=`
|
|
1390
1390
|
id
|
|
1391
1391
|
name
|
|
1392
1392
|
number
|
|
@@ -1394,11 +1394,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1394
1394
|
startsAt
|
|
1395
1395
|
endsAt
|
|
1396
1396
|
completedAt
|
|
1397
|
-
`,ms=s=>({id:s.id,name:s.name??`Cycle ${s.number}`,number:s.number,description:s.description??null,startsAt:new Date(s.startsAt),endsAt:new Date(s.endsAt),completedAt:
|
|
1397
|
+
`,ms=s=>({id:s.id,name:s.name??`Cycle ${s.number}`,number:s.number,description:s.description??null,startsAt:new Date(s.startsAt),endsAt:new Date(s.endsAt),completedAt:mr(s.completedAt),url:""}),gs=async(s,r,e)=>{let t=`
|
|
1398
1398
|
query GetCycles($first: Int!, $after: String) {
|
|
1399
1399
|
cycles(first: $first, after: $after) {
|
|
1400
1400
|
nodes {
|
|
1401
|
-
${
|
|
1401
|
+
${go}
|
|
1402
1402
|
}
|
|
1403
1403
|
pageInfo {
|
|
1404
1404
|
hasNextPage
|
|
@@ -1406,7 +1406,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1406
1406
|
}
|
|
1407
1407
|
}
|
|
1408
1408
|
}
|
|
1409
|
-
`;return(await
|
|
1409
|
+
`;return(await te(s,r,t,{first:gr,after:e})).cycles},ho=`
|
|
1410
1410
|
id
|
|
1411
1411
|
name
|
|
1412
1412
|
color
|
|
@@ -1415,7 +1415,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1415
1415
|
query GetLabels($first: Int!, $after: String) {
|
|
1416
1416
|
projectLabels(first: $first, after: $after) {
|
|
1417
1417
|
nodes {
|
|
1418
|
-
${
|
|
1418
|
+
${ho}
|
|
1419
1419
|
}
|
|
1420
1420
|
pageInfo {
|
|
1421
1421
|
hasNextPage
|
|
@@ -1423,31 +1423,31 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1423
1423
|
}
|
|
1424
1424
|
}
|
|
1425
1425
|
}
|
|
1426
|
-
`;return(await
|
|
1426
|
+
`;return(await te(s,r,t,{first:gr,after:e})).projectLabels};var Le=(i=>(i[i.None=0]="None",i[i.Assignee=1]="Assignee",i[i.Creator=2]="Creator",i[i.Mention=3]="Mention",i[i.MentionInDescription=4]="MentionInDescription",i[i.MentionInComments=5]="MentionInComments",i))(Le||{});function Rs(s,r){return s?`${Le[s]}:${r||""}`:r??null}function Is(s){if(!s)return{category:0};let[r,e]=s.split(":");return r in Le?{category:Le[r],cursor:e||void 0}:{category:0,cursor:s}}var bs=100;function ut(s){return s?s instanceof Date?s:new Date(s):null}var Ps=`
|
|
1427
1427
|
id
|
|
1428
1428
|
name
|
|
1429
1429
|
key
|
|
1430
1430
|
icon
|
|
1431
|
-
`;function
|
|
1431
|
+
`;function fo(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var ys=`
|
|
1432
1432
|
id
|
|
1433
1433
|
name
|
|
1434
1434
|
avatarUrl
|
|
1435
|
-
`;function ws(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var
|
|
1435
|
+
`;function ws(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var Ro=`
|
|
1436
1436
|
id
|
|
1437
1437
|
name
|
|
1438
|
-
`;function
|
|
1438
|
+
`;function Io(s,r){if(s)return{id:s.id,name:s.name,key:r?.key||null,namespace:null,resourceId:r?.id||null}}var bo=`
|
|
1439
1439
|
id
|
|
1440
1440
|
sortOrder
|
|
1441
1441
|
name
|
|
1442
1442
|
description
|
|
1443
1443
|
status
|
|
1444
1444
|
targetDate
|
|
1445
|
-
`;function
|
|
1445
|
+
`;function yo(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:ut(s.targetDate)}:null}function wo(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Po=`
|
|
1446
1446
|
id
|
|
1447
1447
|
name
|
|
1448
1448
|
color
|
|
1449
1449
|
type
|
|
1450
|
-
`;function
|
|
1450
|
+
`;function vo(s){return s?{id:s.id,name:s.name,color:s.color,category:wo(s.type)}:null}var fr=`
|
|
1451
1451
|
creator {
|
|
1452
1452
|
${ys}
|
|
1453
1453
|
}
|
|
@@ -1460,35 +1460,35 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1460
1460
|
id
|
|
1461
1461
|
identifier
|
|
1462
1462
|
project {
|
|
1463
|
-
${
|
|
1463
|
+
${Ro}
|
|
1464
1464
|
}
|
|
1465
1465
|
team {
|
|
1466
1466
|
${Ps}
|
|
1467
1467
|
}
|
|
1468
1468
|
state {
|
|
1469
|
-
${
|
|
1469
|
+
${Po}
|
|
1470
1470
|
}
|
|
1471
1471
|
title
|
|
1472
1472
|
updatedAt
|
|
1473
1473
|
url
|
|
1474
1474
|
projectMilestone {
|
|
1475
|
-
${
|
|
1475
|
+
${bo}
|
|
1476
1476
|
}
|
|
1477
|
-
`;async function
|
|
1477
|
+
`;async function hr(s){return{author:ws(await s.creator),assignees:[ws(await s.assignee)].filter(r=>r!=null),commentCount:null,closedDate:ut(s.archivedAt),createdDate:ut(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:Io(await s.project,await s.team),state:vo(await s.state),title:s.title,type:null,updatedDate:ut(s.updatedAt),upvoteCount:null,url:s.url,milestone:yo(await s.projectMilestone)}}var at=`
|
|
1478
1478
|
nodes {
|
|
1479
|
-
${
|
|
1479
|
+
${fr}
|
|
1480
1480
|
}
|
|
1481
1481
|
pageInfo {
|
|
1482
1482
|
hasNextPage
|
|
1483
1483
|
endCursor
|
|
1484
1484
|
}
|
|
1485
|
-
`,
|
|
1485
|
+
`,we=class extends F{async fetchIssue(r,e){let t=`
|
|
1486
1486
|
query GetIssue($identifier: String!) {
|
|
1487
1487
|
issue(id: $identifier) {
|
|
1488
|
-
${
|
|
1488
|
+
${fr}
|
|
1489
1489
|
}
|
|
1490
1490
|
}
|
|
1491
|
-
`;return(await
|
|
1491
|
+
`;return(await te(this.config,e,t,{identifier:r})).issue}async fetchOrganization(r){let e=`
|
|
1492
1492
|
query GetOrganization {
|
|
1493
1493
|
organization {
|
|
1494
1494
|
id
|
|
@@ -1496,7 +1496,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1496
1496
|
urlKey
|
|
1497
1497
|
}
|
|
1498
1498
|
}
|
|
1499
|
-
`;return(await
|
|
1499
|
+
`;return(await te(this.config,r,e)).organization}async fetchTeams(r){let e=`
|
|
1500
1500
|
query GetTeams {
|
|
1501
1501
|
teams {
|
|
1502
1502
|
nodes {
|
|
@@ -1504,7 +1504,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1504
1504
|
}
|
|
1505
1505
|
}
|
|
1506
1506
|
}
|
|
1507
|
-
`;return(await
|
|
1507
|
+
`;return(await te(this.config,r,e)).teams}async rawRequest(r,e,t){return{data:await te(this.config,r,e,t)}}async fetchViewer(r){let e=`
|
|
1508
1508
|
query GetViewer {
|
|
1509
1509
|
viewer {
|
|
1510
1510
|
id
|
|
@@ -1513,7 +1513,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1513
1513
|
displayName
|
|
1514
1514
|
}
|
|
1515
1515
|
}
|
|
1516
|
-
`;return(await
|
|
1516
|
+
`;return(await te(this.config,r,e)).viewer}async getIssue(r,e={}){let t=await this.fetchIssue(r.number,e);return{data:await hr(t)}}async getLinearOrganization(r={}){let e=await this.fetchOrganization(r);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(r={}){return{data:(await this.fetchTeams(r)).nodes.map(fo)}}async getProjects(r={},e={}){let t=await cs(this.config,e,r.cursor??void 0);return{data:t.nodes.map(ps),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCycles(r={},e={}){let t=await gs(this.config,e,r.cursor??void 0);return{data:t.nodes.map(ms),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getLabels(r={},e={}){let t=await fs(this.config,e,r.cursor??void 0);return{data:t.nodes.map(hs),pageInfo:{hasNextPage:t.pageInfo.hasNextPage,endCursor:t.pageInfo.endCursor??null}}}async getCurrentUser(r={}){return{data:await this.fetchViewer(r)}}async getIssuesForCurrentUser(r,e={}){let{cursor:t}=r,{category:n,cursor:o}=Is(t),i=await this.fetchViewer(e),a,u,l=new it,d=async(c,p)=>{if(u||n>c)return;let g=await p(Math.max(bs-l.length,1),n===c?o:void 0);if(!g)return;let m=await Tt(g.nodes.map(hr));l.push(...m),g.pageInfo.hasNextPage&&(a=c,u=g.pageInfo.endCursor)};return await d(1,async(c,p)=>(await this.rawRequest(e,`
|
|
1517
1517
|
query GetAssignedIssues($first: Int!, $after: String) {
|
|
1518
1518
|
viewer {
|
|
1519
1519
|
issues: assignedIssues(first: $first, after: $after) {
|
|
@@ -1521,7 +1521,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1521
1521
|
}
|
|
1522
1522
|
}
|
|
1523
1523
|
}
|
|
1524
|
-
`,{first:c,after:
|
|
1524
|
+
`,{first:c,after:p})).data?.viewer?.issues),await d(2,async(c,p)=>(await this.rawRequest(e,`
|
|
1525
1525
|
query GetCreatedIssues($first: Int!, $after: String) {
|
|
1526
1526
|
viewer {
|
|
1527
1527
|
issues: createdIssues(first: $first, after: $after) {
|
|
@@ -1529,7 +1529,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1529
1529
|
}
|
|
1530
1530
|
}
|
|
1531
1531
|
}
|
|
1532
|
-
`,{first:c,after:
|
|
1532
|
+
`,{first:c,after:p})).data?.viewer?.issues),await d(4,async(c,p)=>(await this.rawRequest(e,`
|
|
1533
1533
|
query GetMentionedIssues($first: Int!, $after: String) {
|
|
1534
1534
|
issues(
|
|
1535
1535
|
first: $first
|
|
@@ -1553,7 +1553,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1553
1553
|
${at}
|
|
1554
1554
|
}
|
|
1555
1555
|
}
|
|
1556
|
-
`,{first:c,after:
|
|
1556
|
+
`,{first:c,after:p})).data?.issues),await d(5,async(c,p)=>{let m=(await this.rawRequest(e,`
|
|
1557
1557
|
query GetCommentedIssues($first: Int!, $after: String) {
|
|
1558
1558
|
comments(
|
|
1559
1559
|
first: $first
|
|
@@ -1576,7 +1576,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1576
1576
|
){
|
|
1577
1577
|
nodes {
|
|
1578
1578
|
issue {
|
|
1579
|
-
${
|
|
1579
|
+
${fr}
|
|
1580
1580
|
}
|
|
1581
1581
|
}
|
|
1582
1582
|
pageInfo {
|
|
@@ -1585,10 +1585,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1585
1585
|
}
|
|
1586
1586
|
}
|
|
1587
1587
|
}
|
|
1588
|
-
`,{first:c,after:
|
|
1588
|
+
`,{first:c,after:p})).data?.comments;return m?{nodes:m.nodes.map(y=>y.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:Rs(a,u)}}}async getIssues(r,e={}){let{teams:t,projects:n,labels:o,cursor:i}=r,a=[];if(t&&t.length>0){let g=t.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(n&&n.length>0){let g=n.map(m=>`"${m}"`).join(", ");a.push(`project: { id: { in: [${g}] } }`)}if(o&&o.length>0){let g=o.map(m=>`"${m}"`).join(", ");a.push(`labels: { name: { in: [${g}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",l=`
|
|
1589
1589
|
query GetIssues($first: Int!, $after: String) {
|
|
1590
1590
|
issues(first: $first, after: $after${u?", ":""}${u}) {
|
|
1591
1591
|
${at}
|
|
1592
1592
|
}
|
|
1593
1593
|
}
|
|
1594
|
-
`,c=(await this.rawRequest(e,l,{first:bs,after:i})).data?.issues;return c?{data:await Ut(c.nodes.map(gr)),pageInfo:{hasNextPage:c.pageInfo.hasNextPage,endCursor:c.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var K="https://api.trello.com",Po=1e3,X=(s,r)=>({...f(r),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${r}"`}),vo=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),qo=(s,r)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:r[s.idList??""]?{id:s.idList,name:r[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},be=class extends F{async getCurrentUser(r,e={}){let t=await this.config.request({url:`${e.baseUrl||K}/1/members/me`,headers:X(r.appKey,e.token||this.config.token)});return{data:{name:t.body.fullName,email:t.body.email,avatarUrl:t.body.avatarHash?`https://trello-members.s3.amazonaws.com/${t.body.id}/${t.body.avatarHash}/50.png`:null,id:t.body.id,username:t.body.username,url:t.body.url}}}async getBoardsForCurrentUser(r,e={}){return{data:(await this.config.request({url:`${e.baseUrl||K}/1/members/me/boards?fields=name&filter=open`,headers:X(r.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(r,e={}){let{appKey:t,boardId:n}=r;return{data:(await this.config.request({url:`${e.baseUrl||K}/1/boards/${n}/lists`,headers:X(t,e.token||this.config.token)})).body}}async getAccountForId(r,e={}){let{appKey:t,memberId:n}=r,o=await this.config.request({url:`${e.baseUrl||K}/1/members/${n}`,headers:X(t,e.token||this.config.token)});return{data:vo(o.body)}}async getAccountsForTrelloBoard(r,e={}){let{appKey:t,boardId:n}=r;return{data:(await this.config.request({url:`${e.baseUrl||K}/1/boards/${n}/members`,headers:X(t,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(r,e={}){let t=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=r||{};a&&t.push("@me"),u&&u.forEach(d=>t.push(`label:"${d}"`));let p=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||K}/1/search?query=${p}&cards_limit=${Po}&card_members=true`,headers:X(n,e.token||this.config.token)})).body.cards.map(d=>qo(d,l||{}))}}async updateIssue(r,e,t,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||K}/1/cards/${e.id}?${t}`,headers:X(r,n.token||this.config.token)})}async setIssueStatus(r,e={}){let{appKey:t,issue:n,status:o}=r;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(r,e={}){let{appKey:t,issue:n,assignees:o}=r,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(r,e={}){let{appKey:t,issue:n,labels:o}=r,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||K}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:X(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(r,e={}){let{appKey:t,issue:n,archived:o}=r;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||K}/1/cards/${n.id}?closed=${o}`,headers:X(t,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(r,e={}){await this.setIssueArchived({...r,archived:!0},e)}async unArchiveIssue(r,e={}){await this.setIssueArchived({...r,archived:!1},e)}async getLabelsForBoard(r,e={}){let{appKey:t,boardId:n}=r;return{data:(await this.config.request({url:`${e.baseUrl||K}/1/boards/${n}/labels`,headers:X(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var lt={};W(lt,{default:()=>Eo});var Eo={};var pt={};W(pt,{default:()=>So});var So={};var Pt={};W(Pt,{decode:()=>fr,decodeV0:()=>Ao,encode:()=>$o,validate:()=>Do});var k=(e=>(e.Zero="0",e.One="1",e))(k||{}),_=(e=>(e.PullRequest="pr",e.Issue="issue",e))(_||{}),x=(d=>(d.Azure="azure",d.AzureDevOpsServer="azureDevOpsServer",d.Github="github",d.GithubEnterprise="githubEnterprise",d.Gitlab="gitlab",d.GitlabSelfHosted="gitlabSelfHosted",d.Bitbucket="bitbucket",d.BitbucketServer="bitbucketServer",d.Jira="jira",d.JiraServer="jiraServer",d.Linear="linear",d.Trello="trello",d))(x||{});var dt=class{constructor(){}validate(r){if(!r.organizationName)throw new Error("organizationName is required");if(!r.projectId)throw new Error("projectId is required");if(!r.entityId)throw new Error("issueId is required")}encode(r){if(this.validate(r),!r.organizationName||!r.projectId||!r.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="azureDevOpsServer"?e.push(r.domain):e.push(""),e.push(r.organizationName),e.push(r.projectId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:r[4],projectId:r[5],repoId:null,entityId:r[6]}}};var ct=class{constructor(){}validate(r){if(!r.organizationName)throw new Error("organizationName is required");if(!r.projectId)throw new Error("projectId is required");if(!r.repoId)throw new Error("repoId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.organizationName||!r.projectId||!r.repoId||!r.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="azureDevOpsServer"?e.push(r.domain):e.push(""),e.push(r.organizationName),e.push(r.projectId),e.push(r.repoId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:r[4],projectId:r[5],repoId:r[6],entityId:r[7]}}};var mt=class{constructor(){}validate(r){if(!r.repoId)throw new Error("repoId is required");if(!r.entityId)throw new Error("issueId is required")}encode(r){if(this.validate(r),!r.repoId||!r.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="bitbucketServer"?e.push(r.domain):e.push(""),e.push(r.repoId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:r[4],entityId:r[5]}}};var gt=class{constructor(){}validate(r){if(!r.repoId)throw new Error("repoId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.repoId||!r.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="bitbucketServer"?e.push(r.domain):e.push(""),e.push(r.repoId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:r[4],entityId:r[5]}}};var ht=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="githubEnterprise"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var ft=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="githubEnterprise"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var Rt=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="gitlabSelfHosted"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var It=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="gitlabSelfHosted"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var bt=class{constructor(){}validate(r){if(!r.projectId)throw new Error("projectId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.projectId||!r.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider=="jira"?(e.push(""),e.push(r.resourceId)):(e.push(r.domain),e.push("")),e.push(r.projectId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:r[4]==""?null:r[4],accountOrOrgId:null,organizationName:null,projectId:r[5],repoId:null,entityId:r[6]}}};var yt=class{constructor(){}validate(r){if(!r.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!r.projectId)throw new Error("projectId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.accountOrOrgId||!r.projectId||!r.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(r.accountOrOrgId),e.push(r.projectId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:r[4],organizationName:null,projectId:r[5],repoId:null,entityId:r[6]}}};var wt=(s,r)=>{if(r!=="issue"&&r!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return r==="pr"?new ct:new dt;case"bitbucket":case"bitbucketServer":return r==="pr"?new gt:new mt;case"github":case"githubEnterprise":return r==="pr"?new ft:new ht;case"gitlab":case"gitlabSelfHosted":return r==="pr"?new It:new Rt;case"jira":case"jiraServer":if(r==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new bt;case"trello":if(r==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new yt;default:throw new Error("unknown provider")}},Co=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")},Do=s=>{if(s.version==="0"){Co(s);return}wt(s.provider,s.entityType).validate(s)},$o=s=>wt(s.provider,s.entityType).encode(s),fr=s=>{let r=JSON.parse(s);if(!r||!r.length)throw new Error("invalid issue unique id");return wt(r[0],r[1]).decode(r)},Ao=(s,r,e)=>{if(!e)throw new Error("entityID is required");try{let t=JSON.parse(e);if(!t||!t.length)throw new Error("Invalid pull request uniqueId");let n=[s,r,"0",...t];return wt(s,r).decode(n)}catch{return{provider:s,entityType:r,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var vt={};W(vt,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>Ds,CHANGES_REQUESTED_BUCKET_ID:()=>vr,CONFLICTS_ACTION_CATEGORY:()=>Ss,CONFLICTS_BUCKET_ID:()=>wr,DRAFT_ACTION_CATEGORY:()=>Ls,DRAFT_BUCKET_ID:()=>Sr,FAILING_CI_ACTION_CATEGORY:()=>Es,FAILING_CI_BUCKET_ID:()=>yr,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Cs,NEEDS_MY_REVIEW_BUCKET_ID:()=>Pr,OTHER_ACTION_CATEGORY:()=>Us,OTHER_BUCKET_ID:()=>Cr,PINNED_BUCKET_ID:()=>Rr,READY_TO_MERGE_ACTION_CATEGORY:()=>vs,READY_TO_MERGE_BUCKET_ID:()=>Ir,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>$s,REVIEWER_COMMENTED_BUCKET_ID:()=>qr,SNOOZED_BUCKET_ID:()=>Dr,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>qs,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>br,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>As,WAITING_FOR_REVIEW_BUCKET_ID:()=>Er,getActionablePullRequests:()=>Ts,groupPullRequestsByAssignee:()=>To,groupPullRequestsByAuthor:()=>Go,groupPullRequestsByGitKrakenTeam:()=>_o,groupPullRequestsByRepo:()=>Uo,groupPullRequestsByReviewer:()=>Oo,groupPullRequestsByWorkspace:()=>ko,groupPullRequestsIntoBuckets:()=>Lo});var Q=(s,r,e,t)=>({id:s,faIconName:e,name:r,priority:t,pullRequests:[]}),Rr="pinned",Ir="readyToMerge",br="unassignedReviewers",yr="failingCI",wr="conflicts",Pr="needsMyReview",vr="changesRequested",qr="reviewerCommented",Er="waitingForReview",Sr="draft",Cr="other",Dr="snoozed",vs="readyToMerge",qs="unassignedReviewers",Es="failingCI",Ss="conflicts",Cs="needsMyReview",Ds="changesRequested",$s="reviewerCommented",As="waitingForReview",Ls="draft",Us="other",Ts=(s,r,e)=>s.map(t=>{let o={...t,...{suggestedActionCategory:Us,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}};r&&(o.viewer.isAuthor=t.author?.id===r.id,o.viewer.isAssignee=t.assignees?.some(u=>u.id===r.id)??!1,o.viewer.isReviewer=t.reviews?.some(u=>u.reviewer.id===r.id)??!1),o.viewer.canMerge=t.permissions?.canMerge??!0,o.hasConflicts=t.mergeableState==="CONFLICTS",o.failingCI=t.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||t.mergeableState==="FAILING_CHECKS",o.commentReviewCount=t.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=t.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=t.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[t.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?.[t.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!r||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&t.mergeableState==="MERGEABLE"&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=vs),(!r||o.viewer.isAuthor)&&t.isDraft&&(o.suggestedActionCategory=Ls),(!r||o.viewer.isAuthor)&&t.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=As,o.viewer.waitingOnReviews=!0),(!r||o.viewer.isAuthor)&&t.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=$s),(!r||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Es),(!r||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=Ss),(!r||o.viewer.isAuthor)&&(t.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=Ds),(!r||o.viewer.isAuthor)&&!t.reviews?.length&&(o.suggestedActionCategory=qs,o.viewer.shouldAssignReviewer=!0),r&&t.reviews?.some(u=>u.reviewer.id===r.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=Cs,o.viewer.shouldReview=!0),o}),Lo=(s,r,e)=>{let t={pinned:Q(Rr,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:Q(Ir,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:Q(br,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:Q(yr,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:Q(wr,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:Q(Pr,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:Q(vr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:Q(qr,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:Q(Er,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:Q(Sr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:Q(Cr,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:Q(Dr,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=Ts(s,r,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){t[Dr].pullRequests.push(i);return}a.viewer.pinned&&t[Rr].pullRequests.push(i),(!r||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(t[Ir].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(t[br].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.failingCI&&(t[yr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.hasConflicts&&(t[wr].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(t[Pr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(t[vr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(t[qr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(t[Er].pullRequests.push(i),u=!1),a.isDraft&&(t[Sr].pullRequests.push(i),u=!1),u&&t[Cr].pullRequests.push(i)}),Object.values(t).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),t},Uo=s=>{let r={};return s.forEach(e=>{let t=e.repository.id;r[t]?r[t].pullRequests.push(e):r[t]={name:e.repository.name,priority:0,pullRequests:[e],id:t}}),ie(r)},To=s=>{let r="internal-no-assignees",e={[r]:{name:"No assignees",priority:-1,pullRequests:[],id:r,faIconName:"user-slash"}};return s.forEach(t=>{t.assignees&&t.assignees.length?t.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(t):e[o]={accountData:n,name:Te(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[t],id:o}}):e[r].pullRequests.push(t)}),ie(e)},Go=s=>{let r="internal-no-author",e={[r]:{name:"No author",priority:-1,pullRequests:[],id:r,faIconName:"user-slash"}};return s.forEach(t=>{if(t.author){let n=t.author.id;e[n]?e[n].pullRequests.push(t):e[n]={accountData:t.author,name:Te(t.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[t],id:n}}else e[r].pullRequests.push(t)}),ie(e)},Oo=s=>{let r="internal-no-reviewer",e={[r]:{name:"No reviewers",priority:-1,pullRequests:[],id:r,faIconName:"user-slash"}};return s.forEach(t=>{t.reviews&&t.reviews.length?t.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(t):e[o]={accountData:n.reviewer,name:Te(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[t],id:o}}):e[r].pullRequests.push(t)}),ie(e)},xo=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(r=>`${s.provider}-${r.repositoryId}`)??[],ko=(s,r)=>{let e="internal-no-workspace",t={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(r.length){let n=r.reduce((o,i)=>(xo(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=fr(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((c,d)=>n[d]?c.concat(n[d]):c,[]);p?.length&&p.forEach(c=>{l=!0;let d=c.id;t[d]?t[d].pullRequests.push(o):t[d]={name:c.name,priority:0,pullRequests:[o],id:d,faIconName:"folder"}}),l||t[e].pullRequests.push(o)})}else t[e].pullRequests=s;return ie(t)},_o=(s,r,e,t)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return t.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)),t.forEach(l=>{if(l.members?.some(c=>{let d=r[c.id]?.[e]?.providerID;return d&&u.has(d)})){a=!0;let c=l.id;o[c]?o[c].pullRequests.push(i):o[c]={name:l.name,priority:0,pullRequests:[i],id:c,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,ie(o)};var qt={};W(qt,{getPullRequestRank:()=>No});var No=(s,r,e)=>{let t=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===r&&(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===r?t+=1e3:s.assignees?.find(i=>i.id===r)?t+=900:n==="REVIEW_REQUESTED"?t+=800:e&&(t+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?t+=100:s.mergeableState==="CONFLICTS"?t+=90:t+=80:o=="CHANGES_REQUESTED"&&(t+=70),t};var Et={};W(Et,{default:()=>jo});var jo={};var St={};W(St,{default:()=>Bo});var Bo={};var Ct={};W(Ct,{default:()=>Qo});var Qo={};var Gs=s=>{let r={request:s?.request};return{azureDevOps:new pe({...r,...s?.azureDevOps}),bitbucket:new de({...r,...s?.bitbucket}),bitbucketServer:new ce({...r,...s?.bitbucketServer}),github:new me({...r,...s?.github}),gitlab:new he({...r,...s?.gitlab}),jira:new fe({...r,...s?.jira}),jiraServer:new Re({...r,...s?.jiraServer}),linear:new Ie({...r,...s?.linear}),trello:new be({...r,...s?.trello})}};var Os=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(Os||{});var xs=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(xs||{});var Fo=Gs;var Mo={azureDevOps:lt,bitbucket:pt,bitbucketServer:_e,github:qt,gitlab:Et,gitProvider:vt,jira:St,trello:Ct,entityIdentifier:Pt};
|
|
1594
|
+
`,c=(await this.rawRequest(e,l,{first:bs,after:i})).data?.issues;return c?{data:await Tt(c.nodes.map(hr)),pageInfo:{hasNextPage:c.pageInfo.hasNextPage,endCursor:c.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var V="https://api.trello.com",qo=1e3,K=(s,r)=>({...f(r),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${r}"`}),Eo=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),So=(s,r)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(t=>({id:t.id,username:t.username,name:t.fullName,email:null,avatarUrl:t.avatarUrl,url:null})),description:null,state:r[s.idList??""]?{id:s.idList,name:r[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(t=>({color:t.color,description:null,id:t.id,name:t.name}))}},Pe=class extends F{async getCurrentUser(r,e={}){let t=await this.config.request({url:`${e.baseUrl||V}/1/members/me`,headers:K(r.appKey,e.token||this.config.token)});return{data:{name:t.body.fullName,email:t.body.email,avatarUrl:t.body.avatarHash?`https://trello-members.s3.amazonaws.com/${t.body.id}/${t.body.avatarHash}/50.png`:null,id:t.body.id,username:t.body.username,url:t.body.url}}}async getBoardsForCurrentUser(r,e={}){return{data:(await this.config.request({url:`${e.baseUrl||V}/1/members/me/boards?fields=name&filter=open`,headers:K(r.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(r,e={}){let{appKey:t,boardId:n}=r;return{data:(await this.config.request({url:`${e.baseUrl||V}/1/boards/${n}/lists`,headers:K(t,e.token||this.config.token)})).body}}async getAccountForId(r,e={}){let{appKey:t,memberId:n}=r,o=await this.config.request({url:`${e.baseUrl||V}/1/members/${n}`,headers:K(t,e.token||this.config.token)});return{data:Eo(o.body)}}async getAccountsForTrelloBoard(r,e={}){let{appKey:t,boardId:n}=r;return{data:(await this.config.request({url:`${e.baseUrl||V}/1/boards/${n}/members`,headers:K(t,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(r,e={}){let t=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=r||{};a&&t.push("@me"),u&&u.forEach(p=>t.push(`label:"${p}"`));let d=`${i?`${i}`:""}${t.join(" ")} board:${o}`;return{data:(await this.config.request({url:`${e.baseUrl||V}/1/search?query=${d}&cards_limit=${qo}&card_members=true`,headers:K(n,e.token||this.config.token)})).body.cards.map(p=>So(p,l||{}))}}async updateIssue(r,e,t,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||V}/1/cards/${e.id}?${t}`,headers:K(r,n.token||this.config.token)})}async setIssueStatus(r,e={}){let{appKey:t,issue:n,status:o}=r;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(t,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(r,e={}){let{appKey:t,issue:n,assignees:o}=r,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(t,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(r,e={}){let{appKey:t,issue:n,labels:o}=r,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||V}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:K(t,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(r,e={}){let{appKey:t,issue:n,archived:o}=r;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||V}/1/cards/${n.id}?closed=${o}`,headers:K(t,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(r,e={}){await this.setIssueArchived({...r,archived:!0},e)}async unArchiveIssue(r,e={}){await this.setIssueArchived({...r,archived:!1},e)}async getLabelsForBoard(r,e={}){let{appKey:t,boardId:n}=r;return{data:(await this.config.request({url:`${e.baseUrl||V}/1/boards/${n}/labels`,headers:K(t,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var lt={};z(lt,{default:()=>Co});var Co={};var dt={};z(dt,{default:()=>Do});var Do={};var Pt={};z(Pt,{decode:()=>Rr,decodeV0:()=>Uo,encode:()=>Lo,validate:()=>Ao});var _=(e=>(e.Zero="0",e.One="1",e))(_||{}),N=(e=>(e.PullRequest="pr",e.Issue="issue",e))(N||{}),x=(p=>(p.Azure="azure",p.AzureDevOpsServer="azureDevOpsServer",p.Github="github",p.GithubEnterprise="githubEnterprise",p.Gitlab="gitlab",p.GitlabSelfHosted="gitlabSelfHosted",p.Bitbucket="bitbucket",p.BitbucketServer="bitbucketServer",p.Jira="jira",p.JiraServer="jiraServer",p.Linear="linear",p.Trello="trello",p))(x||{});var pt=class{constructor(){}validate(r){if(!r.organizationName)throw new Error("organizationName is required");if(!r.projectId)throw new Error("projectId is required");if(!r.entityId)throw new Error("issueId is required")}encode(r){if(this.validate(r),!r.organizationName||!r.projectId||!r.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="azureDevOpsServer"?e.push(r.domain):e.push(""),e.push(r.organizationName),e.push(r.projectId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:r[4],projectId:r[5],repoId:null,entityId:r[6]}}};var ct=class{constructor(){}validate(r){if(!r.organizationName)throw new Error("organizationName is required");if(!r.projectId)throw new Error("projectId is required");if(!r.repoId)throw new Error("repoId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.organizationName||!r.projectId||!r.repoId||!r.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="azureDevOpsServer"?e.push(r.domain):e.push(""),e.push(r.organizationName),e.push(r.projectId),e.push(r.repoId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:r[4],projectId:r[5],repoId:r[6],entityId:r[7]}}};var mt=class{constructor(){}validate(r){if(!r.repoId)throw new Error("repoId is required");if(!r.entityId)throw new Error("issueId is required")}encode(r){if(this.validate(r),!r.repoId||!r.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="bitbucketServer"?e.push(r.domain):e.push(""),e.push(r.repoId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:r[4],entityId:r[5]}}};var gt=class{constructor(){}validate(r){if(!r.repoId)throw new Error("repoId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.repoId||!r.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="bitbucketServer"?e.push(r.domain):e.push(""),e.push(r.repoId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:r[4],entityId:r[5]}}};var ht=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="githubEnterprise"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var ft=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="githubEnterprise"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var Rt=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider==="gitlabSelfHosted"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var It=class{constructor(){}validate(r){if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(r.provider),e.push("pr"),e.push("1"),r.provider==="gitlabSelfHosted"?e.push(r.domain):e.push(""),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:r[4]}}};var bt=class{constructor(){}validate(r){if(!r.projectId)throw new Error("projectId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.projectId||!r.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(r.provider),e.push("issue"),e.push("1"),r.provider=="jira"?(e.push(""),e.push(r.resourceId)):(e.push(r.domain),e.push("")),e.push(r.projectId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:r[4]==""?null:r[4],accountOrOrgId:null,organizationName:null,projectId:r[5],repoId:null,entityId:r[6]}}};var yt=class{constructor(){}validate(r){if(!r.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!r.projectId)throw new Error("projectId is required");if(!r.entityId)throw new Error("entityId is required")}encode(r){if(this.validate(r),!r.accountOrOrgId||!r.projectId||!r.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(r.accountOrOrgId),e.push(r.projectId),e.push(r.entityId),JSON.stringify(e)}decode(r){if(r.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:r[0],entityType:r[1],version:r[2],domain:r[3]==""?null:r[3],resourceId:null,accountOrOrgId:r[4],organizationName:null,projectId:r[5],repoId:null,entityId:r[6]}}};var wt=(s,r)=>{if(r!=="issue"&&r!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return r==="pr"?new ct:new pt;case"bitbucket":case"bitbucketServer":return r==="pr"?new gt:new mt;case"github":case"githubEnterprise":return r==="pr"?new ft:new ht;case"gitlab":case"gitlabSelfHosted":return r==="pr"?new It:new Rt;case"jira":case"jiraServer":if(r==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new bt;case"trello":if(r==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new yt;default:throw new Error("unknown provider")}},$o=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")},Ao=s=>{if(s.version==="0"){$o(s);return}wt(s.provider,s.entityType).validate(s)},Lo=s=>wt(s.provider,s.entityType).encode(s),Rr=s=>{let r=JSON.parse(s);if(!r||!r.length)throw new Error("invalid issue unique id");return wt(r[0],r[1]).decode(r)},Uo=(s,r,e)=>{if(!e)throw new Error("entityID is required");try{let t=JSON.parse(e);if(!t||!t.length)throw new Error("Invalid pull request uniqueId");let n=[s,r,"0",...t];return wt(s,r).decode(n)}catch{return{provider:s,entityType:r,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var vt={};z(vt,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>Ds,CHANGES_REQUESTED_BUCKET_ID:()=>qr,CONFLICTS_ACTION_CATEGORY:()=>Ss,CONFLICTS_BUCKET_ID:()=>Pr,DRAFT_ACTION_CATEGORY:()=>Ls,DRAFT_BUCKET_ID:()=>Cr,FAILING_CI_ACTION_CATEGORY:()=>Es,FAILING_CI_BUCKET_ID:()=>wr,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>Cs,NEEDS_MY_REVIEW_BUCKET_ID:()=>vr,OTHER_ACTION_CATEGORY:()=>Us,OTHER_BUCKET_ID:()=>Dr,PINNED_BUCKET_ID:()=>Ir,READY_TO_MERGE_ACTION_CATEGORY:()=>vs,READY_TO_MERGE_BUCKET_ID:()=>br,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>$s,REVIEWER_COMMENTED_BUCKET_ID:()=>Er,SNOOZED_BUCKET_ID:()=>$r,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>qs,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>yr,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>As,WAITING_FOR_REVIEW_BUCKET_ID:()=>Sr,getActionablePullRequests:()=>Ts,groupPullRequestsByAssignee:()=>Oo,groupPullRequestsByAuthor:()=>xo,groupPullRequestsByGitKrakenTeam:()=>jo,groupPullRequestsByRepo:()=>Go,groupPullRequestsByReviewer:()=>ko,groupPullRequestsByWorkspace:()=>No,groupPullRequestsIntoBuckets:()=>To});var Q=(s,r,e,t)=>({id:s,faIconName:e,name:r,priority:t,pullRequests:[]}),Ir="pinned",br="readyToMerge",yr="unassignedReviewers",wr="failingCI",Pr="conflicts",vr="needsMyReview",qr="changesRequested",Er="reviewerCommented",Sr="waitingForReview",Cr="draft",Dr="other",$r="snoozed",vs="readyToMerge",qs="unassignedReviewers",Es="failingCI",Ss="conflicts",Cs="needsMyReview",Ds="changesRequested",$s="reviewerCommented",As="waitingForReview",Ls="draft",Us="other",Ts=(s,r,e)=>s.map(t=>{let o={...t,...{suggestedActionCategory:Us,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}};r&&(o.viewer.isAuthor=t.author?.id===r.id,o.viewer.isAssignee=t.assignees?.some(u=>u.id===r.id)??!1,o.viewer.isReviewer=t.reviews?.some(u=>u.reviewer.id===r.id)??!1),o.viewer.canMerge=t.permissions?.canMerge??!0,o.hasConflicts=t.mergeableState==="CONFLICTS",o.failingCI=t.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||t.mergeableState==="FAILING_CHECKS",o.commentReviewCount=t.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=t.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=t.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[t.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?.[t.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!r||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&t.mergeableState==="MERGEABLE"&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=vs),(!r||o.viewer.isAuthor)&&t.isDraft&&(o.suggestedActionCategory=Ls),(!r||o.viewer.isAuthor)&&t.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=As,o.viewer.waitingOnReviews=!0),(!r||o.viewer.isAuthor)&&t.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=$s),(!r||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Es),(!r||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=Ss),(!r||o.viewer.isAuthor)&&(t.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=Ds),(!r||o.viewer.isAuthor)&&!t.reviews?.length&&(o.suggestedActionCategory=qs,o.viewer.shouldAssignReviewer=!0),r&&t.reviews?.some(u=>u.reviewer.id===r.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=Cs,o.viewer.shouldReview=!0),o}),To=(s,r,e)=>{let t={pinned:Q(Ir,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:Q(br,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:Q(yr,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:Q(wr,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:Q(Pr,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:Q(vr,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:Q(qr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:Q(Er,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:Q(Sr,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:Q(Cr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:Q(Dr,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:Q($r,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=Ts(s,r,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){t[$r].pullRequests.push(i);return}a.viewer.pinned&&t[Ir].pullRequests.push(i),(!r||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(t[br].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(t[yr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.failingCI&&(t[wr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.hasConflicts&&(t[Pr].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(t[vr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(t[qr].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(t[Er].pullRequests.push(i),u=!1),(!r||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(t[Sr].pullRequests.push(i),u=!1),a.isDraft&&(t[Cr].pullRequests.push(i),u=!1),u&&t[Dr].pullRequests.push(i)}),Object.values(t).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),t},Go=s=>{let r={};return s.forEach(e=>{let t=e.repository.id;r[t]?r[t].pullRequests.push(e):r[t]={name:e.repository.name,priority:0,pullRequests:[e],id:t}}),ae(r)},Oo=s=>{let r="internal-no-assignees",e={[r]:{name:"No assignees",priority:-1,pullRequests:[],id:r,faIconName:"user-slash"}};return s.forEach(t=>{t.assignees&&t.assignees.length?t.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(t):e[o]={accountData:n,name:Te(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[t],id:o}}):e[r].pullRequests.push(t)}),ae(e)},xo=s=>{let r="internal-no-author",e={[r]:{name:"No author",priority:-1,pullRequests:[],id:r,faIconName:"user-slash"}};return s.forEach(t=>{if(t.author){let n=t.author.id;e[n]?e[n].pullRequests.push(t):e[n]={accountData:t.author,name:Te(t.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[t],id:n}}else e[r].pullRequests.push(t)}),ae(e)},ko=s=>{let r="internal-no-reviewer",e={[r]:{name:"No reviewers",priority:-1,pullRequests:[],id:r,faIconName:"user-slash"}};return s.forEach(t=>{t.reviews&&t.reviews.length?t.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(t):e[o]={accountData:n.reviewer,name:Te(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[t],id:o}}):e[r].pullRequests.push(t)}),ae(e)},_o=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(r=>`${s.provider}-${r.repositoryId}`)??[],No=(s,r)=>{let e="internal-no-workspace",t={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(r.length){let n=r.reduce((o,i)=>(_o(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Rr(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,d=u.reduce((c,p)=>n[p]?c.concat(n[p]):c,[]);d?.length&&d.forEach(c=>{l=!0;let p=c.id;t[p]?t[p].pullRequests.push(o):t[p]={name:c.name,priority:0,pullRequests:[o],id:p,faIconName:"folder"}}),l||t[e].pullRequests.push(o)})}else t[e].pullRequests=s;return ae(t)},jo=(s,r,e,t)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return t.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)),t.forEach(l=>{if(l.members?.some(c=>{let p=r[c.id]?.[e]?.providerID;return p&&u.has(p)})){a=!0;let c=l.id;o[c]?o[c].pullRequests.push(i):o[c]={name:l.name,priority:0,pullRequests:[i],id:c,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,ae(o)};var qt={};z(qt,{getPullRequestRank:()=>Bo});var Bo=(s,r,e)=>{let t=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===r&&(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===r?t+=1e3:s.assignees?.find(i=>i.id===r)?t+=900:n==="REVIEW_REQUESTED"?t+=800:e&&(t+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?t+=100:s.mergeableState==="CONFLICTS"?t+=90:t+=80:o=="CHANGES_REQUESTED"&&(t+=70),t};var Et={};z(Et,{default:()=>Qo});var Qo={};var St={};z(St,{default:()=>Fo});var Fo={};var Ct={};z(Ct,{default:()=>Mo});var Mo={};var Gs=s=>{let r={request:s?.request};return{azureDevOps:new me({...r,...s?.azureDevOps}),bitbucket:new ge({...r,...s?.bitbucket}),bitbucketServer:new he({...r,...s?.bitbucketServer}),github:new fe({...r,...s?.github}),gitlab:new Ie({...r,...s?.gitlab}),jira:new be({...r,...s?.jira}),jiraServer:new ye({...r,...s?.jiraServer}),linear:new we({...r,...s?.linear}),trello:new Pe({...r,...s?.trello})}};var Os=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(Os||{});var xs=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(xs||{});var zo=Gs;var Wo={azureDevOps:lt,bitbucket:dt,bitbucketServer:_e,github:qt,gitlab:Et,gitProvider:vt,jira:St,trello:Ct,entityIdentifier:Pt};
|