@gitkraken/provider-apis 0.53.0 → 0.54.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/index.js +150 -149
- package/dist/index.provider-utils.js +1 -1
- package/dist/index.providers.js +181 -180
- package/dist/providers/bitbucketServer/bitbucketServer.d.ts +3 -11
- package/dist/providers/github/github.d.ts +8 -0
- package/dist/providers/github/githubHelpers.d.ts +1 -1
- package/dist/providers/gitlab/gitlab.d.ts +4 -1
- package/dist/types/exportedTypes/gitProvider.d.ts +6 -0
- package/dist/types/exportedTypes/issueProvider.d.ts +3 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var Bt=Object.defineProperty;var yn=Object.getOwnPropertyDescriptor;var Pn=Object.getOwnPropertyNames;var wn=Object.prototype.hasOwnProperty;var H=(s,t)=>{for(var e in t)Bt(s,e,{get:t[e],enumerable:!0})},qn=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Pn(t))!wn.call(s,n)&&n!==e&&Bt(s,n,{get:()=>t[n],enumerable:!(r=yn(t,n))||r.enumerable});return s};var vn=s=>qn(Bt({},"__esModule",{value:!0}),s);var Fi={};H(Fi,{AzureDevOps:()=>we,AzureDevopsUtils:()=>yt,Bitbucket:()=>qe,BitbucketServer:()=>ve,BitbucketServerUtils:()=>Je,BitbucketUtils:()=>Pt,EntityIdentifierProviderType:()=>N,EntityIdentifierUtils:()=>Gt,EntityType:()=>j,EntityVersion:()=>B,GitBuildStatusStage:()=>zr,GitBuildStatusState:()=>Ue,GitDiffLineType:()=>jt,GitHub:()=>Ee,GitHubIssueCloseReason:()=>hn,GitHubUtils:()=>Ot,GitIssueState:()=>me,GitLab:()=>Se,GitLabUtils:()=>_t,GitMergeStrategy:()=>be,GitProviderUtils:()=>Tt,GitPullRequestMergeableState:()=>ee,GitPullRequestReviewState:()=>V,GitPullRequestState:()=>ie,GraphQLErrors:()=>I,Jira:()=>Ce,JiraServer:()=>De,JiraUtils:()=>kt,Linear:()=>Ae,PullRequestAsyncStatus:()=>mn,Trello:()=>$e,TrelloUtils:()=>xt,Utils:()=>ji,default:()=>Bi,isFetch:()=>ze});module.exports=vn(Fi);var ns=require("diff");var zr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(zr||{}),Ue=(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))(Ue||{}),be=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(be||{}),ie=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(ie||{}),V=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(V||{}),ee=(u=>(u.Behind="BEHIND",u.Blocked="BLOCKED",u.Conflicts="CONFLICTS",u.FailingChecks="FAILING_CHECKS",u.Mergeable="MERGEABLE",u.Unknown="UNKNOWN",u.UnknownAndBlocked="UNKNOWN_AND_BLOCKED",u.Unstable="UNSTABLE",u))(ee||{}),jt=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(jt||{});var Mr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},J=s=>!s||s.length===0?null:s.reduce((t,e)=>Mr[e.state]>Mr[t]?e.state:t,"APPROVED"),Qe=(s,t)=>s.name||s.username||s.email||t,ce=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var En=new Set(["ECONNABORTED","ECONNREFUSED","ECONNRESET","EAI_AGAIN","ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"]),R=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},Vr=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,ae=(s,t,e)=>!s||t.some(r=>s[r])?e:"",Jr=async s=>{let t=[],e=!0,r;for(;e;){let n=await s(r);t=t.concat(n.data),e=!!n?.pageInfo?.hasNextPage,r=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return t};async function Ft(s){return(await Promise.allSettled(s)).map(e=>$n(e)).filter(e=>e!=null)}var L=(s,{fallback:t,max:e})=>!s||s<=0?t:e===void 0?s:Math.min(s,e),x=(s,t)=>{if(!t||t.length===0)return s;let e=new Set(t);return s.filter(r=>e.has(r.state))},Sn=s=>{if(!(!s||typeof s!="object")){if("statusCode"in s&&typeof s.statusCode=="number")return s.statusCode;if("response"in s&&s.response&&typeof s.response=="object"&&"status"in s.response&&typeof s.response.status=="number")return s.response.status}},Cn=s=>{if(!(!s||typeof s!="object"||!("code"in s)||typeof s.code!="string"))return s.code},Kr=s=>{if(typeof s=="string")return s;if(s instanceof Error)return s.message},Dn=s=>{let t=Sn(s);if(t===401)return"authentication";if(t===404)return"not-found";if(t===429)return"rate-limit";if(t!==void 0)return"provider";let e=Cn(s);if(e&&En.has(e))return"network";let r=Kr(s)?.toLowerCase();return r&&(r.includes("network")||r.includes("fetch failed")||r.includes("timed out")||r.includes("timeout")||r.includes("econn")||r.includes("enotfound")||r.includes("eai_again"))?"network":"unknown"},An=(s,t)=>{let e=Kr(t);return{scope:s,kind:Dn(t),...e?{message:e}:{}}},ye=(s,t=[])=>({completeness:s,...t.length?{failures:t}:{}}),Wr={complete:0,unknown:1,partial:2},Hr=(s,t)=>Wr[s]>=Wr[t]?s:t,ge=s=>s?s.id||`${s.namespace}/${s.name}`:void 0;async function te(s,{run:t,failureScope:e,completeness:r,concurrency:n}){let o=async d=>{try{return{scope:d,result:await t(d)}}catch(p){return{scope:d,error:p}}},i;if(n===void 0)i=await Promise.all(s.map(o));else{if(!Number.isInteger(n)||n<=0)throw new Error("concurrency must be a positive integer");let d=new Array(s.length);await Qt(s.map((p,c)=>({scope:p,index:c})),n,async({scope:p,index:c})=>{d[c]=await o(p)}),i=d}let a=[],u=[],l="complete";return i.forEach(d=>{if("error"in d){a.push(An(e(d.scope),d.error)),l=Hr(l,"partial");return}if(d.result===void 0)return;let p=d.result;l=Hr(l,r?r(p):"complete"),u.push({scope:d.scope,result:p})}),{successes:u,metadata:ye(l,a)}}function $n(s,t=void 0){return s?.status==="fulfilled"?s.value:t}async function Qt(s,t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)throw new Error("batchSize must be a positive integer");for(let r=0;r<s.length;r+=t){let n=s.slice(r,r+t);await Promise.all(n.map(e))}}var me=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(me||{});var zt=(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))(zt||{});var C=100;var Xr=globalThis.fetch;var Ln=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(t.startsWith("text/")||t===""||t.startsWith("application/vnd.github.diff")||t.startsWith("application/vnd.github.patch"))e=await s.text();else if(t.startsWith("application/vnd.github.raw+json")||t.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${t}`);let r={};s.headers.forEach((o,i)=>{r[i]=o});let n={body:e,headers:r,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},Mt=s=>async({url:t,...e})=>{let r=await s(t,e);return Ln(r)};var ze=(s,t=!1)=>s.name==="fetch"||t;var M=class{constructor(t){let e=t?.request||Xr;this.config={...t,request:ze(e,t?.forceIsFetch)?Mt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&ze(t.request,t?.forceIsFetch??this.config.forceIsFetch)?Mt(t.request):this.config.request}}},F=class extends M{};var Un="https://app.vssps.visualstudio.com/_apis",Gn="https://vssps.dev.azure.com/",Tn="https://dev.azure.com",q=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT),Zr=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),Wt=(s,t)=>{let e=t.baseUrl||s.baseUrl||Un;return e=e.replace(/\/$/,""),e},D=(s,t)=>{let e=t.baseUrl||s.baseUrl||Tn;return e=e.replace(/\/$/,""),e},Ht=(s,t)=>{let e=t.baseUrl||s.baseUrl||Gn;return e=e.replace(/\/$/,""),e};var On={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},_n={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},Pe=100,kn=200,Yr=5,xn=200,es=s=>{if(!s||s.length===0)return"active";let t=Array.from(new Set(s.map(e=>_n[e])));return t.length===1?t[0]:"all"},Nn=s=>{if(!s||s.length===0)return["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"];let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?[]:r?["([Microsoft.VSTS.Common.ClosedDate] <> '' OR [Microsoft.VSTS.Common.ResolvedDate] <> '')"]:["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"]},Bn=s=>{if(typeof s!="string")return s;let t=s.charAt(0).toUpperCase()+s.slice(1);return zt[t]??0},jn=new Set([2,3,4,5]),Fn={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},he=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),Me=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Qn=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"}},Vt=(s,t,e,r,n,o)=>`${s}|${t}|${e}|${r}|${n}|${o}`,ts=s=>{let t=s.split("|");if(t.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4],commentId:t[5]}},rs=(s,t,e,r,n)=>`${s}|${t}|${e}|${r}|${n}`,Jt=s=>{let t=s.split("|");if(t.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4]}},Ge=(s,t,e)=>{let r=!!t.forkSource,n=[],o=[];return t.reviewers.forEach(i=>{let a={reviewer:he(i),state:Fn[i.vote??0]||"REVIEW_REQUESTED"};i.isRequired&&n.push(a),o.push(a)}),{id:t.pullRequestId.toString(),title:t.title,description:t.description??null,number:t.codeReviewId,state:On[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:he(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,isCrossRepository:r,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null},headCommit:{buildStatuses:null},baseRef:{name:Me(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:Me(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:Zr(t),assignees:t.reviewers.map(he),reviews:o,reviewDecision:J(n),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:e?.get(t.forkSource.repository.id)??null,isFork:!0}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null,isFork:!1},mergeableState:Qn(t.mergeStatus),labels:t.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},ss=(s,t)=>({id:t.id,name:t.name,namespace:s,project:t.project.name,projectId:t.project.id,webUrl:t.webUrl,httpsUrl:t.remoteUrl,sshUrl:t.sshUrl,defaultBranch:t.defaultBranch?{name:Me(t.defaultBranch)}:null,permissions:null}),zn=(s,t,e,r)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=r[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},we=class extends F{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,r){let n=JSON.stringify([e,r.token??null,r.isPAT??this.config.isPAT??!1,r.baseUrl??null]),o=this.cachedUserIds.get(n);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(n);if(i)return i;let a=this.fetchCurrentUserId(e,r,n);return this.inflightUserIds.set(n,a),a}async fetchCurrentUserId(e,r,n){try{let o=await this.getCurrentUserForInstance({namespace:e},r);return this.cachedUserIds.set(n,o.data.id),o.data.id}finally{this.inflightUserIds.delete(n)}}getRepoApiUrl(e,r,n,o){return`${D(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(r)}/_apis/git/repositories/${encodeURIComponent(n)}`}async getCurrentUser(e={},r={}){if(r.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let n=`${Wt(this.config,r)}/profile/profiles/me`,o=await this.config.request({url:n,headers:q(this.config,r)});return{data:{id:o.body.id,name:o.body.displayName,username:o.body.displayName,email:o.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(e,r={}){let o=(await this.config.request({url:`${D(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:q(this.config,r)})).body.authorizedUser;if(o.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:o.id,name:o.providerDisplayName,username:o.providerDisplayName,email:o.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=(await this.config.request({url:`${D(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:q(this.config,r)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,r={}){let n=`${Wt(this.config,r)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,r={}){let n=`${D(this.config,r)}/_apis/projectCollections`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,r={}){let n=new URL(`${D(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/projects`);n.searchParams.set("$top",C.toString()),e.cursor&&n.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:n.toString(),headers:q(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({id:a.id,name:a.name,namespace:e.namespace}))}}async getAzureProjectScopeDescriptor(e,r={}){let{namespace:n,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${Ht(this.config,r)}/${encodeURIComponent(n)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:q(this.config,r)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,r={}){let{namespace:n,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${Ht(this.config,r)}/${encodeURIComponent(n)}/_apis/graph/users`);o&&a.searchParams.set("scopeDescriptor",o),i&&a.searchParams.set("continuationToken",i);let u=await this.config.request({url:a.toString(),headers:q(this.config,r)}),l=u.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:l||null,hasNextPage:!!l},data:u.body.value.map(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,r={}){let{azureGraphAccount:n}=e;if(!n.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:n.storageKeyURL,headers:q(this.config,r)});return{data:{avatarUrl:n.avatarUrl,email:n.email,id:o.body.value,name:n.name,username:n.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,r={}){let n=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},r);n.push(i.data)}return{data:n}}async getRepo(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${D(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:q(this.config,r)});return{data:ss(e.namespace,n.body)}}async getRepos(e,r={}){let n=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,r);n.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:n,errors:o}}async getReposForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${D(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:q(this.config,r)})).body.value.map(o=>ss(e.namespace,o))}}async getRefs(e,r,n={}){if(!r.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${D(this.config,n)}/${encodeURIComponent(r.repo.namespace)}/${encodeURIComponent(r.repo.project)}/_apis/git/repositories/${encodeURIComponent(r.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",C.toString()),r.cursor&&o.searchParams.set("continuationToken",r.cursor);let i=await this.config.request({url:o.toString(),headers:q(this.config,n)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:Me(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,r={}){return this.getRefs("heads",e,r)}async getTags(e,r={}){return this.getRefs("tags",e,r)}async fetchRemoteInfoByRepoId(e,r,n){let o=new Map;if(!e)return o;let i=new Map;for(let{namespace:a,pullRequests:u}of r)for(let l of u)i.has(l.repository.id)||i.set(l.repository.id,a),l.forkSource&&!i.has(l.forkSource.repository.id)&&i.set(l.forkSource.repository.id,a);return await Qt([...i],10,async([a,u])=>{try{let l=await this.config.request({url:`${D(this.config,n)}/${encodeURIComponent(u)}/_apis/git/repositories/${encodeURIComponent(a)}`,headers:q(this.config,n)}),{remoteUrl:d,sshUrl:p}=l.body;d&&p&&o.set(a,{cloneUrlHTTPS:d,cloneUrlSSH:p})}catch{}}),o}async getPullRequestsForRepoBase(e,r={},n=Pe){let{page:o,repo:i,assigneeLogins:a,authorLogin:u,reviewerId:l}=e||{},d=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let p=L(e.pageSize,{fallback:n}),c=l??(a&&a.length?a[0]:void 0),m=`searchCriteria.status=${es(e.states)}`;return c&&(m+=`&searchCriteria.reviewerId=${encodeURIComponent(c)}`),u&&(m+=`&searchCriteria.creatorId=${encodeURIComponent(u)}`),await this.config.request({url:`${D(this.config,r)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${m}&%24top=${p}&%24skip=${(d-1)*p}`,headers:q(this.config,r)})}async getPullRequestsForRepo(e,r={}){let n=L(e.pageSize,{fallback:Pe}),o=e.page||1,i=await this.getPullRequestsForRepoBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:e.repo.namespace,pullRequests:i.body.value}],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i.body.value.map(l=>Ge(e.repo.namespace,l,u)),e.states)}}async getPullRequestsForRepos(e,r={}){if(!e.repos.every(p=>p.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:n}=e||{},o=L(e.pageSize,{fallback:Pe}),{successes:i,metadata:a}=await te(n,{run:p=>this.getPullRequestsForRepoBase({repo:p,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o},r,o),failureScope:p=>({providerId:"azure",projectId:p.project,repositoryId:ge(p)}),completeness:p=>p.body.value.length===o?"unknown":"complete",concurrency:Yr}),u=i.map(({scope:p,result:c})=>({namespace:p.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,r),d=u.flatMap(({namespace:p,pullRequests:c})=>c.map(m=>Ge(p,m,l)));return{data:x(d,e.states),metadata:a}}async getPullRequestsForProjectBase(e,r={},n=Pe){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,reviewerId:d,repo:p}=e;if(p?.project&&p.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,m=L(e.pageSize,{fallback:n}),g=d??(u&&u.length?u[0]:void 0),h=new URL(`${D(this.config,r)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",es(e.states)),h.searchParams.set("$top",m.toString()),h.searchParams.set("$skip",((c-1)*m).toString()),p?.id&&p?.project===i&&h.searchParams.set("searchCriteria.repositoryId",p.id),g&&h.searchParams.set("searchCriteria.reviewerId",g),l&&h.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:h.toString(),headers:q(this.config,r)})}async getPullRequestsForProject(e,r={}){let n=L(e.pageSize,{fallback:Pe}),o=e.page||1,i=await this.getPullRequestsForProjectBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,i?[{namespace:e.namespace,pullRequests:i.body.value}]:[],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i?.body.value.map(l=>Ge(e.namespace,l,u))||[],e.states)}}async getPullRequestsForProjects(e,r={}){let{projects:n}=e||{};if(e.repo&&!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=L(e.pageSize,{fallback:Pe}),{successes:i,metadata:a}=await te(n,{run:p=>e.repo&&e.repo.project!==p.project?Promise.resolve(void 0):this.getPullRequestsForProjectBase({...p,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o,repo:e.repo},r,o),failureScope:p=>({providerId:"azure",projectId:p.project,repositoryId:ge(e.repo)}),completeness:p=>p.body.value.length===o?"unknown":"complete",concurrency:Yr}),u=i.map(({scope:p,result:c})=>({namespace:p.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,r),d=u.flatMap(({namespace:p,pullRequests:c})=>c.map(m=>Ge(p,m,l)));return{data:x(d,e.states),metadata:a}}async getAzurePullRequestLastMergeStatus(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:n,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${D(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...q(this.config,r)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,r,n){return await this.config.request({method:"PATCH",url:`${D(this.config,n)}/${encodeURIComponent(e.repository.owner.login)}/${encodeURIComponent(e.repository.project)}/_apis/git/repositories/${e.repository.name}/pullrequests/${e.id}?api-version=6.0`,body:r,headers:{...q(this.config,n),"Content-Type":"application/json"}})}async closePullRequest(e,r={}){let{pullRequest:n}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(n,JSON.stringify(o),r)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,r={}){let{pullRequest:n,mergeStrategy:o}=e,i;switch(o){case"MERGE_COMMIT":{i="noFastForward";break}case"REBASE":{i="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{i="rebaseMerge";break}case"SQUASH":{i="squash";break}}let a={completionOptions:{mergeStrategy:i},lastMergeSourceCommit:{commitId:n.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(n,JSON.stringify(a),r)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i={name:o.name};if(!(await this.config.request({method:"POST",url:`${D(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${D(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...q(this.config,r)}})}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=n.labels;if(!i)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of o)i.find(u=>u.id===a.id)||await this.addPullRequestLabel({pullRequest:n,label:a},r);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:n,label:a},r)}async setPullRequestAsDraft(e,r={}){let{pullRequest:n,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(n,JSON.stringify(i),r)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${D(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${D(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,headers:{...q(this.config,r),Accept:"application/json"}})}async setPullRequestReviewers(e,r={}){let{pullRequest:n,reviewers:o}=e;for(let i of o)n.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:n,reviewer:i,isRequired:!0},r);for(let i of n.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:n,reviewer:i},r)}async getIssuesForAzureProject(e,r={}){let{page:n,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},d=n||1,p=Math.min(L(e.pageSize,{fallback:kn}),xn),c=["[System.TeamProject] = @project",...Nn(e.states)];i&&c.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&c.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&c.push("[System.Id] IN (@recentMentions)"),u&&u.forEach($=>c.push(`[System.Tags] Contains '${$}'`));let m=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${c.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${D(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:m}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}}),h=g.body.workItems.slice((d-1)*p,p*d).map($=>$.id),y=g.body.workItems.length,f=Math.ceil(y/p),P=y>p*d;if(h.length===0)return{pageInfo:{hasNextPage:!1,nextPage:null,currentPage:d,totalCount:y,totalPages:f},data:[]};let v=await this.config.request({url:`${D(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:h,$expand:"Links"}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?d+1:null,currentPage:d,totalCount:y,totalPages:f},data:v.body.value.map($=>zn(e.namespace,e.project,$,l||{}))}}async getPermissionsForRepos(e,r={}){let{namespace:n,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=p=>{let c="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",m=`repoV2/${p.projectId}/${p.id}`;return Object.keys(i).map(g=>({securityNamespaceId:c,token:m,permissions:g}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${D(this.config,r)}/${encodeURIComponent(n)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.evaluations.reduce((p,c)=>{let[,m,g]=c.token.split("/"),h=`${m}/${g}`,y=i[c.permissions];for(let f of y)p[h]===void 0&&(p[h]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),c.value===!1&&(p[h][f]=!1);return p},{})}}async decorateReposWithPermissions(e,r={}){let{namespace:n,repos:o}=e,i=await this.getPermissionsForRepos({namespace:n,repos:o},r);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,r,n={}){return await this.config.request({method:"PATCH",url:`${D(this.config,n)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(r),headers:{...q(this.config,n),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,r={}){let{issue:n,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,r={}){let{issue:n,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(n,a,r)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${D(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...q(this.config,r)}})).body.value}}async getLabelsForProject(e,r={}){let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${D(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...q(this.config,r)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:n.namespace,pullRequests:[i.body]}],r);return{data:Ge(n.namespace,i.body,a)}}async getPullRequestDescription(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');try{return{data:{description:(await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,r={}){let{repo:n,number:o,description:i}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:{description:(await this.config.request({method:"PATCH",url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:{...q(this.config,r),"Content-Type":"application/json"},body:JSON.stringify({description:i})})).body?.description??i}}}async getMergeBase(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:q(this.config,r)});if(!n.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:n.body.value[0].commitId}}async getFileContents(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...q(this.config,r),Accept:"application/octet-stream"}});return{data:new Blob([n.body])}}async getPullRequestDiff(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${n}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,d=a.body.lastMergeSourceCommit.commitId,p=u.body.value;if(p.length===0)return"";let c=p[p.length-1],m=1e3,g=[],h=0;for(;;){let S=(await this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations/${c.id}/changes?api-version=7.1&$top=${m}&$skip=${h}`,headers:o})).body.changeEntries??[];if(S.length===0||(g.push(...S),S.length<m))break;h+=S.length}if(g.length===0)return"";let y=5,f=[],P=new TextDecoder,v=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",$=async(w,S)=>{try{let pe=await this.config.request({url:`${n}/items?path=${encodeURIComponent(w)}&versionDescriptor[version]=${encodeURIComponent(S)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return v(pe.body)}catch{return""}},A=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let S=w.toLowerCase().split(",").map(pe=>pe.trim());return{add:S.includes("add"),rename:S.includes("rename"),delete:S.includes("delete")}};for(let w=0;w<g.length;w+=y){let S=g.slice(w,w+y),pe=await Promise.all(S.map(async Re=>{let{add:Ie,rename:Nt,delete:de}=A(Re.changeType),Le=Re.originalPath??Re.item.originalPath,T=Re.item.path,Fe=de?T??Le??"":T??"",Qr=Nt||de?Le??Fe:Fe,[fn,Rn]=await Promise.all([Ie?Promise.resolve(""):$(Qr,l),de?Promise.resolve(""):$(Fe,d)]),In=Ie?"/dev/null":`a${Qr}`,bn=de?"/dev/null":`b${Fe}`;return(0,ns.createTwoFilesPatch)(In,bn,fn,Rn)}));f.push(...pe)}return f.join(`
|
|
2
|
-
`)}getPullRequestWriteHeaders(e){return{...q(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,r,n,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${r}/reviewers/${encodeURIComponent(n)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,r,n,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${r}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:n,commentType:1}],status:1})})}async getCommentsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i=await this.config.request({url:`${n}/pullRequests/${e.pullRequestNumber}/threads?api-version=7.1`,headers:o}),a=[];for(let u of i.body.value)if(!(u.isDeleted||u.threadContext))for(let l of u.comments)l.commentType==="system"||l.isDeleted||a.push({id:Vt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?he(l.author):null,body:l.content||"",createdAt:l.publishedDate?new Date(l.publishedDate):null,url:""});return{data:a,pageInfo:{hasNextPage:!1,endCursor:null}}}async addCommentToPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async addInlineCommentToPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r),o=this.getPullRequestWriteHeaders(r);if(e.threadId){let d=Jt(e.threadId),p=e.pullRequest.repository.owner.login,c=e.pullRequest.repository.project,m=e.pullRequest.repository.name,g=String(e.pullRequest.id);if(d.namespace!==p||d.project!==c||d.repoName!==m||d.prId!==g)throw new Error(`Azure thread ID context mismatch: threadId targets ${d.namespace}/${d.project}/${d.repoName} pull request ${d.prId}, but input.pullRequest targets ${p}/${c}/${m} pull request ${g}.`);let y=(await this.config.request({url:`${n}/pullRequests/${e.pullRequest.id}/threads/${d.threadId}?api-version=7.1`,headers:q(this.config,r)})).body.comments?.find(P=>P.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${d.threadId}.`);let f=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 Vt(p,c,m,Number(g),Number(d.threadId),f.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let l=await this.config.request({method:"POST",url:`${n}/pullRequests/${e.pullRequest.id}/threads?api-version=7.1`,headers:o,body:JSON.stringify({comments:[{parentCommentId:0,content:e.comment,commentType:1}],status:1,threadContext:u})});return rs(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,r={}){let n=ts(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({content:e.body})})}async editInlineComment(e,r={}){return this.editComment(e,r)}async deleteComment(e,r={}){let n=ts(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:q(this.config,r)})}async deleteInlineComment(e,r={}){return this.deleteComment(e,r)}async resolveReviewThread(e,r={}){let n=Jt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,r={}){let n=Jt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:1})})}async approvePullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,r),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,r):null])}async requestPullRequestChanges(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,r),await this.setReviewerVote(o,e.pullRequest.id,i,-5,r)}async commentOnPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async getReviewsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(n,o,i,r),l=q(this.config,r),[d,p]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:l}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:l})]),c=(f,P)=>Vt(n,o,i,a,f,P),m=f=>rs(n,o,i,a,f),g=new Map;for(let f of p.body.value){if(f.isDeleted)continue;let P=f.comments.filter(T=>!T.isDeleted&&T.commentType!=="system"),v=P.find(T=>T.parentCommentId===0)??P[0];if(!v)continue;let $=v.author?.id;if(!$)continue;let A=P.filter(T=>T.id!==v.id),w=f.threadContext,S=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,pe=S?.end?.line??S?.start.line??null,Re=S?.start&&S.end&&S.start.line!==S.end.line?S.start.line:null,Ie=w?.filePath??"",Nt=Ie.startsWith("/")?Ie.slice(1):Ie,de={id:c(f.id,v.id),author:v.author?he(v.author):null,body:v.content??"",createdAt:v.publishedDate?new Date(v.publishedDate):null,url:"",diffLines:[],filename:Nt,replies:A.map(T=>({id:c(f.id,T.id),author:T.author?he(T.author):null,body:T.content??"",createdAt:T.publishedDate?new Date(T.publishedDate):null,url:""})),isOutdated:!1,isResolved:jn.has(Bn(f.status)),line:pe,startLine:Re,side:S?.side??null,threadId:m(f.id)},Le=g.get($);Le?Le.push(de):g.set($,[de])}let h=[],y=new Set;for(let f of d.body.value){if(f.hasDeclined)continue;let P=f.vote??0,v=g.get(f.id);P===0&&!v?.length||(h.push({id:f.id,author:he(f),body:"",createdAt:null,url:"",reviewComments:v??[]}),y.add(f.id))}for(let[f,P]of g){if(y.has(f)||!P.length)continue;let v=P[0].author;v&&h.push({id:f,author:v,body:"",createdAt:null,url:"",reviewComments:P})}return{data:h}}};var G=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT);var O="https://api.bitbucket.org/2.0",Mn={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},Wn={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},We=50,Hn=5,os=s=>{let t=!s||s.length===0?["OPEN"]:Array.from(new Set(s.flatMap(r=>Wn[r]))),e=t.map(r=>`state="${r}"`).join(" OR ");return t.length>1?`(${e})`:e},Vn=s=>s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),is=s=>{let t=s?.trim();if(!t)return null;let e=Vn(t);return`(title ~ "${e}" OR description ~ "${e}")`},as=s=>{let t=!!s.next,e=typeof s.size=="number"?s.size:null,r=typeof s.pagelen=="number"&&s.pagelen>0?s.pagelen:null;return{hasNextPage:t,nextPage:t?s.page+1:null,currentPage:typeof s.page=="number"?s.page:null,totalCount:e,totalPages:e!==null&&r?Math.ceil(e/r):null}},He={owner:4,admin:3,contributor:2,member:1},Ve=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}),us=s=>{let t=s.links.clone,e=t?.find(n=>n.name==="ssh"),r=t?.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},Kt=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(t=>t.name==="https")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),Xt=s=>{let t=s.id,e=s.participants?.map(r=>{let n="REVIEW_REQUESTED";return r.approved?n="APPROVED":r.state==="changes_requested"?n="CHANGES_REQUESTED":r.participated_on!==null&&(n="COMMENTED"),{reviewer:Ve(r.user),state:n}})??[];return{id:t.toString(),title:s.title,description:s.description,number:t,state:Mn[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:Ve(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:us(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:J(e),additions:null,deletions:null,fileCount:null,commitCount:null,isCrossRepository:s.source.repository.uuid!==s.destination.repository.uuid,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:us(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Jn=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}}},Kn=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}}},qe=class extends M{async refreshToken(t){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${O}/user`,headers:G(this.config,e)});return{data:Ve(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${O}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:G(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${O}/repositories/${t.namespace}/${t.name}`,headers:G(this.config,e)});return{data:Kt(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForWorkspace(t,e={}){let r=new URL(`${O}/repositories/${encodeURIComponent(t.workspace)}`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",C.toString()),t.minimumRole&&r.searchParams.set("role",t.minimumRole);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Kt)}}async getAllReposForWorkspace(t,e={}){let r=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:t.workspace,minimumRole:t.minimumRole,page:n},e);r.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return r}async getAllReposForWorkspaceWithPermissions(t,e={}){let r=new Map,n=[],o=He[t.minimumRole||"member"];o<=He.admin&&n.push("admin"),o<=He.contributor&&n.push("contributor"),o<=He.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:t.workspace,minimumRole:a},e);for(let u of i)r.has(u.id)||r.set(u.id,a)}return{data:i.map(a=>{let u=r.get(a.id)||"member";return{...a,permissions:Kn(u)}})}}async getReposForCurrentUser(t,e={}){let r=new URL(`${O}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",C.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(Kt)}}async getBranches(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",C.toString());let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",C.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(t={},e={}){let r=new URL(`${O}/user/workspaces`);r.searchParams.set("page",t?.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t?.administrator!==void 0&&r.searchParams.set("administrator",t.administrator.toString());let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(t,e={}){let r=new URL(`${O}/user/permissions/workspaces`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",L(t.pageSize,{fallback:We,max:We}).toString());let n=[os(t.states)];t.repos&&t.repos.length>0&&n.push(`(${t.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`);let o=is(t.query);o&&n.push(o),r.searchParams.set("q",n.join(" AND "));let i=await this.config.request({url:r.toString(),headers:G(this.config,e)});return{pageInfo:as(i.body),data:i.body.values.map(Xt)}}async getPullRequestsForReviewerAndWorkspace(t,e={}){let r=t.repos?.length?t.repos:await this.getAllReposForWorkspace({workspace:t.workspaceSlug},e);return this.getPullRequestsForRepos({repos:r,reviewerId:t.reviewerId,states:t.states,query:t.query,pageSize:t.pageSize},e)}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${O}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let o=os(t.states);n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`);let i=is(t.query);return i&&(o+=` AND ${i}`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",L(t.pageSize,{fallback:We,max:We}).toString()),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:G(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);return n.body.values.forEach(o=>{r.push(Xt(o))}),{pageInfo:as(n.body),data:r}}async getPullRequestsForRepos(t,e={}){let{successes:r,metadata:n}=await te(t.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,authorLogin:t.authorLogin,reviewerId:t.reviewerId,useOrFilter:t.useOrFilter,states:t.states,query:t.query,pageSize:t.pageSize},e),failureScope:i=>({providerId:"bitbucket",repositoryId:ge(i)}),completeness:i=>i.body.next?"partial":"complete",concurrency:Hn}),o=[];return r.forEach(({result:i})=>{i.body.values.forEach(a=>{o.push(Xt(a))})}),{data:o,metadata:n}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>Ve(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${O}/user/permissions/repositories`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:Jn(a.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:G(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var Je={};H(Je,{normalizePermissions:()=>Zt,restApiPullRequestToCommonPullRequest:()=>Xn});var Xn=s=>Te(s),Zt=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Oe=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},Te=s=>{let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(u=>({reviewer:Oe(u.user),state:e[u.status]})),n=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:s.id.toString(),number:s.id,title:s.title,description:s.description,url:s.links.self[0].href,state:t[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Oe(s.author.user),assignees:null,reviews:r,reviewDecision:J(r),isCrossRepository:s.fromRef.repository.id!==s.toRef.repository.id,repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},ls=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(t=>t.name==="https"||t.name==="http")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),ps=50,Zn=5,Yn={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},ds=s=>{if(!s||s.length===0)return"OPEN";let t=Array.from(new Set(s.map(e=>Yn[e])));return t.length===1?t[0]:"ALL"},cs=(s,t)=>typeof s!="number"||t<=0?null:Math.floor(s/t)+1,ve=class extends F{getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return R(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:d,id:p,name:c,slug:m})=>i?i===p:a===c||a===d||a===m);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Oe(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Oe(o.body.author)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data:ls(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=t.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(ls)}}async getRepoPermissionsForUsername(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:Zt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests`);return r.searchParams.set("state",ds(t.states)),r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit",L(t.pageSize,{fallback:ps}).toString()),t.reviewerLogin&&(r.searchParams.set("role.1","REVIEWER"),r.searchParams.set("username.1",t.reviewerLogin)),await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);n.body.values.forEach(i=>{if(t.authorLogin&&i.author.user.name!==t.authorLogin)return null;r.push(Te(i))});let o=!n.body.isLastPage;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.nextPageStart:null,currentPage:cs(n.body.start,n.body.limit)},data:x(r,t.states)}}async getPullRequestsForRepos(t,e={}){let{successes:r,metadata:n}=await te(t.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,reviewerLogin:t.reviewerLogin,states:t.states,pageSize:t.pageSize},e),failureScope:i=>({providerId:"bitbucketServer",repositoryId:ge(i)}),completeness:i=>i.body.isLastPage?"complete":"partial",concurrency:Zn}),o=[];return r.forEach(({result:i})=>{i.body.values.forEach(a=>{t.authorLogin&&a.author.user.name!==t.authorLogin||o.push(Te(a))})}),{data:x(o,t.states),metadata:n}}async getPullRequestsForCurrentUser(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state",ds(t.states)),r.searchParams.set("start",t.page?.toString()||"0");let n=L(t.pageSize,{fallback:ps});r.searchParams.set("limit",n.toString()),t.reviewerLogin&&(r.searchParams.set("role.1","REVIEWER"),r.searchParams.set("username.1",t.reviewerLogin));let o=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),i=!o.body.isLastPage;return{pageInfo:{hasNextPage:i,nextPage:i?o.body.nextPageStart:null,currentPage:cs(o.body.start,o.body.limit)},data:x(o.body.values.map(Te),t.states)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>Oe(i.user))}}};var As=require("js-base64");var I=class extends Error{constructor(e,r){let n=r?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var eo={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]},gs=15,ms=100,_e={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},k=s=>!!s,K=(s,t)=>{let e=eo[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Xe="https://api.github.com",to=`${Xe}/graphql`,Ze=`
|
|
1
|
+
"use strict";var jt=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var vn=Object.getOwnPropertyNames;var En=Object.prototype.hasOwnProperty;var H=(s,t)=>{for(var e in t)jt(s,e,{get:t[e],enumerable:!0})},Sn=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vn(t))!En.call(s,n)&&n!==e&&jt(s,n,{get:()=>t[n],enumerable:!(r=qn(t,n))||r.enumerable});return s};var Cn=s=>Sn(jt({},"__esModule",{value:!0}),s);var Wi={};H(Wi,{AzureDevOps:()=>we,AzureDevopsUtils:()=>Pt,Bitbucket:()=>qe,BitbucketServer:()=>ve,BitbucketServerUtils:()=>Ke,BitbucketUtils:()=>wt,EntityIdentifierProviderType:()=>N,EntityIdentifierUtils:()=>Tt,EntityType:()=>j,EntityVersion:()=>B,GitBuildStatusStage:()=>Mr,GitBuildStatusState:()=>Ue,GitDiffLineType:()=>Ft,GitHub:()=>Ee,GitHubIssueCloseReason:()=>In,GitHubUtils:()=>_t,GitIssueState:()=>he,GitLab:()=>Se,GitLabUtils:()=>kt,GitMergeStrategy:()=>ye,GitProviderUtils:()=>Ot,GitPullRequestMergeableState:()=>ee,GitPullRequestReviewState:()=>V,GitPullRequestState:()=>ae,GraphQLErrors:()=>I,Jira:()=>Ce,JiraServer:()=>De,JiraUtils:()=>xt,Linear:()=>Ae,PullRequestAsyncStatus:()=>Rn,Trello:()=>$e,TrelloUtils:()=>Nt,Utils:()=>Mi,default:()=>zi,isFetch:()=>Me});module.exports=Cn(Wi);var ns=require("diff");var Mr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(Mr||{}),Ue=(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))(Ue||{}),ye=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(ye||{}),ae=(r=>(r.Open="OPEN",r.Closed="CLOSED",r.Merged="MERGED",r))(ae||{}),V=(n=>(n.Approved="APPROVED",n.ChangesRequested="CHANGES_REQUESTED",n.Commented="COMMENTED",n.ReviewRequested="REVIEW_REQUESTED",n))(V||{}),ee=(u=>(u.Behind="BEHIND",u.Blocked="BLOCKED",u.Conflicts="CONFLICTS",u.FailingChecks="FAILING_CHECKS",u.Mergeable="MERGEABLE",u.Unknown="UNKNOWN",u.UnknownAndBlocked="UNKNOWN_AND_BLOCKED",u.Unstable="UNSTABLE",u))(ee||{}),Ft=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(Ft||{});var Wr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},J=s=>!s||s.length===0?null:s.reduce((t,e)=>Wr[e.state]>Wr[t]?e.state:t,"APPROVED"),Qe=(s,t)=>s.name||s.username||s.email||t,me=s=>{let t=Object.values(s).map(e=>e.name).sort((e,r)=>e.localeCompare(r));return Object.values(s).forEach(e=>{e.priority!==-1&&(e.priority=t.indexOf(e.name))}),s};var Dn=new Set(["ECONNABORTED","ECONNREFUSED","ECONNRESET","EAI_AGAIN","ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"]),R=(s,t)=>{let e={};return s&&(e.Authorization=`${t?"Basic":"Bearer"} ${s}`),e},Vr=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,ue=(s,t,e)=>!s||t.some(r=>s[r])?e:"",Jr=async s=>{let t=[],e=!0,r;for(;e;){let n=await s(r);t=t.concat(n.data),e=!!n?.pageInfo?.hasNextPage,r=n?.pageInfo?.endCursor||n?.pageInfo?.nextPage}return t};async function Qt(s){return(await Promise.allSettled(s)).map(e=>Gn(e)).filter(e=>e!=null)}var D=(s,{fallback:t,max:e})=>!s||s<=0?t:e===void 0?s:Math.min(s,e),x=(s,t)=>{if(!t||t.length===0)return s;let e=new Set(t);return s.filter(r=>e.has(r.state))},An=s=>{if(!(!s||typeof s!="object")){if("statusCode"in s&&typeof s.statusCode=="number")return s.statusCode;if("response"in s&&s.response&&typeof s.response=="object"&&"status"in s.response&&typeof s.response.status=="number")return s.response.status}},$n=s=>{if(!(!s||typeof s!="object"||!("code"in s)||typeof s.code!="string"))return s.code},Kr=s=>{if(typeof s=="string")return s;if(s instanceof Error)return s.message},Ln=s=>{let t=An(s);if(t===401)return"authentication";if(t===404)return"not-found";if(t===429)return"rate-limit";if(t!==void 0)return"provider";let e=$n(s);if(e&&Dn.has(e))return"network";let r=Kr(s)?.toLowerCase();return r&&(r.includes("network")||r.includes("fetch failed")||r.includes("timed out")||r.includes("timeout")||r.includes("econn")||r.includes("enotfound")||r.includes("eai_again"))?"network":"unknown"},Un=(s,t)=>{let e=Kr(t);return{scope:s,kind:Ln(t),...e?{message:e}:{}}},te=(s,t=[])=>({completeness:s,...t.length?{failures:t}:{}}),Hr={complete:0,unknown:1,partial:2},ze=(s,t)=>Hr[s]>=Hr[t]?s:t,ge=s=>s?s.id||`${s.namespace}/${s.name}`:void 0;async function re(s,{run:t,failureScope:e,completeness:r,concurrency:n}){let o=async d=>{try{return{scope:d,result:await t(d)}}catch(p){return{scope:d,error:p}}},i;if(n===void 0)i=await Promise.all(s.map(o));else{if(!Number.isInteger(n)||n<=0)throw new Error("concurrency must be a positive integer");let d=new Array(s.length);await zt(s.map((p,c)=>({scope:p,index:c})),n,async({scope:p,index:c})=>{d[c]=await o(p)}),i=d}let a=[],u=[],l="complete";return i.forEach(d=>{if("error"in d){a.push(Un(e(d.scope),d.error)),l=ze(l,"partial");return}if(d.result===void 0)return;let p=d.result;l=ze(l,r?r(p):"complete"),u.push({scope:d.scope,result:p})}),{successes:u,metadata:te(l,a)}}function Gn(s,t=void 0){return s?.status==="fulfilled"?s.value:t}async function zt(s,t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<=0)throw new Error("batchSize must be a positive integer");for(let r=0;r<s.length;r+=t){let n=s.slice(r,r+t);await Promise.all(n.map(e))}}var he=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(he||{});var Mt=(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))(Mt||{});var C=100;var Xr=globalThis.fetch;var Tn=async s=>{let t=s.headers.get("content-type")||"",e=null;if(t.startsWith("application/json")){let o=await s.text();e=o.trim().length>0?JSON.parse(o):null}else if(t.startsWith("text/")||t===""||t.startsWith("application/vnd.github.diff")||t.startsWith("application/vnd.github.patch"))e=await s.text();else if(t.startsWith("application/vnd.github.raw+json")||t.startsWith("application/octet-stream"))e=await s.arrayBuffer();else throw new Error(`Unsupported content-type: ${t}`);let r={};s.headers.forEach((o,i)=>{r[i]=o});let n={body:e,headers:r,status:s.status,statusText:s.statusText};if(!s.ok){let o=new Error(s.statusText);throw Object.assign(o,{response:n}),o}return n},Wt=s=>async({url:t,...e})=>{let r=await s(t,e);return Tn(r)};var Me=(s,t=!1)=>s.name==="fetch"||t;var M=class{constructor(t){let e=t?.request||Xr;this.config={...t,request:Me(e,t?.forceIsFetch)?Wt(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&Me(t.request,t?.forceIsFetch??this.config.forceIsFetch)?Wt(t.request):this.config.request}}},F=class extends M{};var On="https://app.vssps.visualstudio.com/_apis",_n="https://vssps.dev.azure.com/",kn="https://dev.azure.com",q=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT),Zr=s=>s.url.replace("/_apis/git/repositories/","/_git/").replace(`/${s.repository.project.id}/`,`/${encodeURIComponent(s.repository.project.name)}/`).replace(`/${s.repository.id}/`,`/${encodeURIComponent(s.repository.name)}/`).replace("/pullRequests/","/pullrequest/"),Ht=(s,t)=>{let e=t.baseUrl||s.baseUrl||On;return e=e.replace(/\/$/,""),e},A=(s,t)=>{let e=t.baseUrl||s.baseUrl||kn;return e=e.replace(/\/$/,""),e},Vt=(s,t)=>{let e=t.baseUrl||s.baseUrl||_n;return e=e.replace(/\/$/,""),e};var xn={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Nn={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},Pe=100,Bn=200,Yr=5,jn=200,es=s=>{if(!s||s.length===0)return"active";let t=Array.from(new Set(s.map(e=>Nn[e])));return t.length===1?t[0]:"all"},Fn=s=>{if(!s||s.length===0)return["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"];let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?[]:r?["([Microsoft.VSTS.Common.ClosedDate] <> '' OR [Microsoft.VSTS.Common.ResolvedDate] <> '')"]:["[Microsoft.VSTS.Common.ClosedDate] = ''","[Microsoft.VSTS.Common.ResolvedDate] = ''"]},Qn=s=>{if(typeof s!="string")return s;let t=s.charAt(0).toUpperCase()+s.slice(1);return Mt[t]??0},zn=new Set([2,3,4,5]),Mn={10:"APPROVED",5:"APPROVED",0:"REVIEW_REQUESTED",[-5]:"CHANGES_REQUESTED",[-10]:"CHANGES_REQUESTED"},fe=s=>({id:s.id,name:s.displayName??null,username:(s.uniqueName||s.displayName)??null,email:null,avatarUrl:s.imageUrl??null,url:null}),We=s=>s.startsWith("refs/heads/")?s.replace("refs/heads/",""):s,Wn=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"}},Jt=(s,t,e,r,n,o)=>`${s}|${t}|${e}|${r}|${n}|${o}`,ts=s=>{let t=s.split("|");if(t.length!==6)throw new Error("Invalid Azure comment ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4],commentId:t[5]}},rs=(s,t,e,r,n)=>`${s}|${t}|${e}|${r}|${n}`,Kt=s=>{let t=s.split("|");if(t.length!==5)throw new Error("Invalid Azure thread ID format");return{namespace:t[0],project:t[1],repoName:t[2],prId:t[3],threadId:t[4]}},Ge=(s,t,e)=>{let r=!!t.forkSource,n=[],o=[];return t.reviewers.forEach(i=>{let a={reviewer:fe(i),state:Mn[i.vote??0]||"REVIEW_REQUESTED"};i.isRequired&&n.push(a),o.push(a)}),{id:t.pullRequestId.toString(),title:t.title,description:t.description??null,number:t.codeReviewId,state:xn[t.status],isDraft:t.isDraft,commentCount:null,upvoteCount:null,author:fe(t.createdBy),createdDate:new Date(t.creationDate),updatedDate:new Date(t.closedDate||t.creationDate),closedDate:t.closedDate?new Date(t.closedDate):null,mergedDate:t.closedDate&&t.status==="completed"?new Date(t.closedDate):null,isCrossRepository:r,repository:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null},headCommit:{buildStatuses:null},baseRef:{name:We(t.targetRefName),oid:t.lastMergeTargetCommit.commitId},headRef:{name:We(t.sourceRefName),oid:t.lastMergeSourceCommit.commitId},url:Zr(t),assignees:t.reviewers.map(fe),reviews:o,reviewDecision:J(n),additions:null,deletions:null,fileCount:null,commitCount:null,headRepository:t.forkSource?{id:t.forkSource.repository.id,name:t.forkSource.repository.name,project:void 0,owner:{login:s},remoteInfo:e?.get(t.forkSource.repository.id)??null,isFork:!0}:{id:t.repository.id,name:t.repository.name,project:t.repository.project.name,owner:{login:s},remoteInfo:e?.get(t.repository.id)??null,isFork:!1},mergeableState:Wn(t.mergeStatus),labels:t.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},ss=(s,t)=>({id:t.id,name:t.name,namespace:s,project:t.project.name,projectId:t.project.id,webUrl:t.webUrl,httpsUrl:t.remoteUrl,sshUrl:t.sshUrl,defaultBranch:t.defaultBranch?{name:We(t.defaultBranch)}:null,permissions:null}),Hn=(s,t,e,r)=>{let n=e.fields,o=n["System.AssignedTo"],i=n["System.State"],a=n["System.WorkItemType"],u;return i&&a&&(u=r[a]?.[i]),{id:e.id.toString(),number:e.id.toString(),title:n["System.Title"],commentCount:n["System.CommentCount"],author:{avatarUrl:n["System.CreatedBy"]._links?.avatar?.href??null,email:null,id:n["System.CreatedBy"].id,name:n["System.CreatedBy"].uniqueName??null,username:n["System.CreatedBy"].displayName??null,url:null},closedDate:n["Microsoft.VSTS.Common.ClosedDate"]?new Date(n["Microsoft.VSTS.Common.ClosedDate"]):null,createdDate:new Date(n["System.CreatedDate"]),updatedDate:new Date(n["System.ChangedDate"]),url:e._links.html.href,assignees:o?[{avatarUrl:o._links?.avatar?.href??null,email:null,id:o.id,name:o.uniqueName??null,username:o.displayName??null,url:null}]:[],description:n["System.Description"]??null,state:{name:u?.title||i,color:null},type:n["System.WorkItemType"],repository:null,project:{namespace:s,name:t,resourceId:null,key:null,id:null},upvoteCount:0,labels:e.fields["System.Tags"]?.split(";").map(l=>({color:null,description:null,id:null,name:l.trim()}))??[]}},we=class extends F{constructor(){super(...arguments);this.cachedUserIds=new Map;this.inflightUserIds=new Map}getCurrentUserId(e,r){let n=JSON.stringify([e,r.token??null,r.isPAT??this.config.isPAT??!1,r.baseUrl??null]),o=this.cachedUserIds.get(n);if(o)return Promise.resolve(o);let i=this.inflightUserIds.get(n);if(i)return i;let a=this.fetchCurrentUserId(e,r,n);return this.inflightUserIds.set(n,a),a}async fetchCurrentUserId(e,r,n){try{let o=await this.getCurrentUserForInstance({namespace:e},r);return this.cachedUserIds.set(n,o.data.id),o.data.id}finally{this.inflightUserIds.delete(n)}}getRepoApiUrl(e,r,n,o){return`${A(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(r)}/_apis/git/repositories/${encodeURIComponent(n)}`}async getCurrentUser(e={},r={}){if(r.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let n=`${Ht(this.config,r)}/profile/profiles/me`,o=await this.config.request({url:n,headers:q(this.config,r)});return{data:{id:o.body.id,name:o.body.displayName,username:o.body.displayName,email:o.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(e,r={}){let o=(await this.config.request({url:`${A(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:q(this.config,r)})).body.authorizedUser;if(o.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:o.id,name:o.providerDisplayName,username:o.providerDisplayName,email:o.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=(await this.config.request({url:`${A(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:q(this.config,r)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,r={}){let n=`${Ht(this.config,r)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,r={}){let n=`${A(this.config,r)}/_apis/projectCollections`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,r={}){let n=new URL(`${A(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/projects`);n.searchParams.set("$top",C.toString()),e.cursor&&n.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:n.toString(),headers:q(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({id:a.id,name:a.name,namespace:e.namespace}))}}async getAzureProjectScopeDescriptor(e,r={}){let{namespace:n,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${Vt(this.config,r)}/${encodeURIComponent(n)}/_apis/graph/descriptors/${o}?api-version=6.0`,headers:q(this.config,r)})).body.value}}}async getAzureGraphAccountsForAzureProject(e,r={}){let{namespace:n,projectScopeDescriptor:o,cursor:i}=e,a=new URL(`${Vt(this.config,r)}/${encodeURIComponent(n)}/_apis/graph/users`);o&&a.searchParams.set("scopeDescriptor",o),i&&a.searchParams.set("continuationToken",i);let u=await this.config.request({url:a.toString(),headers:q(this.config,r)}),l=u.headers["x-ms-continuationtoken"];return{pageInfo:{endCursor:l||null,hasNextPage:!!l},data:u.body.value.map(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,r={}){let{azureGraphAccount:n}=e;if(!n.storageKeyURL)throw new Error("Expected 'storageKeyURL' to not be null for 'azureGraphAccount'");let o=await this.config.request({url:n.storageKeyURL,headers:q(this.config,r)});return{data:{avatarUrl:n.avatarUrl,email:n.email,id:o.body.value,name:n.name,username:n.username,url:null}}}async getAccountsFromAzureGraphAccounts(e,r={}){let n=[];for(let o of e.azureGraphAccounts){let i=await this.getAccountFromAzureGraphAccount({azureGraphAccount:o},r);n.push(i.data)}return{data:n}}async getRepo(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${A(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:q(this.config,r)});return{data:ss(e.namespace,n.body)}}async getRepos(e,r={}){let n=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,r);n.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:n,errors:o}}async getReposForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${A(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:q(this.config,r)})).body.value.map(o=>ss(e.namespace,o))}}async getRefs(e,r,n={}){if(!r.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${A(this.config,n)}/${encodeURIComponent(r.repo.namespace)}/${encodeURIComponent(r.repo.project)}/_apis/git/repositories/${encodeURIComponent(r.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",C.toString()),r.cursor&&o.searchParams.set("continuationToken",r.cursor);let i=await this.config.request({url:o.toString(),headers:q(this.config,n)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name:We(u.name),commit:{oid:u.objectId,authoredDate:null,committedDate:null}}))}}async getBranches(e,r={}){return this.getRefs("heads",e,r)}async getTags(e,r={}){return this.getRefs("tags",e,r)}async fetchRemoteInfoByRepoId(e,r,n){let o=new Map;if(!e)return o;let i=new Map;for(let{namespace:a,pullRequests:u}of r)for(let l of u)i.has(l.repository.id)||i.set(l.repository.id,a),l.forkSource&&!i.has(l.forkSource.repository.id)&&i.set(l.forkSource.repository.id,a);return await zt([...i],10,async([a,u])=>{try{let l=await this.config.request({url:`${A(this.config,n)}/${encodeURIComponent(u)}/_apis/git/repositories/${encodeURIComponent(a)}`,headers:q(this.config,n)}),{remoteUrl:d,sshUrl:p}=l.body;d&&p&&o.set(a,{cloneUrlHTTPS:d,cloneUrlSSH:p})}catch{}}),o}async getPullRequestsForRepoBase(e,r={},n=Pe){let{page:o,repo:i,assigneeLogins:a,authorLogin:u,reviewerId:l}=e||{},d=o||1;if(!i.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let p=D(e.pageSize,{fallback:n}),c=l??(a&&a.length?a[0]:void 0),m=`searchCriteria.status=${es(e.states)}`;return c&&(m+=`&searchCriteria.reviewerId=${encodeURIComponent(c)}`),u&&(m+=`&searchCriteria.creatorId=${encodeURIComponent(u)}`),await this.config.request({url:`${A(this.config,r)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${m}&%24top=${p}&%24skip=${(d-1)*p}`,headers:q(this.config,r)})}async getPullRequestsForRepo(e,r={}){let n=D(e.pageSize,{fallback:Pe}),o=e.page||1,i=await this.getPullRequestsForRepoBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:e.repo.namespace,pullRequests:i.body.value}],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i.body.value.map(l=>Ge(e.repo.namespace,l,u)),e.states)}}async getPullRequestsForRepos(e,r={}){if(!e.repos.every(p=>p.project))throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repos:n}=e||{},o=D(e.pageSize,{fallback:Pe}),{successes:i,metadata:a}=await re(n,{run:p=>this.getPullRequestsForRepoBase({repo:p,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o},r,o),failureScope:p=>({providerId:"azure",projectId:p.project,repositoryId:ge(p)}),completeness:p=>p.body.value.length===o?"unknown":"complete",concurrency:Yr}),u=i.map(({scope:p,result:c})=>({namespace:p.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,r),d=u.flatMap(({namespace:p,pullRequests:c})=>c.map(m=>Ge(p,m,l)));return{data:x(d,e.states),metadata:a}}async getPullRequestsForProjectBase(e,r={},n=Pe){let{namespace:o,project:i,page:a,assigneeLogins:u,authorLogin:l,reviewerId:d,repo:p}=e;if(p?.project&&p.project!==i)throw new Error("Could not fetch pull requests, project mismatch");let c=a||1,m=D(e.pageSize,{fallback:n}),g=d??(u&&u.length?u[0]:void 0),h=new URL(`${A(this.config,r)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",es(e.states)),h.searchParams.set("$top",m.toString()),h.searchParams.set("$skip",((c-1)*m).toString()),p?.id&&p?.project===i&&h.searchParams.set("searchCriteria.repositoryId",p.id),g&&h.searchParams.set("searchCriteria.reviewerId",g),l&&h.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:h.toString(),headers:q(this.config,r)})}async getPullRequestsForProject(e,r={}){let n=D(e.pageSize,{fallback:Pe}),o=e.page||1,i=await this.getPullRequestsForProjectBase(e,r,n),a=i.body.value.length===n,u=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,i?[{namespace:e.namespace,pullRequests:i.body.value}]:[],r);return{pageInfo:{hasNextPage:a,nextPage:a?o+1:null,currentPage:o},data:x(i?.body.value.map(l=>Ge(e.namespace,l,u))||[],e.states)}}async getPullRequestsForProjects(e,r={}){let{projects:n}=e||{};if(e.repo&&!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=D(e.pageSize,{fallback:Pe}),{successes:i,metadata:a}=await re(n,{run:p=>e.repo&&e.repo.project!==p.project?Promise.resolve(void 0):this.getPullRequestsForProjectBase({...p,assigneeLogins:e.assigneeLogins,authorLogin:e.authorLogin,reviewerId:e.reviewerId,states:e.states,pageSize:o,repo:e.repo},r,o),failureScope:p=>({providerId:"azure",projectId:p.project,repositoryId:ge(e.repo)}),completeness:p=>p.body.value.length===o?"unknown":"complete",concurrency:Yr}),u=i.map(({scope:p,result:c})=>({namespace:p.namespace,pullRequests:c.body.value})),l=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,u,r),d=u.flatMap(({namespace:p,pullRequests:c})=>c.map(m=>Ge(p,m,l)));return{data:x(d,e.states),metadata:a}}async getAzurePullRequestLastMergeStatus(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{repo:{namespace:n,project:o,name:i},pullRequestId:a}=e,u=await this.config.request({url:`${A(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...q(this.config,r)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,r,n){return await this.config.request({method:"PATCH",url:`${A(this.config,n)}/${encodeURIComponent(e.repository.owner.login)}/${encodeURIComponent(e.repository.project)}/_apis/git/repositories/${e.repository.name}/pullrequests/${e.id}?api-version=6.0`,body:r,headers:{...q(this.config,n),"Content-Type":"application/json"}})}async closePullRequest(e,r={}){let{pullRequest:n}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(n,JSON.stringify(o),r)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,r={}){let{pullRequest:n,mergeStrategy:o}=e,i;switch(o){case"MERGE_COMMIT":{i="noFastForward";break}case"REBASE":{i="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{i="rebaseMerge";break}case"SQUASH":{i="squash";break}}let a={completionOptions:{mergeStrategy:i},lastMergeSourceCommit:{commitId:n.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(n,JSON.stringify(a),r)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i={name:o.name};if(!(await this.config.request({method:"POST",url:`${A(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${A(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...q(this.config,r)}})}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=n.labels;if(!i)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of o)i.find(u=>u.id===a.id)||await this.addPullRequestLabel({pullRequest:n,label:a},r);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:n,label:a},r)}async setPullRequestAsDraft(e,r={}){let{pullRequest:n,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(n,JSON.stringify(i),r)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${A(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${A(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,headers:{...q(this.config,r),Accept:"application/json"}})}async setPullRequestReviewers(e,r={}){let{pullRequest:n,reviewers:o}=e;for(let i of o)n.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:n,reviewer:i,isRequired:!0},r);for(let i of n.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:n,reviewer:i},r)}async getIssuesForAzureProject(e,r={}){let{page:n,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},d=n||1,p=Math.min(D(e.pageSize,{fallback:Bn}),jn),c=["[System.TeamProject] = @project",...Fn(e.states)];i&&c.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&c.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&c.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(L=>c.push(`[System.Tags] Contains '${L}'`));let m=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${c.join(" AND ")} order by [System.CreatedDate] desc`,g=await this.config.request({url:`${A(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:m}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}}),h=g.body.workItems.slice((d-1)*p,p*d).map(L=>L.id),y=g.body.workItems.length,f=Math.ceil(y/p),P=y>p*d;if(h.length===0)return{pageInfo:{hasNextPage:!1,nextPage:null,currentPage:d,totalCount:y,totalPages:f},data:[]};let v=await this.config.request({url:`${A(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:h,$expand:"Links"}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?d+1:null,currentPage:d,totalCount:y,totalPages:f},data:v.body.value.map(L=>Hn(e.namespace,e.project,L,l||{}))}}async getPermissionsForRepos(e,r={}){let{namespace:n,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=p=>{let c="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",m=`repoV2/${p.projectId}/${p.id}`;return Object.keys(i).map(g=>({securityNamespaceId:c,token:m,permissions:g}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${A(this.config,r)}/${encodeURIComponent(n)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.evaluations.reduce((p,c)=>{let[,m,g]=c.token.split("/"),h=`${m}/${g}`,y=i[c.permissions];for(let f of y)p[h]===void 0&&(p[h]={canCreateWebhook:!0,canPush:!0,isAdmin:!0}),c.value===!1&&(p[h][f]=!1);return p},{})}}async decorateReposWithPermissions(e,r={}){let{namespace:n,repos:o}=e,i=await this.getPermissionsForRepos({namespace:n,repos:o},r);return{data:o.map(a=>({...a,permissions:i.data[`${a.projectId}/${a.id}`]}))}}async updateIssue(e,r,n={}){return await this.config.request({method:"PATCH",url:`${A(this.config,n)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(r),headers:{...q(this.config,n),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,r={}){let{issue:n,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,r={}){let{issue:n,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(n,a,r)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${A(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...q(this.config,r)}})).body.value}}async getLabelsForProject(e,r={}){let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${A(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...q(this.config,r)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:n.namespace,pullRequests:[i.body]}],r);return{data:Ge(n.namespace,i.body,a)}}async getPullRequestDescription(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');try{return{data:{description:(await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(e,r={}){let{repo:n,number:o,description:i}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:{description:(await this.config.request({method:"PATCH",url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:{...q(this.config,r),"Content-Type":"application/json"},body:JSON.stringify({description:i})})).body?.description??i}}}async getMergeBase(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/commits/${encodeURIComponent(e.base)}/mergebases?otherCommitId=${encodeURIComponent(e.head)}&api-version=7.1`,headers:q(this.config,r)});if(!n.body.value?.length)throw new Error("No merge base found between the specified commits.");return{data:n.body.value[0].commitId}}async getFileContents(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=await this.config.request({url:`${this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r)}/items?path=${encodeURIComponent(e.path)}&versionDescriptor[version]=${encodeURIComponent(e.ref)}&versionDescriptor[versionType]=commit&api-version=7.1`,headers:{...q(this.config,r),Accept:"application/octet-stream"}});return{data:new Blob([n.body])}}async getPullRequestDiff(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i={...o,Accept:"application/octet-stream"},[a,u]=await Promise.all([this.config.request({url:`${n}/pullrequests/${e.pullRequestId}?api-version=7.1`,headers:o}),this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations?api-version=7.1`,headers:o})]),l=a.body.lastMergeTargetCommit.commitId,d=a.body.lastMergeSourceCommit.commitId,p=u.body.value;if(p.length===0)return"";let c=p[p.length-1],m=1e3,g=[],h=0;for(;;){let S=(await this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations/${c.id}/changes?api-version=7.1&$top=${m}&$skip=${h}`,headers:o})).body.changeEntries??[];if(S.length===0||(g.push(...S),S.length<m))break;h+=S.length}if(g.length===0)return"";let y=5,f=[],P=new TextDecoder,v=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",L=async(w,S)=>{try{let de=await this.config.request({url:`${n}/items?path=${encodeURIComponent(w)}&versionDescriptor[version]=${encodeURIComponent(S)}&versionDescriptor[versionType]=commit&includeContent=true&api-version=7.1`,headers:i});return v(de.body)}catch{return""}},$=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let S=w.toLowerCase().split(",").map(de=>de.trim());return{add:S.includes("add"),rename:S.includes("rename"),delete:S.includes("delete")}};for(let w=0;w<g.length;w+=y){let S=g.slice(w,w+y),de=await Promise.all(S.map(async Ie=>{let{add:be,rename:Bt,delete:ce}=$(Ie.changeType),Le=Ie.originalPath??Ie.item.originalPath,T=Ie.item.path,Fe=ce?T??Le??"":T??"",zr=Bt||ce?Le??Fe:Fe,[bn,yn]=await Promise.all([be?Promise.resolve(""):L(zr,l),ce?Promise.resolve(""):L(Fe,d)]),Pn=be?"/dev/null":`a${zr}`,wn=ce?"/dev/null":`b${Fe}`;return(0,ns.createTwoFilesPatch)(Pn,wn,bn,yn)}));f.push(...de)}return f.join(`
|
|
2
|
+
`)}getPullRequestWriteHeaders(e){return{...q(this.config,e),"Content-Type":"application/json"}}setReviewerVote(e,r,n,o,i){return this.config.request({method:"PUT",url:`${e}/pullRequests/${r}/reviewers/${encodeURIComponent(n)}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(i),body:JSON.stringify({vote:o})})}postPullRequestThread(e,r,n,o){return this.config.request({method:"POST",url:`${e}/pullRequests/${r}/threads?api-version=7.1`,headers:this.getPullRequestWriteHeaders(o),body:JSON.stringify({comments:[{parentCommentId:0,content:n,commentType:1}],status:1})})}async getCommentsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.repo.namespace,e.repo.project,e.repo.name,r),o=q(this.config,r),i=await this.config.request({url:`${n}/pullRequests/${e.pullRequestNumber}/threads?api-version=7.1`,headers:o}),a=[];for(let u of i.body.value)if(!(u.isDeleted||u.threadContext))for(let l of u.comments)l.commentType==="system"||l.isDeleted||a.push({id:Jt(e.repo.namespace,e.repo.project,e.repo.name,e.pullRequestNumber,u.id,l.id),author:l.author?fe(l.author):null,body:l.content||"",createdAt:l.publishedDate?new Date(l.publishedDate):null,url:""});return{data:a,pageInfo:{hasNextPage:!1,endCursor:null}}}async addCommentToPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async addInlineCommentToPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r),o=this.getPullRequestWriteHeaders(r);if(e.threadId){let d=Kt(e.threadId),p=e.pullRequest.repository.owner.login,c=e.pullRequest.repository.project,m=e.pullRequest.repository.name,g=String(e.pullRequest.id);if(d.namespace!==p||d.project!==c||d.repoName!==m||d.prId!==g)throw new Error(`Azure thread ID context mismatch: threadId targets ${d.namespace}/${d.project}/${d.repoName} pull request ${d.prId}, but input.pullRequest targets ${p}/${c}/${m} pull request ${g}.`);let y=(await this.config.request({url:`${n}/pullRequests/${e.pullRequest.id}/threads/${d.threadId}?api-version=7.1`,headers:q(this.config,r)})).body.comments?.find(P=>P.parentCommentId===0);if(!y)throw new Error(`Could not determine root comment for Azure DevOps thread ${d.threadId}.`);let f=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 Jt(p,c,m,Number(g),Number(d.threadId),f.body.id)}let i=e.path.startsWith("/")?e.path:`/${e.path}`,a={line:e.line,offset:1},u={filePath:i};e.side==="LEFT"?(u.leftFileStart=a,u.leftFileEnd=a):(u.rightFileStart=a,u.rightFileEnd=a);let l=await this.config.request({method:"POST",url:`${n}/pullRequests/${e.pullRequest.id}/threads?api-version=7.1`,headers:o,body:JSON.stringify({comments:[{parentCommentId:0,content:e.comment,commentType:1}],status:1,threadContext:u})});return rs(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,Number(e.pullRequest.id),l.body.id)}async editComment(e,r={}){let n=ts(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({content:e.body})})}async editInlineComment(e,r={}){return this.editComment(e,r)}async deleteComment(e,r={}){let n=ts(e.commentId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"DELETE",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}/comments/${n.commentId}?api-version=7.1`,headers:q(this.config,r)})}async deleteInlineComment(e,r={}){return this.deleteComment(e,r)}async resolveReviewThread(e,r={}){let n=Kt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:2})})}async unresolveReviewThread(e,r={}){let n=Kt(e.threadId),o=this.getRepoApiUrl(n.namespace,n.project,n.repoName,r);await this.config.request({method:"PATCH",url:`${o}/pullRequests/${n.prId}/threads/${n.threadId}?api-version=7.1`,headers:this.getPullRequestWriteHeaders(r),body:JSON.stringify({status:1})})}async approvePullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await Promise.all([this.setReviewerVote(o,e.pullRequest.id,i,10,r),e.comment?this.postPullRequestThread(o,e.pullRequest.id,e.comment,r):null])}async requestPullRequestChanges(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=e.pullRequest.repository.owner.login,o=this.getRepoApiUrl(n,e.pullRequest.repository.project,e.pullRequest.repository.name,r),i=await this.getCurrentUserId(n,r);await this.postPullRequestThread(o,e.pullRequest.id,e.comment,r),await this.setReviewerVote(o,e.pullRequest.id,i,-5,r)}async commentOnPullRequest(e,r={}){if(!e.pullRequest.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let n=this.getRepoApiUrl(e.pullRequest.repository.owner.login,e.pullRequest.repository.project,e.pullRequest.repository.name,r);await this.postPullRequestThread(n,e.pullRequest.id,e.comment,r)}async getReviewsForPullRequest(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o,name:i}=e.repo,{pullRequestId:a}=e,u=this.getRepoApiUrl(n,o,i,r),l=q(this.config,r),[d,p]=await Promise.all([this.config.request({url:`${u}/pullRequests/${a}/reviewers?api-version=7.1`,headers:l}),this.config.request({url:`${u}/pullRequests/${a}/threads?api-version=7.1`,headers:l})]),c=(f,P)=>Jt(n,o,i,a,f,P),m=f=>rs(n,o,i,a,f),g=new Map;for(let f of p.body.value){if(f.isDeleted)continue;let P=f.comments.filter(T=>!T.isDeleted&&T.commentType!=="system"),v=P.find(T=>T.parentCommentId===0)??P[0];if(!v)continue;let L=v.author?.id;if(!L)continue;let $=P.filter(T=>T.id!==v.id),w=f.threadContext,S=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,de=S?.end?.line??S?.start.line??null,Ie=S?.start&&S.end&&S.start.line!==S.end.line?S.start.line:null,be=w?.filePath??"",Bt=be.startsWith("/")?be.slice(1):be,ce={id:c(f.id,v.id),author:v.author?fe(v.author):null,body:v.content??"",createdAt:v.publishedDate?new Date(v.publishedDate):null,url:"",diffLines:[],filename:Bt,replies:$.map(T=>({id:c(f.id,T.id),author:T.author?fe(T.author):null,body:T.content??"",createdAt:T.publishedDate?new Date(T.publishedDate):null,url:""})),isOutdated:!1,isResolved:zn.has(Qn(f.status)),line:de,startLine:Ie,side:S?.side??null,threadId:m(f.id)},Le=g.get(L);Le?Le.push(ce):g.set(L,[ce])}let h=[],y=new Set;for(let f of d.body.value){if(f.hasDeclined)continue;let P=f.vote??0,v=g.get(f.id);P===0&&!v?.length||(h.push({id:f.id,author:fe(f),body:"",createdAt:null,url:"",reviewComments:v??[]}),y.add(f.id))}for(let[f,P]of g){if(y.has(f)||!P.length)continue;let v=P[0].author;v&&h.push({id:f,author:v,body:"",createdAt:null,url:"",reviewComments:P})}return{data:h}}};var G=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT);var O="https://api.bitbucket.org/2.0",Vn={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},Jn={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},He=50,Kn=5,os=s=>{let t=!s||s.length===0?["OPEN"]:Array.from(new Set(s.flatMap(r=>Jn[r]))),e=t.map(r=>`state="${r}"`).join(" OR ");return t.length>1?`(${e})`:e},Xn=s=>s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),is=s=>{let t=s?.trim();if(!t)return null;let e=Xn(t);return`(title ~ "${e}" OR description ~ "${e}")`},as=s=>{let t=!!s.next,e=typeof s.size=="number"?s.size:null,r=typeof s.pagelen=="number"&&s.pagelen>0?s.pagelen:null;return{hasNextPage:t,nextPage:t?s.page+1:null,currentPage:typeof s.page=="number"?s.page:null,totalCount:e,totalPages:e!==null&&r?Math.ceil(e/r):null}},Ve={owner:4,admin:3,contributor:2,member:1},Je=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}),us=s=>{let t=s.links.clone,e=t?.find(n=>n.name==="ssh"),r=t?.find(n=>n.name==="https");return e&&r?{cloneUrlHTTPS:r.href,cloneUrlSSH:e.href}:null},Xt=s=>({id:s.uuid,namespace:s.workspace.slug,name:s.slug,webUrl:s.links.html.href,httpsUrl:s.links.clone.find(t=>t.name==="https")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:{name:s.mainbranch.name},permissions:null}),Zt=s=>{let t=s.id,e=s.participants?.map(r=>{let n="REVIEW_REQUESTED";return r.approved?n="APPROVED":r.state==="changes_requested"?n="CHANGES_REQUESTED":r.participated_on!==null&&(n="COMMENTED"),{reviewer:Je(r.user),state:n}})??[];return{id:t.toString(),title:s.title,description:s.description,number:t,state:Vn[s.state],isDraft:!1,commentCount:s.comment_count,upvoteCount:null,author:Je(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:us(s.destination.repository)},headCommit:{buildStatuses:null},baseRef:{name:s.destination.branch.name,oid:s.destination.commit.hash},headRef:{name:s.source.branch.name,oid:s.source.commit.hash},url:s.links.html.href,assignees:null,reviews:e,reviewDecision:J(e),additions:null,deletions:null,fileCount:null,commitCount:null,isCrossRepository:s.source.repository.uuid!==s.destination.repository.uuid,headRepository:{id:s.source.repository.uuid,name:s.source.repository.name,owner:{login:s.source.repository.full_name.split("/")[0]},remoteInfo:us(s.source.repository)},mergeableState:"MERGEABLE",permissions:null}},Zn=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}}},Yn=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}}},qe=class extends M{async refreshToken(t){return{data:(await this.config.request({url:"https://bitbucket.org/site/oauth2/access_token",method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:`Basic ${t.base64ClientIDColonClientSecret}`},body:`grant_type=refresh_token&refresh_token=${t.refreshToken}`})).body}}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${O}/user`,headers:G(this.config,e)});return{data:Je(r.body)}}async getUserForCommit(t,e={}){let n=(await this.config.request({url:`${O}/repositories/${t.repo.namespace}/${t.repo.name}/commit/${t.oid}`,headers:G(this.config,e)})).body.author,o=n.raw.match(/([^<]+)<(.+)>/);return{data:{name:o?o[1].trim():null,email:o?o[2]:null,avatarUrl:n.user?.links.avatar.href||null}}}async getRepo(t,e={}){let r=await this.config.request({url:`${O}/repositories/${t.namespace}/${t.name}`,headers:G(this.config,e)});return{data:Xt(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForWorkspace(t,e={}){let r=new URL(`${O}/repositories/${encodeURIComponent(t.workspace)}`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",C.toString()),t.minimumRole&&r.searchParams.set("role",t.minimumRole);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Xt)}}async getAllReposForWorkspace(t,e={}){let r=[],n=1;for(;n!==null;){let o=await this.getReposForWorkspace({workspace:t.workspace,minimumRole:t.minimumRole,page:n},e);r.push(...o.data),n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}return r}async getAllReposForWorkspaceWithPermissions(t,e={}){let r=new Map,n=[],o=Ve[t.minimumRole||"member"];o<=Ve.admin&&n.push("admin"),o<=Ve.contributor&&n.push("contributor"),o<=Ve.member&&n.push("member");let i=[];for(let a of n){i=await this.getAllReposForWorkspace({workspace:t.workspace,minimumRole:a},e);for(let u of i)r.has(u.id)||r.set(u.id,a)}return{data:i.map(a=>{let u=r.get(a.id)||"member";return{...a,permissions:Yn(u)}})}}async getReposForCurrentUser(t,e={}){let r=new URL(`${O}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",C.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(Xt)}}async getBranches(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",C.toString());let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",C.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(t={},e={}){let r=new URL(`${O}/user/workspaces`);r.searchParams.set("page",t?.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t?.administrator!==void 0&&r.searchParams.set("administrator",t.administrator.toString());let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(t,e={}){let r=new URL(`${O}/user/permissions/workspaces`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",D(t.pageSize,{fallback:He,max:He}).toString());let n=[os(t.states)];t.repos&&t.repos.length>0&&n.push(`(${t.repos.map(a=>`source.repository.full_name = "${a.namespace}/${a.name}"`).join(" OR ")})`);let o=is(t.query);o&&n.push(o),r.searchParams.set("q",n.join(" AND "));let i=await this.config.request({url:r.toString(),headers:G(this.config,e)});return{pageInfo:as(i.body),data:i.body.values.map(Zt)}}async getPullRequestsForReviewerAndWorkspace(t,e={}){let r=t.repos?.length?t.repos:await this.getAllReposForWorkspace({workspace:t.workspaceSlug},e);return this.getPullRequestsForRepos({repos:r,reviewerId:t.reviewerId,states:t.states,query:t.query,pageSize:t.pageSize},e)}async getPullRequestsForRepoBase(t,e={}){let r=new URL(`${O}/repositories/${encodeURI(t.repo.namespace)}/${encodeURI(t.repo.name)}/pullrequests`),n=[];t.reviewerId&&n.push(`reviewers.uuid="${t.reviewerId}"`),t.authorLogin&&n.push(`author.uuid="${t.authorLogin}"`);let o=os(t.states);n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`);let i=is(t.query);return i&&(o+=` AND ${i}`),r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",D(t.pageSize,{fallback:He,max:He}).toString()),r.searchParams.set("q",o),await this.config.request({url:r.toString(),headers:G(this.config,e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);return n.body.values.forEach(o=>{r.push(Zt(o))}),{pageInfo:as(n.body),data:r}}async getPullRequestsForRepos(t,e={}){let{successes:r,metadata:n}=await re(t.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,authorLogin:t.authorLogin,reviewerId:t.reviewerId,useOrFilter:t.useOrFilter,states:t.states,query:t.query,pageSize:t.pageSize},e),failureScope:i=>({providerId:"bitbucket",repositoryId:ge(i)}),completeness:i=>i.body.next?"partial":"complete",concurrency:Kn}),o=[];return r.forEach(({result:i})=>{i.body.values.forEach(a=>{o.push(Zt(a))})}),{data:o,metadata:n}}async getAccountsForWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${encodeURI(t.workspace)}/members`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>Je(i.user))}}async getReposPermissionsForCurrentUser(t,e={}){let r=new URL(`${O}/user/permissions/repositories`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","100");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.reduce((i,a)=>({...i,[a.repository.uuid]:Zn(a.permission)}),{})}}async decorateReposWithPermissions(t,e={}){let r={},n=1;do{let o=await this.getReposPermissionsForCurrentUser({page:n},e);r={...o.data,...r},n=o.pageInfo.hasNextPage?o.pageInfo.nextPage:null}while(n!==null);return{data:t.repos.map(o=>({...o,permissions:r[o.id]??{canCreateWebhook:!1,canPush:!1,isAdmin:!1}}))}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/decline`,headers:G(this.config,e)})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategy:n}=t,o;switch(n){case"MERGE_COMMIT":{o="merge_commit";break}case"FAST_FORWARD":{o="fast_forward";break}case"SQUASH":{o="squash";break}}let i={merge_strategy:o,type:"pullrequest"};if(!(await this.config.request({method:"POST",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}/merge`,body:JSON.stringify(i),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t,o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket reviewer requires "username" for this function.');return{username:a.username}})};if(!(await this.config.request({method:"PUT",url:`${O}/repositories/${r.repository.owner.login}/${r.repository.name}/pullrequests/${r.id}`,body:JSON.stringify(o),headers:{...G(this.config,e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}};var Ke={};H(Ke,{normalizePermissions:()=>Yt,restApiPullRequestToCommonPullRequest:()=>eo});var eo=s=>Te(s),Yt=s=>s?s.find(t=>t.permission==="USER_ADMIN"||t.permission==="PROJECT_ADMIN"||t.permission==="ADMIN"||t.permission==="SYS_ADMIN"||t.permission==="REPO_ADMIN")?{canCreateWebhook:!0,canPush:!0,isAdmin:!0}:s.find(t=>t.permission==="REPO_WRITE"||t.permission==="REPO_CREATE"||t.permission==="PROJECT_CREATE"||t.permission==="PROJECT_WRITE")?{canCreateWebhook:!1,canPush:!0,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}:{canCreateWebhook:!1,canPush:!1,isAdmin:!1};var Oe=s=>{let t=s.links.self[0].href;return{name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrl??(t&&`${t}/avatar.png`),id:s.id.toString(),username:s.name,url:t}},Te=s=>{let t={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED"},e={UNAPPROVED:"REVIEW_REQUESTED",NEEDS_WORK:"CHANGES_REQUESTED",APPROVED:"APPROVED"},r=s.reviewers.map(u=>({reviewer:Oe(u.user),state:e[u.status]})),n=s.toRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,o=s.toRef.repository.links.clone.find(u=>u.name==="https")?.href??null;o||(o=s.toRef.repository.links.clone.find(u=>u.name==="http")?.href??null);let i=s.fromRef.repository.links.clone.find(u=>u.name==="ssh")?.href??null,a=s.fromRef.repository.links.clone.find(u=>u.name==="https")?.href??null;return a||(a=s.fromRef.repository.links.clone.find(u=>u.name==="http")?.href??null),{id:s.id.toString(),number:s.id,title:s.title,description:s.description,url:s.links.self[0].href,state:t[s.state],isDraft:!1,createdDate:new Date(s.createdDate),updatedDate:new Date(s.updatedDate),closedDate:s.closedDate?new Date(s.closedDate):null,mergedDate:s.state=="MERGED"&&s.closedDate?new Date(s.closedDate):null,baseRef:{name:s.toRef.displayId,oid:s.toRef.latestCommit},headRef:{name:s.fromRef.displayId,oid:s.fromRef.latestCommit},commentCount:s.properties.commentCount,upvoteCount:null,commitCount:null,fileCount:null,additions:null,deletions:null,author:Oe(s.author.user),assignees:null,reviews:r,reviewDecision:J(r),isCrossRepository:s.fromRef.repository.id!==s.toRef.repository.id,repository:{id:s.toRef.repository.id.toString(),name:s.toRef.repository.name,owner:{login:s.toRef.repository.project.key},remoteInfo:o&&n?{cloneUrlHTTPS:o,cloneUrlSSH:n}:null},headRepository:{id:s.fromRef.repository.id.toString(),name:s.fromRef.repository.name,owner:{login:s.fromRef.repository.project.key},remoteInfo:a&&i?{cloneUrlHTTPS:a,cloneUrlSSH:i}:null},headCommit:null,mergeableState:"MERGEABLE",permissions:null,version:s.version}},ls=s=>({id:s.id.toString(),namespace:s.project.key,name:s.slug,webUrl:s.links.self[0]?.href??null,httpsUrl:s.links.clone.find(t=>t.name==="https"||t.name==="http")?.href??null,sshUrl:s.links.clone.find(t=>t.name==="ssh")?.href??null,defaultBranch:null,permissions:null}),ps=50,to=5,ro={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},ds=s=>{if(!s||s.length===0)return"OPEN";let t=Array.from(new Set(s.map(e=>ro[e])));return t.length===1?t[0]:"ALL"},cs=(s,t)=>typeof s!="number"||t<=0?null:Math.floor(s/t)+1,ms=(s,t)=>{if(typeof s!="number"||!Number.isFinite(s))return 0;let e=Math.floor(s);return e<=1?0:(e-1)*t},gs=s=>{let t=cs(s.start,s.limit);return{hasNextPage:!s.isLastPage,nextPage:s.isLastPage?null:cs(s.nextPageStart,s.limit),currentPage:t}},ve=class extends F{getBaseUrl(t){let e=t.baseUrl||this.config.baseUrl;if(!e)throw new Error('Bitbucket Server requires "baseUrl"');return e}getRequestHeaders(t){return R(t.token||this.config.token)}async getCurrentUser(t={},e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/users?limit=2`,headers:this.getRequestHeaders(e)}),{headers:{"x-auserid":n,"x-ausername":o}}=r,i=n?parseInt(n,10):null,a=decodeURIComponent(o),l=(await this.config.request({url:`${this.getBaseUrl(e)}/users?filter=${o}&avatarSize=64`,headers:this.getRequestHeaders(e)})).body.values.find(({emailAddress:d,id:p,name:c,slug:m})=>i?i===p:a===c||a===d||a===m);if(!l)throw new Error("Could not find current Bitbucket Server user");return{data:Oe(l)}}async getUserForCommit(t,e){let{repo:r,oid:n}=t,o=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${r.namespace}/repos/${r.name}/commits/${n}`,headers:this.getRequestHeaders(e)});if(!o.body.author)throw new Error("Could not find user for commit");return{data:Oe(o.body.author)}}async getRepo(t,e={}){let r=await this.config.request({url:`${this.getBaseUrl(e)}/projects/${t.namespace}/repos/${t.name}`,headers:this.getRequestHeaders(e)});return{data:ls(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForCurrentUser(t,e={}){let r=t.page??0,n=await this.config.request({url:`${this.getBaseUrl(e)}/repos?start=${r}`,headers:this.getRequestHeaders(e)});return{pageInfo:{hasNextPage:!n.body.isLastPage,nextPage:n.body.nextPageStart},data:n.body.values.map(ls)}}async getRepoPermissionsForUsername(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${t.repo.namespace}/repos/${t.repo.name}/permissions/search?filterText=${t.username}`);try{let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{data:Yt(n.body.values)}}catch(n){if(n.response?.status===401)return{data:{canCreateWebhook:!1,canPush:!1,isAdmin:!1}};throw n}}async decorateReposWithPermissions(t,e={}){return await Promise.all(t.repos.map(async n=>{let o=await this.getRepoPermissionsForUsername({repo:n,username:t.username},e);return{...n,permissions:o.data}}))}async getPullRequestsForRepoBase(t,e={}){let r=D(t.pageSize,{fallback:ps}),n=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.repo.namespace)}/repos/${encodeURI(t.repo.name)}/pull-requests`);return n.searchParams.set("state",ds(t.states)),n.searchParams.set("start",ms(t.page,r).toString()),n.searchParams.set("limit",r.toString()),t.reviewerLogin&&(n.searchParams.set("role.1","REVIEWER"),n.searchParams.set("username.1",t.reviewerLogin)),await this.config.request({url:n.toString(),headers:this.getRequestHeaders(e)})}async getPullRequestsForRepo(t,e={}){let r=[],n=await this.getPullRequestsForRepoBase(t,e);return n.body.values.forEach(o=>{if(t.authorLogin&&o.author.user.name!==t.authorLogin)return null;r.push(Te(o))}),{pageInfo:gs(n.body),data:x(r,t.states)}}async getPullRequestsForRepos(t,e={}){let{successes:r,metadata:n}=await re(t.repos,{run:i=>this.getPullRequestsForRepoBase({repo:i,reviewerLogin:t.reviewerLogin,states:t.states,pageSize:t.pageSize},e),failureScope:i=>({providerId:"bitbucketServer",repositoryId:ge(i)}),completeness:i=>i.body.isLastPage?"complete":"partial",concurrency:to}),o=[];return r.forEach(({result:i})=>{i.body.values.forEach(a=>{t.authorLogin&&a.author.user.name!==t.authorLogin||o.push(Te(a))})}),{data:x(o,t.states),metadata:n}}async getPullRequestsForCurrentUser(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/dashboard/pull-requests`);r.searchParams.set("state",ds(t.states));let n=D(t.pageSize,{fallback:ps});r.searchParams.set("start",ms(t.page,n).toString()),r.searchParams.set("limit",n.toString()),t.reviewerLogin&&(r.searchParams.set("role.1","REVIEWER"),r.searchParams.set("username.1",t.reviewerLogin));let o=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)});return{pageInfo:gs(o.body),data:x(o.body.values.map(Te),t.states)}}async closePullRequest(t,e={}){let{pullRequest:r}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/decline`,body:JSON.stringify({version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not close pull request")}async mergePullRequest(t,e={}){let{pullRequest:r,mergeStrategyId:n}=t;if(t.mergeStrategy)throw new Error('Bitbucket Server uses "mergeStrategyId" instead of "mergeStrategy".');if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');if(!(await this.config.request({method:"POST",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}/merge`,body:JSON.stringify({strategyId:n,version:r.version}),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not merge pull request")}async getMergeStrategies(t={}){let e=await this.config.request({url:`${this.getBaseUrl(t)}/admin/pull-requests/git`,headers:{...this.getRequestHeaders(t),"Content-Type":"application/json"}});return{data:{defaultStrategy:e.body.mergeConfig.defaultStrategy,strategies:e.body.mergeConfig.strategies}}}async setPullRequestReviewers(t,e={}){let{pullRequest:r,reviewers:n}=t;if(r.version===void 0)throw new Error('Bitbucket Server requires "version" for this function.');let o={reviewers:n.map(a=>{if(a.username)throw new Error('Bitbucket Server reviewer requires "username" for this function.');return{user:{name:a.username}}}),version:r.version};if(!(await this.config.request({method:"PUT",url:`${this.getBaseUrl(e)}/projects/${r.repository.owner.login}/repos/${r.repository.name}/pull-requests/${r.id}`,body:JSON.stringify(o),headers:{...this.getRequestHeaders(e),"Content-Type":"application/json"}})).body.title)throw new Error("Could not set pull request reviewers")}async getAccountsForProject(t,e={}){let r=new URL(`${this.getBaseUrl(e)}/projects/${encodeURI(t.project)}/permissions/users`);r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit","50");let n=await this.config.request({url:r.toString(),headers:this.getRequestHeaders(e)}),o=n.body.values.length!==0;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.start+n.body.values.length:null},data:n.body.values.map(i=>Oe(i.user))}}};var Us=require("js-base64");var I=class extends Error{constructor(e,r){let n=r?.map(i=>`'${i.message}'`).join(", "),o=n?`${e}: ${n}`:e;super(o);this.graphQLErrors=r??[]}};var so={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]},hs=100,fs=100,_e={__typename:"User",id:"U_kgDNJ5k",databaseId:10137,name:"Deleted user",login:"ghost",email:"",avatarUrl:"https://avatars.githubusercontent.com/u/10137?v=4",url:"https://github.com/ghost"},k=s=>!!s,K=(s,t)=>{let e=so[t];for(let r=0;r<3;r++){if(s[r]>e[r])return!0;if(s[r]<e[r])return!1}return!0},Ze="https://api.github.com",no=`${Ze}/graphql`,Ye=`
|
|
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
|
+
`,oo=`
|
|
11
11
|
... on CheckRun {
|
|
12
12
|
completedAt
|
|
13
13
|
conclusion
|
|
@@ -16,21 +16,21 @@ url
|
|
|
16
16
|
permalink
|
|
17
17
|
startedAt
|
|
18
18
|
}
|
|
19
|
-
`,
|
|
19
|
+
`,Xe=/\/api\/v\d+$/,et=`
|
|
20
20
|
color
|
|
21
21
|
description
|
|
22
22
|
id
|
|
23
23
|
name
|
|
24
|
-
`,
|
|
24
|
+
`,Rs=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.")},io=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Rs(e),Xe.test(e)&&(e=e.replace(Xe,"")),`${e}/api/graphql`):no},X=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Rs(e),Xe.test(e)&&(e=e.replace(Xe,"")),`${e}/api/v3`):Ze},b=(s,t,e)=>{let r=R(e.token||s.token);return r["X-Github-Next-Global-ID"]="1",r["Content-Type"]="application/json",r.Accept="application/vnd.github.merge-info-preview+json",s.request({url:io(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},ao={user:!0,"user:email":!0,"read:user":!0},se=s=>s.some(t=>ao[t]),Q=(s=!1,t=!1,e)=>`
|
|
25
25
|
__typename
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
${
|
|
29
|
-
${
|
|
30
|
-
${t?
|
|
31
|
-
${
|
|
32
|
-
${
|
|
33
|
-
`,
|
|
26
|
+
${ue(e,["graphQLId"],"id")}
|
|
27
|
+
${ue(e,["id"],"databaseId")}
|
|
28
|
+
${ue(e,["name"],"name")}
|
|
29
|
+
${ue(e,["name","username"],"login")}
|
|
30
|
+
${t?ue(e,["email"],"email"):""}
|
|
31
|
+
${ue(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
|
|
32
|
+
${ue(e,["url"],"url")}
|
|
33
|
+
`,uo=(s=!1)=>`
|
|
34
34
|
latestReviews(first: 100) {
|
|
35
35
|
nodes {
|
|
36
36
|
author {
|
|
@@ -38,26 +38,26 @@ latestReviews(first: 100) {
|
|
|
38
38
|
${Q(!1,s)}
|
|
39
39
|
}
|
|
40
40
|
... on EnterpriseUserAccount {
|
|
41
|
-
${
|
|
41
|
+
${er(!1)}
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
44
|
state
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
|
-
`,
|
|
47
|
+
`,Is=(s=!1)=>`
|
|
48
48
|
__typename
|
|
49
49
|
id
|
|
50
50
|
databaseId
|
|
51
51
|
login
|
|
52
52
|
avatarUrl${s?"(size: $avatarSize)":""}
|
|
53
53
|
url
|
|
54
|
-
`,
|
|
54
|
+
`,er=(s=!1)=>`
|
|
55
55
|
__typename
|
|
56
56
|
id
|
|
57
57
|
login
|
|
58
58
|
avatarUrl${s?"(size: $avatarSize)":""}
|
|
59
59
|
url
|
|
60
|
-
`,
|
|
60
|
+
`,tt=(s,t=!1,e)=>`
|
|
61
61
|
id
|
|
62
62
|
${!e||K(e,"PR_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
63
63
|
number
|
|
@@ -69,10 +69,10 @@ author {
|
|
|
69
69
|
${Q(!1,t)}
|
|
70
70
|
}
|
|
71
71
|
... on Bot {
|
|
72
|
-
${
|
|
72
|
+
${Is(!1)}
|
|
73
73
|
}
|
|
74
74
|
... on EnterpriseUserAccount {
|
|
75
|
-
${
|
|
75
|
+
${er(!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||K(e,"CHECK_RUN")?
|
|
88
|
+
${!e||K(e,"CHECK_RUN")?oo:""}
|
|
89
89
|
... on StatusContext {
|
|
90
90
|
context
|
|
91
91
|
createdAt
|
|
@@ -161,22 +161,22 @@ reviewRequests(first: 100) {
|
|
|
161
161
|
}
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
|
-
${!e||K(e,"LATEST_REVIEWS")?
|
|
164
|
+
${!e||K(e,"LATEST_REVIEWS")?uo(t):""}
|
|
165
165
|
additions
|
|
166
166
|
deletions
|
|
167
167
|
changedFiles
|
|
168
168
|
mergeable
|
|
169
169
|
mergeStateStatus
|
|
170
170
|
milestone {
|
|
171
|
-
${
|
|
171
|
+
${Ye}
|
|
172
172
|
}
|
|
173
173
|
labels(first: 100) {
|
|
174
174
|
nodes {
|
|
175
|
-
${
|
|
175
|
+
${et}
|
|
176
176
|
}
|
|
177
177
|
}
|
|
178
178
|
${!e||K(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
|
|
179
|
-
`,
|
|
179
|
+
`,lo=(s=!1,t)=>`
|
|
180
180
|
id
|
|
181
181
|
${!t||K(t,"ISSUE_FULL_DATABASE_ID")?"fullDatabaseId":"databaseId"}
|
|
182
182
|
title
|
|
@@ -185,10 +185,10 @@ author {
|
|
|
185
185
|
${Q(!1,s)}
|
|
186
186
|
}
|
|
187
187
|
... on Bot {
|
|
188
|
-
${
|
|
188
|
+
${Is(!1)}
|
|
189
189
|
}
|
|
190
190
|
... on EnterpriseUserAccount {
|
|
191
|
-
${
|
|
191
|
+
${er(!1)}
|
|
192
192
|
}
|
|
193
193
|
}
|
|
194
194
|
closedAt
|
|
@@ -217,34 +217,35 @@ assignees(first: 100) {
|
|
|
217
217
|
}
|
|
218
218
|
state
|
|
219
219
|
milestone {
|
|
220
|
-
${
|
|
220
|
+
${Ye}
|
|
221
221
|
}
|
|
222
222
|
labels(first: 100) {
|
|
223
223
|
nodes {
|
|
224
|
-
${
|
|
224
|
+
${et}
|
|
225
225
|
}
|
|
226
226
|
}
|
|
227
|
-
`,
|
|
227
|
+
`,po={"-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"},co=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),tr=s=>{let t=[];return(s.match(co)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];po[n]&&t.push(r)}}),t},rr="is:open",bs=s=>{if(!s||s.length===0)return rr;let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED"),n=t.has("MERGED");return e&&(r||n)?"":e?"is:open":r&&n?"is:closed":n?"is:merged":"is:closed is:unmerged"},ys=s=>{if(!s||s.length===0)return rr;let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?"":r?"is:closed":"is:open"},sr=(s,t,e,r)=>{let n=s==="issue",o=r.stateQualifier??rr;return{query:`
|
|
228
228
|
query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
229
229
|
search(type:ISSUE query:$query first: ${r.maxPageSize} after:$after) {
|
|
230
|
+
issueCount
|
|
230
231
|
pageInfo {
|
|
231
232
|
hasNextPage
|
|
232
233
|
endCursor
|
|
233
234
|
}
|
|
234
235
|
nodes {
|
|
235
236
|
... on ${n?"Issue":"PullRequest"} {
|
|
236
|
-
${n?
|
|
237
|
+
${n?lo(r.supportsEmail,r.enterpriseVersion??null):tt(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
|
|
237
238
|
}
|
|
238
239
|
}
|
|
239
240
|
}
|
|
240
|
-
}`,variables:{query:`is:${s} ${o} ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},
|
|
241
|
+
}`,variables:{query:`is:${s} ${o} ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},mo="Field 'isDraft' doesn't exist on type 'PullRequest'",rt=(s=[])=>s.some(t=>t?.message===mo),go=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,ho=`
|
|
241
242
|
\
|
|
242
|
-
+`,
|
|
243
|
+
+`,Ps=(s,t,e,r)=>{let n=go.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(ho,`
|
|
243
244
|
+`).split(`
|
|
244
245
|
`).slice(1),u=o-1,l=i-1,d=a.map(m=>{let g,h;switch(m[0]){case"-":{g="DELETED",u+=1,h=`${m.slice(1)}
|
|
245
246
|
`;break}case"+":{g="ADDED",l+=1,h=`${m.slice(1)}
|
|
246
247
|
`;break}default:g="UNMODIFIED",l+=1,u+=1,h=`${m}
|
|
247
|
-
`}return{line:h,oldLineNumber:g!=="ADDED"?u:null,newLineNumber:g!=="DELETED"?l:null,type:g}}),p=e,c=t;if(p!==null&&c!==null&&r!==null&&p<c){let m=0,g=d.length,h=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<d.length;y++){let P=d[y][h];P===p?m=y:P===c&&(g=y)}d=d.slice(m,g+1)}return d},
|
|
248
|
+
`}return{line:h,oldLineNumber:g!=="ADDED"?u:null,newLineNumber:g!=="DELETED"?l:null,type:g}}),p=e,c=t;if(p!==null&&c!==null&&r!==null&&p<c){let m=0,g=d.length,h=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<d.length;y++){let P=d[y][h];P===p?m=y:P===c&&(g=y)}d=d.slice(m,g+1)}return d},ws=s=>{let t=s.author;return t||(t=_e),{author:{id:"databaseId"in t?t.databaseId.toString():t.id,graphQLId:t.id,name:("name"in t?t.name:t.login)??t.login,username:t.login,email:("email"in t?t.email:null)??null,avatarUrl:t.avatarUrl,url:t.url},body:s.body,createdAt:s.publishedAt?new Date(s.publishedAt):null,graphQLId:s.id,id:s.fullDatabaseId??s.databaseId?.toString()??s.id,url:s.url}};var qs=`mutation DeleteIssueComment(
|
|
248
249
|
$issueCommentId: ID!
|
|
249
250
|
) {
|
|
250
251
|
deleteIssueComment(input: {
|
|
@@ -252,7 +253,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
252
253
|
}) {
|
|
253
254
|
clientMutationId
|
|
254
255
|
}
|
|
255
|
-
}`,
|
|
256
|
+
}`,vs=`mutation DeletePullRequestReviewComment(
|
|
256
257
|
$pullRequestReviewCommentId: ID!
|
|
257
258
|
) {
|
|
258
259
|
deletePullRequestReviewComment(input: {
|
|
@@ -262,7 +263,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
262
263
|
id
|
|
263
264
|
}
|
|
264
265
|
}
|
|
265
|
-
}`,
|
|
266
|
+
}`,Es=`mutation UpdateIssueComment(
|
|
266
267
|
$issueCommentId: ID!,
|
|
267
268
|
$body: String!
|
|
268
269
|
) {
|
|
@@ -275,7 +276,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
275
276
|
body
|
|
276
277
|
}
|
|
277
278
|
}
|
|
278
|
-
}`,
|
|
279
|
+
}`,Ss=`mutation ResolveReviewThread(
|
|
279
280
|
$pullRequestReviewThreadId: ID!
|
|
280
281
|
) {
|
|
281
282
|
resolveReviewThread(input: {
|
|
@@ -286,7 +287,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
286
287
|
isResolved
|
|
287
288
|
}
|
|
288
289
|
}
|
|
289
|
-
}`,
|
|
290
|
+
}`,Cs=`mutation UnresolveReviewThread(
|
|
290
291
|
$pullRequestReviewThreadId: ID!
|
|
291
292
|
) {
|
|
292
293
|
unresolveReviewThread(input: {
|
|
@@ -297,7 +298,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
297
298
|
isResolved
|
|
298
299
|
}
|
|
299
300
|
}
|
|
300
|
-
}`,
|
|
301
|
+
}`,Ds=`mutation UpdatePullRequestReviewComment(
|
|
301
302
|
$pullRequestReviewCommentId: ID!,
|
|
302
303
|
$body: String!
|
|
303
304
|
) {
|
|
@@ -310,7 +311,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
|
|
|
310
311
|
body
|
|
311
312
|
}
|
|
312
313
|
}
|
|
313
|
-
}`;var
|
|
314
|
+
}`;var As=s=>`
|
|
314
315
|
query GetPullRequestComments(
|
|
315
316
|
$namespace: String!
|
|
316
317
|
$name: String!
|
|
@@ -356,7 +357,7 @@ query GetPullRequestComments(
|
|
|
356
357
|
}
|
|
357
358
|
}
|
|
358
359
|
}
|
|
359
|
-
`;var
|
|
360
|
+
`;var nr=`
|
|
360
361
|
id
|
|
361
362
|
databaseId
|
|
362
363
|
owner {
|
|
@@ -369,10 +370,10 @@ defaultBranchRef {
|
|
|
369
370
|
name
|
|
370
371
|
}
|
|
371
372
|
viewerPermission
|
|
372
|
-
`,
|
|
373
|
+
`,fo={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},Ro=1e3,$s=s=>s!=null&&s>Ro?te("partial"):void 0,Io={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},bo={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},yo={OPEN:"OPEN",CLOSED:"CLOSED"},Po=["ADMIN","MAINTAIN","TRIAGE","WRITE"],ar=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),wo=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),or=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:wo(s.viewerPermission)}),qo=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),Ls=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:qo(s.permissions)}),vo=s=>({path:s.path,isDirectory:s.type==="tree"}),Eo={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},So={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},W=(s,t=So)=>{let e={};return t.id&&(e.id="databaseId"in s?s.databaseId.toString():s.id),t.graphQLId&&(e.graphQLId=s.id),t.name&&(e.name=s.name??s.login),t.username&&(e.username=s.login),t.email&&(e.email=s.email??null),t.avatarUrl&&(e.avatarUrl=s.avatarUrl),t.url&&(e.url=s.url),e},Co=(s,t)=>{let e={IN_PROGRESS:"RUNNING",PENDING:"PENDING",QUEUED:"PENDING",REQUESTED:"PENDING",WAITING:"PENDING"};return s!=="COMPLETED"?e[s]:{ACTION_REQUIRED:"ACTION_REQUIRED",CANCELLED:"CANCELLED",FAILURE:"FAILED",NEUTRAL:null,SKIPPED:"SKIPPED",STALE:"FAILED",STARTUP_FAILURE:"FAILED",SUCCESS:"SUCCESS",TIMED_OUT:"ERROR"}[t]},Do=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],ir=s=>{let t=null;s.author?t=s.author:t=_e;let e=(s.reviewRequests?.nodes||[]).filter(k).filter(i=>!i.asCodeOwner),r=s.headRepository?.url;r&&!r.endsWith(".git")&&(r=`${r}.git`);let n=s.repository?.url;n&&!n.endsWith(".git")&&(n=`${n}.git`);let o=e.filter(i=>i.requestedReviewer&&"__typename"in i.requestedReviewer).map(i=>({reviewer:W(i.requestedReviewer),state:"REVIEW_REQUESTED"})).concat((s.latestReviews?.nodes||[]).filter(k).map(i=>{let a=_e;return i.author&&i.author.__typename&&(a=i.author),{reviewer:W(a),state:fo[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:Eo[s.state],commentCount:s.comments.totalCount,upvoteCount:s.reactions.totalCount,author:t&&t.__typename?W(t):null,createdDate:new Date(s.createdAt),isDraft:s.isDraft,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login},remoteInfo:{cloneUrlHTTPS:n,cloneUrlSSH:s.repository.sshUrl}},isCrossRepository:s.headRepository!=null&&s.headRepository.databaseId!==s.repository.databaseId,headRepository:s.headRepository?{id:s.headRepository.databaseId.toString(),graphQLId:s.headRepository.id,name:s.headRepository.name,owner:{login:s.headRepository.owner.login},remoteInfo:{cloneUrlHTTPS:r,cloneUrlSSH:s.headRepository.sshUrl},isFork:s.headRepository.isFork}:null,headCommit:{buildStatuses:s.commits.nodes?.filter(k)[0]?.commit.statusCheckRollup?.contexts.nodes?.filter(k).map(i=>"context"in i?{completedAt:null,description:i.description,name:i.context,state:Do(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:Co(i.status,i.conclusion),startedAt:i.startedAt?new Date(i.startedAt):null,stage:null,url:i.permalink})??[]},headRef:s.headRef?{name:s.headRef.name,oid:s.headRef.target?.oid??null}:null,baseRef:s.baseRef?{name:s.baseRef.name,oid:s.baseRef.target?.oid??null}:null,url:s.url,updatedDate:new Date(s.updatedAt),closedDate:s.closedAt?new Date(s.closedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees.nodes?s.assignees.nodes.filter(k).map(i=>W(i)):null,reviews:o,reviewDecision:J(o),additions:s.additions,deletions:s.deletions,fileCount:s.changedFiles,commitCount:s.commits.totalCount,mergeableState:bo[s.mergeStateStatus]??Io[s.mergeable],milestone:s.milestone?ur(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(ar)??[],permissions:{canMerge:Po.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Ao=s=>{let{id:t,comments:e,isOutdated:r,isResolved:n,line:o,startLine:i,diffSide:a,originalLine:u,originalStartLine:l,startDiffSide:d}=s,p=e.nodes?.[0];if(!p)return null;let{author:c,body:m,databaseId:g,fullDatabaseId:h,id:y,path:f,publishedAt:P,url:v}=p,L=o??u,$=i??l,w=a??d;return{author:c?{avatarUrl:c.avatarUrl,email:null,name:c.login}:null,body:m,createdAt:P?new Date(P):null,diffLines:Ps(p.diffHunk,L,$,w),id:h??g.toString(),isOutdated:r,isResolved:n,graphQLId:y,threadId:t,filename:f,replies:e.nodes?.filter(k).slice(1).map($o)??[],url:v,line:L,startLine:$,side:w}},$o=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}),Lo=s=>{let t=null;return s.author?t=s.author:t=_e,{id:s.fullDatabaseId!==void 0?s.fullDatabaseId:s.databaseId.toString(),graphQLId:s.id,number:s.number,title:s.title,author:t&&t.__typename?W(t):null,commentCount:s.comments.totalCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:null,state:{name:yo[s.state],color:null},type:null,repository:{id:s.repository.databaseId.toString(),graphQLId:s.repository.id,name:s.repository.name,owner:{login:s.repository.owner.login}},url:s.url,updatedDate:new Date(s.updatedAt),assignees:s.assignees.nodes?.filter(k).map(e=>W(e))??[],upvoteCount:s.reactions.totalCount,milestone:s.milestone?ur(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(ar)??[]}},ur=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}),Ee=class extends F{constructor(){super(...arguments);this._scopesCache={};this._enterpriseVersionsCache={}}async getScopes(e){let r=e.token||this.config.token;if(!r)return[];let n=this._scopesCache[r];if(!n){let i=(await b(this.config,{query:"query { rateLimit(dryRun: true) { __typename } }"},e)).headers["x-oauth-scopes"];n=i?i.split(", "):[],this._scopesCache[r]=n}return n}async getEnterpriseVersion(e){let r=e.baseUrl||this.config.baseUrl;if(!r)return null;let n=this._enterpriseVersionsCache[r];if(!n){let o=await this.config.request({url:`${X(this.config,e)}/meta`,headers:R(e.token||this.config.token)});if(!o.body.installed_version)return null;n=o.body.installed_version.split(".").slice(0,3).map(i=>parseInt(i,10)),this._enterpriseVersionsCache[r]=n}return n}getEnterpriseAvatarUrlIfNeeded(e,r,n){let o=n.baseUrl||this.config.baseUrl;return!o||o.startsWith(Ze)?e:r?`https://avatars.githubusercontent.com/u/e?email=${encodeURIComponent(r)}`:""}async getCurrentUser(e={},r={}){if(e.fields&&!e.fields.length)throw new Error('"fields" must contain at least one field or be omitted');let n=Vr(e.fields),o=await this.getScopes(r),i=await b(this.config,{query:`
|
|
373
374
|
query getCurrentUser {
|
|
374
375
|
viewer {
|
|
375
|
-
${Q(!1,
|
|
376
|
+
${Q(!1,se(o),n)}
|
|
376
377
|
}
|
|
377
378
|
}
|
|
378
379
|
`},r),a=i.body.data?.viewer;if(!a)throw new I("Current user not found.",i.body.errors);return{data:W(a,n)}}async getAccountsForRepo(e,r={}){let n=await this.getScopes(r),{repo:{namespace:o,name:i},cursor:a}=e,u=await b(this.config,{query:`
|
|
@@ -380,7 +381,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
|
|
|
380
381
|
repository(owner: $owner, name: $name) {
|
|
381
382
|
assignableUsers(first: $first, after: $cursor) {
|
|
382
383
|
nodes {
|
|
383
|
-
${Q(!1,
|
|
384
|
+
${Q(!1,se(n))}
|
|
384
385
|
}
|
|
385
386
|
pageInfo {
|
|
386
387
|
endCursor
|
|
@@ -435,12 +436,12 @@ mutation createCommitOnBranch(
|
|
|
435
436
|
}
|
|
436
437
|
}
|
|
437
438
|
}
|
|
438
|
-
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([d,p])=>({contents:
|
|
439
|
+
`,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([d,p])=>({contents:Us.Base64.encode(p),path:d})),deletions:o.map(d=>({path:d}))},message:{body:n.description,headline:n.summary},repositoryNameWithOwner:`${a.namespace}/${a.name}`}},r);if(!l.body.data)throw new I("Could not create commit",l.body.errors);return{data:{name:l.body.data.createCommitOnBranch.ref.name,commit:{authoredDate:new Date(l.body.data.createCommitOnBranch.commit.authoredDate),committedDate:new Date(l.body.data.createCommitOnBranch.commit.committedDate),oid:l.body.data.createCommitOnBranch.commit.oid}}}}async getAccountForEmail(e,r={}){let n=await this.getScopes(r),o=await b(this.config,{query:`
|
|
439
440
|
query getAccountForEmail($query: String! $avatarSize: Int) {
|
|
440
441
|
search(query: $query, type: USER, first: 1) {
|
|
441
442
|
nodes {
|
|
442
443
|
... on User {
|
|
443
|
-
${Q(!0,
|
|
444
|
+
${Q(!0,se(n))}
|
|
444
445
|
}
|
|
445
446
|
}
|
|
446
447
|
}
|
|
@@ -448,7 +449,7 @@ query getAccountForEmail($query: String! $avatarSize: Int) {
|
|
|
448
449
|
`,variables:{query:`in:email ${e.email}`,avatarSize:e.avatarSize}},r),i=o.body.data?.search?.nodes?.[0];if(!i)throw new I("Could not find user via email",o.body.errors);return{data:W({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getAccountForUsername(e,r={}){let n=await this.getScopes(r),o=await b(this.config,{query:`
|
|
449
450
|
query getUserForUsername($login: String! $avatarSize: Int) {
|
|
450
451
|
user(login: $login) {
|
|
451
|
-
${Q(!0,
|
|
452
|
+
${Q(!0,se(n))}
|
|
452
453
|
}
|
|
453
454
|
}
|
|
454
455
|
`,variables:{login:e.username,avatarSize:e.avatarSize}},r),i=o.body.data?.user;if(!i)throw new I("Could not find user via username",o.body.errors);return{data:W({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)})}}async getOrgsForCurrentUser(e={},r={}){let n=await b(this.config,{query:`
|
|
@@ -489,19 +490,19 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
|
|
|
489
490
|
`,variables:{cursor:e.cursor,first:C,login:e.org}},r);if(!n.body.data?.viewer.organization?.membersWithRole&&n.body.errors?.length)throw new I("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=>W({...i,avatarUrl:this.getEnterpriseAvatarUrlIfNeeded(i.avatarUrl,i.email,r)}))}}async getRepo(e,r={}){let n=await b(this.config,{query:`
|
|
490
491
|
query getRepo($owner: String!, $name: String!) {
|
|
491
492
|
repository(owner: $owner, name: $name) {
|
|
492
|
-
${
|
|
493
|
+
${nr}
|
|
493
494
|
}
|
|
494
495
|
}
|
|
495
|
-
`,variables:{owner:e.namespace,name:e.name}},r);if(!n.body.data?.repository)throw new I(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:
|
|
496
|
+
`,variables:{owner:e.namespace,name:e.name}},r);if(!n.body.data?.repository)throw new I(`Repository ${e.namespace}/${e.name} not found`,n.body.errors);return{data:or(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},d)=>`
|
|
496
497
|
getRepo_${d}: repository(owner: "${u}", name: "${l}") {
|
|
497
|
-
${
|
|
498
|
+
${nr}
|
|
498
499
|
}
|
|
499
500
|
`).join(`
|
|
500
501
|
`),o=await b(this.config,{query:`
|
|
501
502
|
query batchGetRepos {
|
|
502
503
|
${n}
|
|
503
504
|
}
|
|
504
|
-
`},r);if(!o.body.data)throw new I("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(
|
|
505
|
+
`},r);if(!o.body.data)throw new I("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(or(d)):a.push({input:u})}),{data:i,errors:a}}async fetchMultipleRESTPages(e,r,n,o){let i=[];for(let p=0;p<r;p++)i.push(n(e+p));let a=await Promise.all(i),u=[];for(let p of a){if(!p.body)throw new Error(p.statusText||"Unknown error");u=u.concat(p.body.map(c=>o(c)))}let l=a.every(p=>p.body.length===100),d=e+r;return{data:u,pageInfo:{hasNextPage:l,nextPage:l?d:null}}}async getReposForCurrentUser(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForCurrentUser'");let n=new URLSearchParams;n.append("per_page","100"),e.affiliations&&n.append("affiliation",e.affiliations.join(","));let o=i=>this.config.request({url:`${X(this.config,r)}/user/repos?${n.toString()}&page=${i}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,o,Ls)}async getReposForOrg(e,r={}){if(e.simultaneousPagesToFetch&&e.simultaneousPagesToFetch>40)throw new Error("The argument 'simultaneousPagesToFetch' cannot exceed 40 for 'getReposForOrg'");let n=o=>this.config.request({url:`${X(this.config,r)}/orgs/${e.orgName}/repos?per_page=100&page=${o}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.raw+json","X-Github-Next-Global-ID":1}});return await this.fetchMultipleRESTPages(e.page??1,e.simultaneousPagesToFetch??4,n,Ls)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await b(this.config,{query:`
|
|
505
506
|
query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
506
507
|
search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
|
|
507
508
|
pageInfo {
|
|
@@ -510,12 +511,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
|
|
|
510
511
|
}
|
|
511
512
|
nodes {
|
|
512
513
|
... on Repository {
|
|
513
|
-
${
|
|
514
|
+
${nr}
|
|
514
515
|
}
|
|
515
516
|
}
|
|
516
517
|
}
|
|
517
518
|
}
|
|
518
|
-
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:C}},r);if(!n.body.data)throw new I("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(
|
|
519
|
+
`,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:C}},r);if(!n.body.data)throw new I("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(or)}}async getReposForOwners(e,r={}){return this.getReposForUsernames({usernames:e.owners.filter(n=>n.username).map(n=>n.username),cursor:e.cursor},r)}async getRefs(e,r,n={}){let o=await b(this.config,{query:`
|
|
519
520
|
query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
|
|
520
521
|
repository(owner: $owner, name: $name) {
|
|
521
522
|
refs(refPrefix: $refPrefix first: $first after: $cursor) {
|
|
@@ -575,7 +576,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
575
576
|
}
|
|
576
577
|
}
|
|
577
578
|
}
|
|
578
|
-
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},r),o=n.body.data?.repository;if(!o)throw new I("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new I("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new I("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,r={}){let n=await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async getMergeBase(e,r={}){return{data:(await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:R(r.token||this.config.token)})).body.merge_base_commit.sha}}async getPullRequestDiff(e,r={}){return(await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.pullRequestId}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.diff"}})).body??""}async searchPullRequests(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=
|
|
579
|
+
`,variables:{owner:e.repo.namespace,name:e.repo.name,ref:e.ref,path:e.path}},r),o=n.body.data?.repository;if(!o)throw new I("Blame repository not found.",n.body.errors);let i=o.object;if(!i||!("blame"in i))throw new I("Ref not found.",n.body.errors);if(i.blame.ranges.length===0)throw new I("File not found.",n.body.errors);return{data:{ranges:i.blame.ranges.map(a=>({startingLine:a.startingLine,endingLine:a.endingLine,commit:{oid:a.commit.oid,parentOids:a.commit.parents.nodes?.map(u=>u.oid)||[],authoredDate:new Date(a.commit.authoredDate),author:a.commit.author?{name:a.commit.author.name,email:a.commit.author.email,avatarUrl:a.commit.author.avatarUrl}:null,committedDate:new Date(a.commit.committedDate),committer:a.commit.committer?{name:a.commit.committer.name,email:a.commit.committer.email,avatarUrl:a.commit.committer.avatarUrl}:null,message:a.commit.message,fileCount:a.commit.changedFilesIfAvailable,additions:a.commit.additions,deletions:a.commit.deletions}}))}}}async getFileContents(e,r={}){let n=await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/contents/${encodeURIComponent(e.path)}?ref=${e.ref}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.raw+json"}});if(n.headers["content-type"].startsWith("application/json"))throw new Error(`GitHub: got directory when fetching "${e.path}", getFileContents does not support fetching directories`);if(!n.headers["content-type"].startsWith("application/vnd.github.raw+json"))throw new Error(`GitHub: unsupported content type "${n.headers["content-type"]}" when fetching "${e.path}"`);return{data:new Blob([n.body])}}async getMergeBase(e,r={}){return{data:(await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/compare/${encodeURIComponent(e.base)}...${encodeURIComponent(e.head)}`,headers:R(r.token||this.config.token)})).body.merge_base_commit.sha}}async getPullRequestDiff(e,r={}){return(await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.pullRequestId}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.diff"}})).body??""}async searchPullRequests(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=se(o),a=bs(e.states),u=D(e.maxPageSize,{fallback:hs,max:C}),l=c=>{let m=c&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return sr("pr",m,e.cursor,{maxPageSize:u,supportsEmail:i,supportsDrafts:c,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos,stateQualifier:a})},d=await b(this.config,l(!0),r);d.body.errors&&rt(d.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(d=await b(this.config,l(!1),r));let{data:p}=d.body;if(!p)throw new I("Could not search pull requests",d.body.errors);return{pageInfo:{hasNextPage:p.search.pageInfo.hasNextPage,endCursor:p.search.pageInfo.endCursor},data:x(p.search.nodes?.filter(k).map(ir)||[],e.states),metadata:$s(p.search.issueCount)}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=se(o),a=ys(e.states),u=D(e.maxPageSize,{fallback:fs,max:C}),l=await b(this.config,sr("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:u,enterpriseVersion:n,stateQualifier:a}),r),{data:d}=l.body;if(!d)throw new I("Could not search issues",l.body.errors);return{pageInfo:{hasNextPage:d.search.pageInfo.hasNextPage,endCursor:d.search.pageInfo.endCursor},data:d.search.nodes?.filter(k).map(Lo)||[],metadata:$s(d.search.issueCount)}}async getPullRequestsAssociatedWithUser(e,r={}){let n=[`involves:${e.username}`];return e.repos?.length&&e.repos.forEach(o=>{n.push(`repo:${o.namespace}/${o.name}`)}),e.labelNames&&e.labelNames.forEach(o=>{n.push(`label:"${o}"`)}),this.searchPullRequests({query:n.join(" "),cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize,states:e.states},r)}async getPullRequestsForRepos(e,r={}){let{assigneeLogins:n,updatedBefore:o,authorLogin:i,repos:a,reviewRequestedLogin:u,startQuery:l,mentionLogin:d,labelNames:p,maxPageSize:c}=e,m=tr(l||"");return a.forEach(g=>{m.push(`repo:${g.namespace}/${g.name}`)}),n&&n.forEach(g=>{m.push(`assignee:${g}`)}),o&&m.push(`updated:<${o}`),i&&m.push(`author:${i}`),u&&m.push(`review-requested:${u}`),d&&m.push(`mentions:${d}`),p&&p.forEach(g=>{m.push(`label:"${g}"`)}),this.searchPullRequests({query:`sort:updated ${m.join(" ")}`,isDraft:e.isDraft,cursor:e.cursor,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:c,states:e.states},r)}async getPullRequestForRepo(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=se(o),a=p=>({query:`query getPullRequest(
|
|
579
580
|
$owner: String!
|
|
580
581
|
$name: String!
|
|
581
582
|
$number: Int!
|
|
@@ -585,18 +586,18 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
585
586
|
name: $name
|
|
586
587
|
) {
|
|
587
588
|
pullRequest(number: $number) {
|
|
588
|
-
${
|
|
589
|
+
${tt(p,i,n)}
|
|
589
590
|
}
|
|
590
591
|
}
|
|
591
|
-
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),r);u.body.errors&&
|
|
592
|
+
}`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),r);u.body.errors&&rt(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await b(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new I("Could not fetch pull request by number",u.body.errors);let d=u.body.data?.repository.pullRequest;return{data:d?ir(d):null}}async getPullRequestDescription(e,r={}){try{let n=await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github.full+json"}});return{data:{description:n.body?.body??"",descriptionHtml:n.body?.body_html||null}}}catch{return{data:{description:null,descriptionHtml:null}}}}async setPullRequestDescription(e,r={}){let n=await this.config.request({method:"PATCH",url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/pulls/${e.number}`,headers:{...R(r.token||this.config.token),Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({body:e.description})});return{data:{description:n.body?.body??e.description,descriptionHtml:n.body?.body_html||null}}}async getPullRequestByGraphQLId(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=se(o),a=p=>({query:`query getPullRequest(
|
|
592
593
|
$graphQLId: ID!
|
|
593
594
|
) {
|
|
594
595
|
node(id: $graphQLId) {
|
|
595
596
|
... on PullRequest {
|
|
596
|
-
${
|
|
597
|
+
${tt(p,i,n)}
|
|
597
598
|
}
|
|
598
599
|
}
|
|
599
|
-
}`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),r);u.body.errors&&
|
|
600
|
+
}`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),r);u.body.errors&&rt(u.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(u=await b(this.config,a(!1),r));let{data:l}=u.body;if(!l)throw new I("Could not fetch pull request by id",u.body.errors);let d=u.body.data?.node;return{data:d?ir(d):null}}async closePullRequest(e,r={}){let{pullRequest:{graphQLId:n}}=e;if(!n)throw new Error('GitHub requires "graphQLId" for this function.');let o=`mutation ClosePullRequest($pullRequestGraphQLId: ID!) {
|
|
600
601
|
closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
|
|
601
602
|
pullRequest {
|
|
602
603
|
id
|
|
@@ -669,7 +670,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
669
670
|
}
|
|
670
671
|
}
|
|
671
672
|
}
|
|
672
|
-
}`,a=await b(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},r);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new I("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,r={}){let{pullRequest:n,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(l)return this.addReplyToReviewThread({threadId:l,comment:o},r);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:n,comment:o,path:i,line:a,side:u},r)}async deleteInlineComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:
|
|
673
|
+
}`,a=await b(this.config,{query:i,variables:{subjectId:n.graphQLId,body:o}},r);if(!a.body.data?.addComment?.commentEdge?.node?.id)throw new I("Could not add comment to pull request",a.body.errors)}async addInlineCommentToPullRequest(e,r={}){let{pullRequest:n,comment:o,path:i,line:a,side:u="RIGHT",threadId:l}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');if(!o?.trim())throw new Error("GitHub requires a comment when adding an inline comment to a pull request.");if(l)return this.addReplyToReviewThread({threadId:l,comment:o},r);if(!i?.trim())throw new Error("GitHub requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(a)||a<1)throw new Error("GitHub requires a positive line number when adding an inline comment to a pull request.");if(u!=="LEFT"&&u!=="RIGHT")throw new Error('GitHub requires side to be either "LEFT" or "RIGHT".');return this.createReviewThread({pullRequest:n,comment:o,path:i,line:a,side:u},r)}async deleteInlineComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:vs,variables:{pullRequestReviewCommentId:n}},r);if(!o.body.data?.deletePullRequestReviewComment)throw new I("Could not delete inline comment",o.body.errors)}async deleteComment(e,r={}){let{commentId:n}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');let o=await b(this.config,{query:qs,variables:{issueCommentId:n}},r);if(!o.body.data?.deleteIssueComment)throw new I("Could not delete comment",o.body.errors)}async editComment(e,r={}){let{commentId:n,body:o}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing a comment.");let i=await b(this.config,{query:Es,variables:{issueCommentId:n,body:o}},r);if(!i.body.data?.updateIssueComment?.issueComment?.id)throw new I("Could not edit comment",i.body.errors)}async editInlineComment(e,r={}){let{commentId:n,body:o}=e;if(!n)throw new Error('GitHub requires "commentId" for this function.');if(!o?.trim())throw new Error("GitHub requires a body when editing an inline comment.");let i=await b(this.config,{query:Ds,variables:{pullRequestReviewCommentId:n,body:o}},r);if(!i.body.data?.updatePullRequestReviewComment?.pullRequestReviewComment?.id)throw new I("Could not edit inline comment",i.body.errors)}async resolveReviewThread(e,r={}){let{threadId:n}=e;if(!n)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:Ss,variables:{pullRequestReviewThreadId:n}},r);if(!o.body.data?.resolveReviewThread?.thread?.id)throw new I("Could not resolve review thread",o.body.errors)}async unresolveReviewThread(e,r={}){let{threadId:n}=e;if(!n)throw new Error('GitHub requires "threadId" for this function.');let o=await b(this.config,{query:Cs,variables:{pullRequestReviewThreadId:n}},r);if(!o.body.data?.unresolveReviewThread?.thread?.id)throw new I("Could not unresolve review thread",o.body.errors)}async addReplyToReviewThread(e,r){let{threadId:n,comment:o}=e,i=`mutation AddPullRequestReviewThreadReply(
|
|
673
674
|
$threadId: ID!,
|
|
674
675
|
$body: String!
|
|
675
676
|
) {
|
|
@@ -799,13 +800,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
|
|
|
799
800
|
}
|
|
800
801
|
}
|
|
801
802
|
}
|
|
802
|
-
}`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),d=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(k).reduce((c,m)=>{if(!m.comments.nodes?.[0]?.pullRequestReview)return c;let g=m.comments.nodes[0].pullRequestReview,h=
|
|
803
|
+
}`,l=await b(this.config,{query:u,variables:{namespace:o,name:i,pullRequestId:a}},r),d=l.body.data?.repository.pullRequest.reviewThreads.nodes?.filter(k).reduce((c,m)=>{if(!m.comments.nodes?.[0]?.pullRequestReview)return c;let g=m.comments.nodes[0].pullRequestReview,h=Ao(m);return h&&(c[g.id]||(c[g.id]=[]),c[g.id].push(h)),c},{})??{};return{data:l.body.data?.repository.pullRequest.reviews.nodes?.filter(k).filter(c=>d[c.id]).map(c=>({author:c.author?{avatarUrl:c.author.avatarUrl,email:null,name:c.author.login}:null,body:c.body,createdAt:c.publishedAt?new Date(c.publishedAt):null,id:c.fullDatabaseId??c.databaseId.toString(),graphQLId:c.id,reviewComments:d[c.id],url:c.url}))??[]}}async getCommentsForPullRequest(e,r={}){let n=await this.getEnterpriseVersion(r),o=!n||K(n,"ISSUE_FULL_DATABASE_ID"),{repo:{namespace:i,name:a},pullRequestNumber:u,cursor:l}=e,d=await b(this.config,{query:As(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:C}},r),p=d.body.data?.repository;if(!p)throw new I("Could not fetch pull request comments",d.body.errors);return{data:p.pullRequest.comments.nodes?.filter(k).map(ws)??[],pageInfo:p.pullRequest.comments.pageInfo}}async getIssuesAssociatedWithUser(e,r={}){let[n,o]=e.cursor?.split(";")||[void 0,void 0],i=[];e.labelNames&&e.labelNames.forEach(m=>{i.push(`label:"${m}"`)});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,states:e.states},r),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize,states:e.states},r)]),l={},d=[],p=m=>{l[m.id]||(l[m.id]=!0,d.push(m))};a?.data.forEach(p),u?.data.forEach(p);let c=a?.metadata&&u?.metadata?te(ze(a.metadata.completeness,u.metadata.completeness),[...a.metadata.failures??[],...u.metadata.failures??[]]):a?.metadata??u?.metadata;return{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,metadata:c}}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation SetPullRequestLabels($pullRequestGraphQLId: ID!, $labelGraphQLIds: [ID!]) {
|
|
803
804
|
updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
|
|
804
805
|
pullRequest {
|
|
805
806
|
id
|
|
806
807
|
}
|
|
807
808
|
}
|
|
808
|
-
}`,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})}},r);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=
|
|
809
|
+
}`,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})}},r);if(!a.body.data?.updatePullRequest?.pullRequest?.id)throw new I("Could not set pull request labels",a.body.errors)}async getIssuesForRepos(e,r={}){let n=tr(e.startQuery||""),{cursor:o,assigneeLogins:i,updatedBefore:a,authorLogin:u,mentionLogin:l,labelNames:d}=e;return e.repos.forEach(p=>{n.push(`repo:${p.namespace}/${p.name}`)}),i&&i.forEach(p=>{n.push(`assignee:${p}`)}),a&&n.push(`updated:<${a}`),u&&n.push(`author:${u}`),l&&n.push(`mentions:${l}`),d&&d.forEach(p=>{n.push(`label:"${p}"`)}),this.searchIssues({query:`sort:updated ${n.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize,states:e.states},r)}async closeIssueWithReason(e,r={}){let{issue:n,reason:o}=e;if(!n.graphQLId)throw new Error('GitHub requires "graphQLId" for this function.');let i=`mutation CloseIssueWithReason($issueGraphQLId: ID!, $reason: IssueClosedStateReason!) {
|
|
809
810
|
closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
|
|
810
811
|
issue {
|
|
811
812
|
id
|
|
@@ -846,7 +847,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
846
847
|
repository(owner: $owner, name: $name) {
|
|
847
848
|
milestones(first: $first, after: $cursor) {
|
|
848
849
|
nodes {
|
|
849
|
-
${
|
|
850
|
+
${Ye}
|
|
850
851
|
}
|
|
851
852
|
pageInfo {
|
|
852
853
|
endCursor
|
|
@@ -855,12 +856,12 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
855
856
|
}
|
|
856
857
|
}
|
|
857
858
|
}
|
|
858
|
-
`,variables:{owner:n,name:o,cursor:i,first:C}},r);if(!a.body.data)throw new I("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(
|
|
859
|
+
`,variables:{owner:n,name:o,cursor:i,first:C}},r);if(!a.body.data)throw new I("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(ur)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await b(this.config,{query:`
|
|
859
860
|
query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
|
|
860
861
|
repository(owner: $owner, name: $name) {
|
|
861
862
|
labels(first: $first, after: $cursor) {
|
|
862
863
|
nodes {
|
|
863
|
-
${
|
|
864
|
+
${et}
|
|
864
865
|
}
|
|
865
866
|
pageInfo {
|
|
866
867
|
endCursor
|
|
@@ -869,7 +870,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
|
|
|
869
870
|
}
|
|
870
871
|
}
|
|
871
872
|
}
|
|
872
|
-
`,variables:{owner:n,name:o,cursor:i,first:C}},r);if(!a.body.data)throw new I("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(
|
|
873
|
+
`,variables:{owner:n,name:o,cursor:i,first:C}},r);if(!a.body.data)throw new I("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(ar)??[]}}async getTreeForRepo(e,r={}){let n=await this.config.request({url:`${X(this.config,r)}/repos/${e.repo.namespace}/${e.repo.name}/git/trees/${e.branch}?recursive=1`,headers:{...R(r.token||this.config.token)}});if(!n.body)throw new Error("Could not fetch trees");return{data:n.body.tree.map(vo)}}};var Uo="https://gitlab.com/api/v4",Go="https://gitlab.com/api/graphql",lr=/\/api\/v\d+$/,Gs=s=>{if(s.endsWith("/api/graphql"))throw new Error("The graphql endpoint is being used as the baseUrl. This package uses both GraphQL and REST APIs, and the REST version cannot be assumed. Use the REST endpoint as the baseUrl instead.")},U=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Gs(e),lr.test(e)||(e=e+"/api/v4"),e):Uo},To=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Gs(e),lr.test(e)&&(e=e.replace(lr,"")),`${e}/api/graphql`):Go},E=(s,t,e)=>{let r=R(e.token||s.token);return s.request({url:To(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},ke=s=>s?.map(t=>`"${t.message}"`).join(", ");var nt=s=>s.split("/").slice(0,-1).join("/"),ot=s=>s.split("/").at(-1)??"",pr=s=>{let t=parseInt(`${s["x-next-page"]}`,10);return Number.isNaN(t)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:t}},st=s=>({id:s.id.replace(Re,""),graphQLId:s.id,namespace:nt(s.fullPath),name:ot(s.fullPath),webUrl:s.webUrl}),xe=s=>({id:s.id.replace(Re,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:nt(s.fullPath),name:ot(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Oo={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},_o={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var xs="gid://gitlab/User/",Re="gid://gitlab/Project/",ko="gid://gitlab/MergeRequest/",Ns="gid://gitlab/Issue/",xo="gid://gitlab/ProjectLabel/",No="gid://gitlab/Milestone/",Bo="gid://gitlab/Ci::Build/",yr=`
|
|
873
874
|
description
|
|
874
875
|
dueDate
|
|
875
876
|
id
|
|
@@ -878,7 +879,7 @@ startDate
|
|
|
878
879
|
state
|
|
879
880
|
title
|
|
880
881
|
webPath
|
|
881
|
-
`,
|
|
882
|
+
`,dr=`
|
|
882
883
|
id
|
|
883
884
|
fullPath
|
|
884
885
|
webUrl
|
|
@@ -892,14 +893,14 @@ userPermissions {
|
|
|
892
893
|
downloadCode
|
|
893
894
|
pushCode
|
|
894
895
|
}
|
|
895
|
-
`,
|
|
896
|
+
`,ne=`
|
|
896
897
|
id
|
|
897
898
|
name
|
|
898
899
|
username
|
|
899
900
|
publicEmail
|
|
900
901
|
avatarUrl
|
|
901
902
|
webUrl
|
|
902
|
-
`,
|
|
903
|
+
`,Pr=`
|
|
903
904
|
color
|
|
904
905
|
description
|
|
905
906
|
id
|
|
@@ -910,13 +911,13 @@ httpUrlToRepo
|
|
|
910
911
|
fullPath
|
|
911
912
|
sshUrlToRepo
|
|
912
913
|
webUrl
|
|
913
|
-
`,
|
|
914
|
+
`,cr=`
|
|
914
915
|
author {
|
|
915
|
-
${
|
|
916
|
+
${ne}
|
|
916
917
|
}
|
|
917
918
|
assignees {
|
|
918
919
|
nodes {
|
|
919
|
-
${
|
|
920
|
+
${ne}
|
|
920
921
|
}
|
|
921
922
|
}
|
|
922
923
|
closedAt
|
|
@@ -927,7 +928,7 @@ id
|
|
|
927
928
|
iid
|
|
928
929
|
labels {
|
|
929
930
|
nodes {
|
|
930
|
-
${
|
|
931
|
+
${Pr}
|
|
931
932
|
}
|
|
932
933
|
}
|
|
933
934
|
state
|
|
@@ -938,9 +939,9 @@ upvotes
|
|
|
938
939
|
userNotesCount
|
|
939
940
|
webUrl
|
|
940
941
|
milestone {
|
|
941
|
-
${
|
|
942
|
+
${yr}
|
|
942
943
|
}
|
|
943
|
-
`,
|
|
944
|
+
`,jo=`
|
|
944
945
|
stages {
|
|
945
946
|
nodes {
|
|
946
947
|
jobs {
|
|
@@ -956,11 +957,11 @@ stages {
|
|
|
956
957
|
name
|
|
957
958
|
}
|
|
958
959
|
}
|
|
959
|
-
`,
|
|
960
|
+
`,mr=(s,t,e)=>`
|
|
960
961
|
id
|
|
961
962
|
state
|
|
962
963
|
author {
|
|
963
|
-
${
|
|
964
|
+
${ne}
|
|
964
965
|
}
|
|
965
966
|
diffRefs {
|
|
966
967
|
baseSha
|
|
@@ -986,12 +987,12 @@ targetBranch
|
|
|
986
987
|
sourceBranch
|
|
987
988
|
assignees {
|
|
988
989
|
nodes {
|
|
989
|
-
${
|
|
990
|
+
${ne}
|
|
990
991
|
}
|
|
991
992
|
}
|
|
992
993
|
reviewers {
|
|
993
994
|
nodes {
|
|
994
|
-
${
|
|
995
|
+
${ne}
|
|
995
996
|
mergeRequestInteraction {
|
|
996
997
|
approved
|
|
997
998
|
reviewState
|
|
@@ -1001,25 +1002,25 @@ reviewers {
|
|
|
1001
1002
|
mergeStatusEnum
|
|
1002
1003
|
labels {
|
|
1003
1004
|
nodes {
|
|
1004
|
-
${
|
|
1005
|
+
${Pr}
|
|
1005
1006
|
}
|
|
1006
1007
|
}
|
|
1007
1008
|
${s?`project { ${Ne} archived } sourceProject { ${Ne} }`:""}
|
|
1008
|
-
${t?`milestone { ${
|
|
1009
|
-
${e?`headPipeline { ${
|
|
1010
|
-
`,_=s=>`${s.namespace}/${s.name}`,
|
|
1009
|
+
${t?`milestone { ${yr} }`:""}
|
|
1010
|
+
${e?`headPipeline { ${jo} }`:""}
|
|
1011
|
+
`,_=s=>`${s.namespace}/${s.name}`,Fo=s=>`${s.namespace}/${s.name}`,Qo=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),zo=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),gr=s=>({id:s.id.replace(Re,""),graphQLId:s.id,namespace:nt(s.fullPath),name:ot(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:zo(s.userPermissions)}),Mo=s=>({path:s.path,isDirectory:s.type==="tree"}),Wo={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Ho={OPEN:"opened",MERGED:"merged",CLOSED:"closed"},Ts=s=>{if(!s||s.length===0)return"state: opened";let t=Array.from(new Set(s));return t.length>1?"":`state: ${Ho[t[0]]}`},Os=s=>{if(!s||s.length===0)return"state: opened";let t=Array.from(new Set(s));return t.length>1?"":`state: ${t[0]==="CLOSED"?"closed":"opened"}`},le=100,Vo=20,Jo=250,it=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,oe=(s,t,e)=>{let r=it(s.avatarUrl,t,e);return{id:s.id.replace(xs,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},wr=s=>({color:s.color,description:s.description,id:s.id.replace(xo,""),graphQLId:s.id,name:s.title}),Ko=(s,t)=>s?s==="FAILED"&&t?"WARNING":{CANCELED:"CANCELLED",CREATED:"PENDING",FAILED:"FAILED",MANUAL:"OPTIONAL_ACTION_REQUIRED",PENDING:"PENDING",PREPARING:"RUNNING",RUNNING:"RUNNING",SCHEDULED:"PENDING",SKIPPED:"SKIPPED",SUCCESS:"SUCCESS",WAITING_FOR_CALLBACK:"PENDING",WAITING_FOR_RESOURCE:"PENDING"}[s]:null,Xo=(s,t,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:oe(s,t,e),state:s.mergeRequestInteraction?.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},hr=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>Xo(i,r,n)):null;return{id:s.id.replace(ko,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:Wo[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?oe(s.author,r,n):null,createdDate:new Date(s.createdAt),isDraft:s.draft,repository:{id:t.id,graphQLId:t.graphQLId,name:t.name,owner:{login:t.namespace},remoteInfo:t.httpsUrl&&t.sshUrl?{cloneUrlHTTPS:t.httpsUrl,cloneUrlSSH:t.sshUrl}:null},isCrossRepository:e!=null&&e.id!==t.id,headRepository:e?{id:e.id,graphQLId:e.graphQLId,name:e.name,owner:{login:e.namespace},remoteInfo:{cloneUrlHTTPS:e.httpsUrl,cloneUrlSSH:e.sshUrl}}:null,headCommit:{buildStatuses:s.headPipeline?.stages?.nodes?.flatMap(i=>i.jobs?.nodes?.map(a=>({completedAt:a.finishedAt?new Date(a.finishedAt):null,description:null,name:a.name??null,state:Ko(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(Bo,"")}`}))??[])??[]},baseRef:{name:s.targetBranch,oid:s.diffRefs?.baseSha??null},headRef:{name:s.sourceBranch,oid:s.diffRefs?.headSha??null},url:s.webUrl,updatedDate:new Date(s.updatedAt),closedDate:s.mergedAt?new Date(s.mergedAt):null,mergedDate:s.mergedAt?new Date(s.mergedAt):null,assignees:s.assignees?.nodes?s.assignees.nodes.map(i=>oe(i,r,n)):null,reviews:o,reviewDecision:J(o),additions:s.diffStatsSummary?.additions||0,deletions:s.diffStatsSummary?.deletions||0,fileCount:s.diffStatsSummary?.fileCount||0,commitCount:s.commitCount||0,mergeableState:_o[s.mergeStatusEnum],milestone:s.milestone?qr(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(wr)??[],permissions:null}},fr=(s,t,e,r)=>({author:oe(s.author,e,r),assignees:s.assignees.nodes.map(n=>oe(n,e,r)),commentCount:s.userNotesCount,closedDate:s.closedAt?new Date(s.closedAt):null,createdDate:new Date(s.createdAt),description:s.description,graphQLId:s.id,id:s.id.replace(Ns,""),labels:s.labels?.nodes?.map(wr)??[],number:s.iid,repository:{id:t.id.replace(Re,""),graphQLId:t.id,name:t.name,owner:{login:t.namespace}},updatedDate:new Date(s.updatedAt),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:s.type,title:s.title,url:s.webUrl,milestone:s.milestone?qr(s.milestone,t.webUrl):null}),qr=(s,t)=>({id:s.id.replace(No,""),graphQLId:s.id,number:parseInt(s.iid,10),title:s.title,description:s.description,isOpen:s.state==="active",url:`${t}/-/${s.webPath.replace(/.+?\/-\//,"")}`,startDate:s.startDate?new Date(s.startDate):null,dueDate:s.dueDate?new Date(s.dueDate):null}),Zo=s=>Buffer.from(JSON.stringify(s),"utf8").toString("base64"),Yo=(s,t)=>{if(!s)return{page:1,perPage:t};try{let e=JSON.parse(Buffer.from(s,"base64").toString("utf8")),r=typeof e.page=="number"&&e.page>0?e.page:1,n=typeof e.perPage=="number"&&e.perPage>0?e.perPage:t;return{page:r,perPage:n}}catch{return{page:1,perPage:t}}},Ir=(s,t,e)=>({id:s.id.toString(),graphQLId:`${xs}${s.id}`,name:s.name,username:s.username,email:s.email??null,avatarUrl:it(s.avatar_url,t,e),url:s.web_url}),_s=(s,t,e)=>({avatarUrl:it(s.avatar_url,t,e)??"",email:null,name:s.name}),ks=s=>s.replace(/^\/+/,"").split("/")[0]==="groups",ei=s=>{let t=s.references?.full;if(t){let r=t.includes("#")?t.slice(0,t.lastIndexOf("#")):t;if(r&&!ks(r))return r}let e="/-/issues";try{let{pathname:r}=new URL(s.web_url),n=r.indexOf(e);if(n===-1)return;let o=r.slice(0,n).replace(/^\/+/,"");return!o||ks(o)?void 0:o}catch{return}},ti=(s,t,e)=>{let r=ei(s);return{author:s.author?Ir(s.author,t,e):null,assignees:(s.assignees??[]).map(n=>Ir(n,t,e)),commentCount:s.user_notes_count,closedDate:s.closed_at?new Date(s.closed_at):null,createdDate:new Date(s.created_at),description:s.description,graphQLId:`${Ns}${s.id}`,id:s.id.toString(),labels:(s.labels??[]).map(n=>({color:null,description:null,id:null,name:n})),number:s.iid.toString(),repository:{graphQLId:`${Re}${s.project_id}`,id:s.project_id.toString(),name:r?ot(r):"",owner:{login:r?nt(r):void 0}},updatedDate:new Date(s.updated_at),upvoteCount:s.upvotes,state:{name:s.state,color:null},type:null,title:s.title,url:s.web_url}},ri=s=>s?.new_line!=null?"RIGHT":s?.old_line!=null?"LEFT":null,si=s=>{let t=s.old_path||s.new_path,e=s.new_path||s.old_path,r=[`diff --git a/${t} b/${e}`];return s.new_file&&s.b_mode?r.push(`new file mode ${s.b_mode}`):s.deleted_file&&s.a_mode?r.push(`deleted file mode ${s.a_mode}`):s.a_mode&&s.b_mode&&s.a_mode!==s.b_mode&&(r.push(`old mode ${s.a_mode}`),r.push(`new mode ${s.b_mode}`)),s.renamed_file&&(r.push(`rename from ${s.old_path}`),r.push(`rename to ${s.new_path}`)),s.diff&&s.diff.length>0?(r.push(`--- ${s.new_file?"/dev/null":`a/${t}`}`),r.push(`+++ ${s.deleted_file?"/dev/null":`b/${e}`}`),`${r.join(`
|
|
1011
1012
|
`)}
|
|
1012
1013
|
${s.diff.endsWith(`
|
|
1013
1014
|
`)?s.diff:`${s.diff}
|
|
1014
1015
|
`}`):`${r.join(`
|
|
1015
1016
|
`)}
|
|
1016
|
-
`},
|
|
1017
|
+
`},Bs="|",br=(s,t,e,r)=>[s,t,e.toString(),r.toString()].join(Bs),ni=s=>{let t=s.split(Bs);if(t.length!==4)throw new Error("Invalid GitLab comment ID format \u2014 expected a composite ID produced by getCommentsForPullRequest or addInlineCommentToPullRequest.");return{namespace:t[0],name:t[1],mergeRequestIid:t[2],noteId:t[3]}},Rr=(s,t,e,r)=>({author:s.author?Ir(s.author,t,e):null,body:s.body,createdAt:s.created_at?new Date(s.created_at):null,id:br(r.namespace,r.name,r.mergeRequestIid,s.id),url:""}),Se=class extends F{getIsSelfHosted(t){return!!t.baseUrl||!!this.config.baseUrl}async getCurrentUser(t={},e={}){let n=(await E(this.config,{query:`
|
|
1017
1018
|
query getCurrentUser {
|
|
1018
1019
|
currentUser {
|
|
1019
|
-
${
|
|
1020
|
+
${ne}
|
|
1020
1021
|
}
|
|
1021
1022
|
}
|
|
1022
|
-
`},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:
|
|
1023
|
+
`},e)).body.data?.currentUser;if(!n)throw new Error("Current user not found.");return{data:oe(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getUserForCommit(t,e={}){let r=_(t.repo),o=(await E(this.config,{query:`
|
|
1023
1024
|
query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
1024
1025
|
project(fullPath: $fullPath) {
|
|
1025
1026
|
repository {
|
|
@@ -1035,21 +1036,21 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
|
|
|
1035
1036
|
}
|
|
1036
1037
|
}
|
|
1037
1038
|
}
|
|
1038
|
-
`,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=
|
|
1039
|
+
`,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=it(o.author.avatarUrl,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl);return{data:{name:o.authorName,email:o.authorEmail,avatarUrl:i}}}async getAccountForEmail(t,e={}){let n=(await E(this.config,{query:`
|
|
1039
1040
|
query getAccountForEmail($email: String!) {
|
|
1040
1041
|
users(search: $email) {
|
|
1041
1042
|
nodes {
|
|
1042
|
-
${
|
|
1043
|
+
${ne}
|
|
1043
1044
|
}
|
|
1044
1045
|
}
|
|
1045
1046
|
}
|
|
1046
|
-
`,variables:{email:t.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:
|
|
1047
|
+
`,variables:{email:t.email}},e)).body.data?.users?.nodes?.[0];if(!n)throw new Error("User not found.");return{data:oe(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountForUsername(t,e={}){let n=(await E(this.config,{query:`
|
|
1047
1048
|
query getAccountForUsername($username: String!) {
|
|
1048
1049
|
user(username: $username) {
|
|
1049
|
-
${
|
|
1050
|
+
${ne}
|
|
1050
1051
|
}
|
|
1051
1052
|
}
|
|
1052
|
-
`,variables:{username:t.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:
|
|
1053
|
+
`,variables:{username:t.username}},e)).body.data?.user;if(!n)throw new Error("User not found.");return{data:oe(n,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}async getAccountsForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await E(this.config,{query:`
|
|
1053
1054
|
query getAccountsForRepo(
|
|
1054
1055
|
$fullPath: ID!
|
|
1055
1056
|
$after: String
|
|
@@ -1060,7 +1061,7 @@ query getAccountsForRepo(
|
|
|
1060
1061
|
projectMembers(after: $after) {
|
|
1061
1062
|
nodes {
|
|
1062
1063
|
user {
|
|
1063
|
-
${
|
|
1064
|
+
${ne}
|
|
1064
1065
|
}
|
|
1065
1066
|
}
|
|
1066
1067
|
pageInfo {
|
|
@@ -1070,15 +1071,15 @@ query getAccountsForRepo(
|
|
|
1070
1071
|
}
|
|
1071
1072
|
}
|
|
1072
1073
|
}
|
|
1073
|
-
`,variables:{fullPath:`${r}/${n}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>
|
|
1074
|
+
`,variables:{fullPath:`${r}/${n}`,after:o}},e),a=i.body.data?.project?.projectMembers?.nodes?.map(u=>u.user).filter(u=>u!==null);return{pageInfo:i.body.data?.project?.projectMembers?.pageInfo??{endCursor:null,hasNextPage:!1},data:a?.map(u=>oe(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(t,e={}){let r=_(t),n=await E(this.config,{query:`
|
|
1074
1075
|
query getRepo($fullPath: ID!) {
|
|
1075
1076
|
project(fullPath: $fullPath) {
|
|
1076
|
-
${
|
|
1077
|
+
${dr}
|
|
1077
1078
|
}
|
|
1078
1079
|
}
|
|
1079
1080
|
`,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:gr(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(_).map((u,l)=>`
|
|
1080
1081
|
getRepo_${l}: project(fullPath: "${u}") {
|
|
1081
|
-
${
|
|
1082
|
+
${dr}
|
|
1082
1083
|
}
|
|
1083
1084
|
`).join(`
|
|
1084
1085
|
`),o=await E(this.config,{query:`
|
|
@@ -1093,11 +1094,11 @@ query getReposForCurrentUser($after: String) {
|
|
|
1093
1094
|
hasNextPage
|
|
1094
1095
|
}
|
|
1095
1096
|
nodes {
|
|
1096
|
-
${
|
|
1097
|
+
${dr}
|
|
1097
1098
|
}
|
|
1098
1099
|
}
|
|
1099
1100
|
}
|
|
1100
|
-
`,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(ke(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(gr)}}async getGroupsForCurrentUser(t={},e={}){let r=new URL(`${U(this.config,e)}/groups`);r.searchParams.set("top_level_only",(t.topLevelOnly??!0).toString()),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("per_page",C.toString());let n=await this.config.request({url:r.toString(),headers:R(e.token||this.config.token)});return{pageInfo:
|
|
1101
|
+
`,variables:{after:t.cursor}},e);if(!r.body.data?.projects)throw new Error(ke(r.body.errors)||r.statusText||"Unknown error");let n=r.body.data?.projects?.nodes||[];return{pageInfo:r.body.data?.projects?.pageInfo,data:n.map(gr)}}async getGroupsForCurrentUser(t={},e={}){let r=new URL(`${U(this.config,e)}/groups`);r.searchParams.set("top_level_only",(t.topLevelOnly??!0).toString()),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("per_page",C.toString());let n=await this.config.request({url:r.toString(),headers:R(e.token||this.config.token)});return{pageInfo:pr(n.headers),data:n.body.map(o=>({id:o.id.toString(),path:o.path,fullPath:o.full_path,name:o.name,webUrl:o.web_url}))}}async getRefs(t,e,r={}){let n=_(e.repo),o=new URL(`${U(this.config,r)}/projects/${encodeURIComponent(n)}/repository/${t}`);o.searchParams.set("page",e.page?.toString()||"1"),o.searchParams.set("per_page",C.toString());let i=await this.config.request({url:o.toString(),headers:R(r.token||this.config.token)});return{pageInfo:pr(i.headers),data:i.body.map(a=>({name:a.name,commit:{oid:a.commit.id,authoredDate:new Date(a.commit.authored_date),committedDate:new Date(a.commit.committed_date)}}))}}async getBranches(t,e={}){return this.getRefs("branches",t,e)}async getTags(t,e={}){return this.getRefs("tags",t,e)}async getBlame(t,e={}){let r=_(t.repo),n=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/blame`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)}),i=0;return{data:{ranges:o.body.map(a=>{let u=i+1;return i+=a.lines.length,{startingLine:u,endingLine:i,commit:{oid:a.commit.id,parentOids:a.commit.parent_ids,authoredDate:new Date(a.commit.authored_date),author:{name:a.commit.author_name,email:a.commit.author_email,avatarUrl:null},committedDate:new Date(a.commit.committed_date),committer:{name:a.commit.committer_name,email:a.commit.committer_email,avatarUrl:null},message:a.commit.message,fileCount:null,additions:null,deletions:null}}})}}}async getPullRequestsForUser(t,e={}){let r="";t.repo?.id?r=`projectId:"${t.repo.id}"`:t.repo?.namespace&&t.repo?.name&&(r=`projectPath:"${t.repo.namespace}/${t.repo.name}"`);let n=Oo[t.association],o=Ts(t.states),i=D(t.pageSize,{fallback:le,max:le}),a=await E(this.config,{query:`
|
|
1101
1102
|
query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
|
|
1102
1103
|
user(username: $username) {
|
|
1103
1104
|
${n}(${o} first: ${i} after:$cursor labels: $labelNames${r?` ${r}`:""}) {
|
|
@@ -1106,12 +1107,12 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
|
|
|
1106
1107
|
hasNextPage
|
|
1107
1108
|
}
|
|
1108
1109
|
nodes {
|
|
1109
|
-
${
|
|
1110
|
+
${mr(!0,!0,!0)}
|
|
1110
1111
|
}
|
|
1111
1112
|
}
|
|
1112
1113
|
}
|
|
1113
1114
|
}
|
|
1114
|
-
`,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!a.body.data)throw new Error(ke(a.body.errors)||a.statusText||"Unknown error");if(!a.body.data.user)throw new Error("User not found");let u=a.body.data.user[n];if(!u)throw new Error("Unexpected response");let l=u.nodes?.filter(d=>t.includeFromArchivedRepos||!d.project.archived).map(d=>
|
|
1115
|
+
`,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!a.body.data)throw new Error(ke(a.body.errors)||a.statusText||"Unknown error");if(!a.body.data.user)throw new Error("User not found");let u=a.body.data.user[n];if(!u)throw new Error("Unexpected response");let l=u.nodes?.filter(d=>t.includeFromArchivedRepos||!d.project.archived).map(d=>hr(d,xe(d.project),d.sourceProject?xe(d.sourceProject):null,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))||[];return{pageInfo:u.pageInfo,data:x(l,t.states)}}async getPullRequestsAssociatedWithUser(t,e={}){let[r,n,o]=t.cursor?.split(";")||[void 0,void 0,void 0],i=r?.split("-")||[],a=n?.split("-")||[],u=o?.split("-")||[],l=[],d=[],p=[],c=0;do{let $=t.repos&&t.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:i[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,states:t.states,...$&&{repo:$}},e)),a[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,states:t.states,...$&&{repo:$}},e)),u[c]==="null"?p.push(null):p.push(this.getPullRequestsForUser({username:t.username,association:"reviewRequested",cursor:u[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,states:t.states,...$&&{repo:$}},e)),c++}while(c<(t.repos?.length||0));let m=[l,d,p].flat(),g=await Promise.all(m),h={},y=[],f=$=>{h[$.id]||(h[$.id]=!0,y.push($))},P=!1,L=g.map(($,w)=>{let S="";return $&&$.data.forEach(f),$?.pageInfo.hasNextPage?(P=!0,S+=`${$.pageInfo.endCursor||"null"}`):S+="null",t.repos?.length&&(w+1)%t.repos.length!==0?S+="-":w+1<g.length&&(S+=";"),S}).join("");return{pageInfo:{hasNextPage:P,endCursor:L},data:y}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=t||{},u={},l=[],d=[],p=(c,m,g)=>{l.push(`$${c}: ${g}`),d.push(`${c}: $${c}`),u[c]=m};return e&&p("updatedBefore",e,"Time"),n&&p("authorUsername",n,"String"),o&&o.length&&(o.length===1?p("assigneeUsername",o[0],"String"):p("assigneeUsernames",o,"[String!]")),i&&p("labelName",i,"[String]"),r!=null&&p("draft",r,"Boolean"),a&&p("reviewerUsername",a,"String"),{variables:u,variableTypes:l,mergeRequestArguments:d}}async getPullRequestsForRepoBase(t,e={},r){let{cursor:n,repo:o}=t||{},i=_(o),a=Ts(t.states),u=D(t.pageSize,{fallback:le,max:le}),{variables:l,variableTypes:d,mergeRequestArguments:p}=this.getVariablesForPullRequests(t),c={fullPath:i,...l},m=await E(this.config,{query:`
|
|
1115
1116
|
query getPullRequestsForRepo(
|
|
1116
1117
|
$fullPath: ID!
|
|
1117
1118
|
$after: String
|
|
@@ -1136,7 +1137,7 @@ query getPullRequestsForRepo(
|
|
|
1136
1137
|
hasNextPage
|
|
1137
1138
|
}
|
|
1138
1139
|
nodes {
|
|
1139
|
-
${
|
|
1140
|
+
${mr(!1,!0,!0)}
|
|
1140
1141
|
sourceProject {
|
|
1141
1142
|
${Ne}
|
|
1142
1143
|
}
|
|
@@ -1144,7 +1145,7 @@ query getPullRequestsForRepo(
|
|
|
1144
1145
|
}
|
|
1145
1146
|
}
|
|
1146
1147
|
}
|
|
1147
|
-
`,variables:{...c,after:n}},e),g=[],h=m.body.data?.project;if(!r&&h?.archived)return{pageInfo:null,data:[]};let y=
|
|
1148
|
+
`,variables:{...c,after:n}},e),g=[],h=m.body.data?.project;if(!r&&h?.archived)return{pageInfo:null,data:[]};let y=st(h||{id:"",fullPath:"",webUrl:""});return(h?.mergeRequests?.nodes||[]).forEach(P=>{let v=P.sourceProject?xe(P.sourceProject):null;g.push(hr(P,y,v,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.mergeRequests?.pageInfo,data:x(g,t.states)}}async getPullRequestsForRepo(t,e={}){return this.getPullRequestsForRepoBase(t,e,!1)}async getPullRequestsForRepos(t,e={}){let{repos:r,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l}=t;return{data:(await Promise.all(r.map(p=>this.getPullRequestsForRepoBase({repo:p,assigneeLogins:n,updatedBefore:o,authorLogin:i,labelNames:a,isDraft:u,reviewRequestedLogin:l,states:t.states,pageSize:t.pageSize},e,t.includeFromArchivedRepos??!1)))).flatMap(p=>p.data)}}async closePullRequest(t,e={}){let{pullRequest:r}=t,n=`mutation ClosePullRequest($fullPath: ID!, $pullRequestId: String!) {
|
|
1148
1149
|
mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
|
|
1149
1150
|
errors,
|
|
1150
1151
|
mergeRequest {
|
|
@@ -1209,18 +1210,18 @@ query getPullRequestsForRepo(
|
|
|
1209
1210
|
id
|
|
1210
1211
|
}
|
|
1211
1212
|
}
|
|
1212
|
-
}`;if(!(await E(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(t,e={}){let r=
|
|
1213
|
+
}`;if(!(await E(this.config,{query:i,variables:{fullPath:`${r.repository.owner.login}/${r.repository.name}`,pullRequestId:r.number.toString(),labelGraphQLIds:o}},e)).body.data?.mergeRequestSetLabels?.mergeRequest?.id)throw new Error("Could not set pull request labels")}async getIssue(t,e={}){let r=Fo(t),n=await E(this.config,{query:`
|
|
1213
1214
|
query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
1214
1215
|
project(fullPath: $projectId) {
|
|
1215
1216
|
id
|
|
1216
1217
|
fullPath
|
|
1217
1218
|
webUrl
|
|
1218
1219
|
issue(iid: $issueNumber) {
|
|
1219
|
-
${
|
|
1220
|
+
${cr}
|
|
1220
1221
|
}
|
|
1221
1222
|
}
|
|
1222
1223
|
}
|
|
1223
|
-
`,variables:{issueNumber:t.number,projectId:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${t.number} not found`);return{data:
|
|
1224
|
+
`,variables:{issueNumber:t.number,projectId:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);if(!n.body.data?.project?.issue)throw new Error(`Issue ${t.number} not found`);return{data:fr(n.body.data.project.issue,st(n.body.data.project),this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getVariablesForIssues(t){let{updatedBefore:e,authorLogin:r,assigneeLogins:n,labelNames:o}=t||{},i={},a=[],u=[],l=(d,p,c)=>{a.push(`$${d}: ${c}`),u.push(`${d}: $${d}`),i[d]=p};return e&&l("updatedBefore",e,"Time"),r&&l("authorUsername",r,"String"),n&&n.length&&(n.length===1?l("assigneeUsername",n[0],"String"):l("assigneeUsernames",n,"[String!]")),o&&l("labelName",o,"[String]"),{variables:i,variableTypes:a,issueArguments:u}}async getIssuesForRepo(t,e={}){let{cursor:r,repo:n}=t||{},o=_(n),i=Os(t.states),a=D(t.pageSize,{fallback:le,max:le}),{variables:u,variableTypes:l,issueArguments:d}=this.getVariablesForIssues(t),p={fullPath:o,...u},c=`
|
|
1224
1225
|
query GetIssuesFromProject(
|
|
1225
1226
|
$fullPath: ID!
|
|
1226
1227
|
$after: String
|
|
@@ -1240,7 +1241,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1240
1241
|
${d.length?d.join(" "):""}
|
|
1241
1242
|
) {
|
|
1242
1243
|
nodes {
|
|
1243
|
-
${
|
|
1244
|
+
${cr}
|
|
1244
1245
|
}
|
|
1245
1246
|
pageInfo {
|
|
1246
1247
|
endCursor
|
|
@@ -1248,7 +1249,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1248
1249
|
}
|
|
1249
1250
|
}
|
|
1250
1251
|
}
|
|
1251
|
-
}`,m=await E(this.config,{query:c,variables:{...p,after:r}},e),g=[],h=m.body.data?.project,y=
|
|
1252
|
+
}`,m=await E(this.config,{query:c,variables:{...p,after:r}},e),g=[],h=m.body.data?.project,y=st(h||{id:"",fullPath:"",webUrl:""});return(h?.issues?.nodes||[]).forEach(P=>{g.push(fr(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:g.sort((P,v)=>(P.updatedDate||P.createdDate).getTime()-(v.updatedDate||v.createdDate).getTime())}}async getIssuesForRepos(t,e={}){let{cursor:r}=t||{},n=Os(t.states),o=D(t.pageSize,{fallback:le,max:le}),i=t.repoIds.map(h=>h.toString().startsWith(Re)?h:`${Re}${h}`),{variables:a,variableTypes:u,issueArguments:l}=this.getVariablesForIssues(t),d={projectIds:i,...a},p=`
|
|
1252
1253
|
query GetIssuesFromProject(
|
|
1253
1254
|
$projectIds: [ID!]
|
|
1254
1255
|
$after: String
|
|
@@ -1274,12 +1275,12 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
|
|
|
1274
1275
|
${l.length?l.join(" "):""}
|
|
1275
1276
|
) {
|
|
1276
1277
|
nodes {
|
|
1277
|
-
${
|
|
1278
|
+
${cr}
|
|
1278
1279
|
}
|
|
1279
1280
|
}
|
|
1280
1281
|
}
|
|
1281
1282
|
}
|
|
1282
|
-
}`,c=await E(this.config,{query:p,variables:{...d,after:r}},e),m=[];return(c.body.data?.projects?.nodes||[]).forEach(h=>{if(!t.includeFromArchivedRepos&&h.archived)return;let y=
|
|
1283
|
+
}`,c=await E(this.config,{query:p,variables:{...d,after:r}},e),m=[];return(c.body.data?.projects?.nodes||[]).forEach(h=>{if(!t.includeFromArchivedRepos&&h.archived)return;let y=st(h);(h.issues?.nodes||[]).forEach(P=>m.push(fr(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:c.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:m.sort((h,y)=>(h.updatedDate||h.createdDate).getTime()-(y.updatedDate||y.createdDate).getTime())}}async getIssuesForCurrentUser(t={},e={}){let r=t.scope??"assigned_to_me",{assigneeUsername:n,authorUsername:o}=t,i=t.page?.toString()||"1",a=D(t.pageSize,{fallback:C,max:C}),u=new URL(`${U(this.config,e)}/issues`);u.searchParams.set("scope",r),u.searchParams.set("state","opened"),n&&u.searchParams.set("assignee_username",n),o&&u.searchParams.set("author_username",o),u.searchParams.set("page",i),u.searchParams.set("per_page",a.toString());let l=await this.config.request({url:u.toString(),headers:R(e.token||this.config.token)});return{pageInfo:pr(l.headers),data:l.body.map(d=>ti(d,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}}async setIssueState(t,e={}){let{issue:r,state:n}=t;if(!r.repository)throw new Error('GitLab requires "repository" for this function.');let o=`mutation SetIssueState($fullPath: ID!, $issueId: String!, $status: IssueStateEvent!) {
|
|
1283
1284
|
updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
|
|
1284
1285
|
issue {
|
|
1285
1286
|
id
|
|
@@ -1319,7 +1320,7 @@ query getLabelsForRepo(
|
|
|
1319
1320
|
webUrl
|
|
1320
1321
|
milestones(after: $after) {
|
|
1321
1322
|
nodes {
|
|
1322
|
-
${
|
|
1323
|
+
${yr}
|
|
1323
1324
|
}
|
|
1324
1325
|
pageInfo {
|
|
1325
1326
|
endCursor
|
|
@@ -1328,7 +1329,7 @@ query getLabelsForRepo(
|
|
|
1328
1329
|
}
|
|
1329
1330
|
}
|
|
1330
1331
|
}
|
|
1331
|
-
`,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>
|
|
1332
|
+
`,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.milestones?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.milestones?.nodes?.map(a=>qr(a,i.body.data?.project?.webUrl||""))??[]}}async getLabelsForRepo(t,e={}){let{repo:{namespace:r,name:n},cursor:o}=t,i=await E(this.config,{query:`
|
|
1332
1333
|
query getLabelsForRepo(
|
|
1333
1334
|
$fullPath: ID!
|
|
1334
1335
|
$after: String
|
|
@@ -1338,7 +1339,7 @@ query getLabelsForRepo(
|
|
|
1338
1339
|
) {
|
|
1339
1340
|
labels(after: $after) {
|
|
1340
1341
|
nodes {
|
|
1341
|
-
${
|
|
1342
|
+
${Pr}
|
|
1342
1343
|
}
|
|
1343
1344
|
pageInfo {
|
|
1344
1345
|
endCursor
|
|
@@ -1347,28 +1348,28 @@ query getLabelsForRepo(
|
|
|
1347
1348
|
}
|
|
1348
1349
|
}
|
|
1349
1350
|
}
|
|
1350
|
-
`,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(
|
|
1351
|
+
`,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(wr)??[]}}async getTreeForRepo(t,e={}){let r=_(t.repo),n=new URL(t.cursor??`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/tree`);n.searchParams.set("per_page","10000"),n.searchParams.set("recursive","true"),n.searchParams.set("pagination","keyset"),n.searchParams.set("ref",t.branch);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)}),i=o.headers.link;return{data:o.body.map(Mo),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(t,e={}){let r=_(t.repo),o=(await E(this.config,{query:`
|
|
1351
1352
|
query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
|
|
1352
1353
|
project(fullPath: $fullPath) {
|
|
1353
1354
|
${Ne}
|
|
1354
1355
|
archived
|
|
1355
1356
|
mergeRequest(iid: $iid) {
|
|
1356
|
-
${
|
|
1357
|
+
${mr(!1,!0,!0)}
|
|
1357
1358
|
sourceProject {
|
|
1358
1359
|
${Ne}
|
|
1359
1360
|
}
|
|
1360
1361
|
}
|
|
1361
1362
|
}
|
|
1362
1363
|
}
|
|
1363
|
-
`,variables:{fullPath:r,iid:t.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=xe(o),u=i.sourceProject?xe(i.sourceProject):null;return{data:mr(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(t,e,r){let n=_(t);return`${U(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${e}`}async getPullRequestDescription(t,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(t.repo,t.number,e),headers:R(e.token||this.config.token)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(t,e={}){return{data:{description:(await this.config.request({method:"PUT",url:this.getMergeRequestUrl(t.repo,t.number,e),headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({description:t.description})})).body?.description??t.description}}}async getFileContents(t,e={}){let r=_(t.repo),n=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/raw`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(t,e={}){let r=_(t.repo),{page:n,perPage:o}=Jo(t.cursor,C),i=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/merge_requests/${t.pullRequestNumber}/notes`);i.searchParams.set("page",n.toString()),i.searchParams.set("per_page",o.toString()),i.searchParams.set("sort","asc"),i.searchParams.set("order_by","created_at");let a=await this.config.request({url:i.toString(),headers:R(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,d={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestNumber},p=a.body.filter(g=>!g.system&&!g.position).map(g=>fr(g,u,l,d)),c=!!a.headers["x-next-page"],m=c?Vo({page:n+1,perPage:o}):null;return{data:p,pageInfo:{endCursor:m,hasNextPage:c}}}async getReviewsForPullRequest(t,e={}){let r=_(t.repo),n=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=R(e.token||this.config.token),a=U(this.config,e),u=encodeURIComponent(r),[l,d]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${t.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(r,t.pullRequestId,e)]),p=(l.body.approved_by??[]).map(g=>g?.user).filter(g=>!!g).map(g=>{let h=Gs(g,n,o),y=`approval-${g.id}`;return{author:h,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),c={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestId},m=d.filter(g=>g.notes.some(h=>!h.system&&!!h.position)).map(g=>{let h=g.notes.filter(w=>!w.system),f=h.filter(w=>!!w.position)[0];if(!f)return null;let P=h.filter(w=>w.id!==f.id).map(w=>fr(w,n,o,c)),$={...fr(f,n,o,c),diffLines:[],filename:f.position?.new_path??f.position?.old_path??"",line:f.position?.new_line??f.position?.old_line??null,startLine:f.position?.line_range?.start?.new_line??null,side:Zo(f.position),isOutdated:!1,isResolved:!!g.resolved,threadId:g.id,replies:P};return{author:f.author?Gs(f.author,n,o):null,body:f.body??"",createdAt:f.created_at?new Date(f.created_at):null,id:g.id,graphQLId:g.id,reviewComments:[$],url:""}}).filter(g=>g!==null);return{data:[...p,...m]}}async getPullRequestDiff(t,e={}){let r=_(t.repo),n=encodeURIComponent(r),o=U(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${n}/merge_requests/${t.pullRequestId}/diffs`,e,{perPage:zo,maxPages:Mo})).map(Yo).join("")}async getMergeBase(t,e={}){let r=_(t.repo),n=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/merge_base`);n.searchParams.append("refs[]",t.base),n.searchParams.append("refs[]",t.head);let i=(await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)})).body?.id;if(!i)throw new Error("No merge base found between the specified commits.");return{data:i}}async fetchAllMergeRequestDiscussions(t,e,r){let n=U(this.config,r),o=encodeURIComponent(t);return this.fetchAllPagedGitLabREST(`${n}/projects/${o}/merge_requests/${e}/discussions`,r)}async fetchAllPagedGitLabREST(t,e,{perPage:r=C,maxPages:n=50}={}){let o=R(e.token||this.config.token),i=[],a=1;for(;a<=n;){let u=new URL(t);u.searchParams.set("page",a.toString()),u.searchParams.set("per_page",r.toString());let l=await this.config.request({url:u.toString(),headers:o});i.push(...l.body);let d=l.headers["x-next-page"];if(!d)break;let p=parseInt(`${d}`,10);if(Number.isNaN(p)||p<=a)break;a=p}return i}async addCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`,i=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:n})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n,path:o,line:i,side:a="RIGHT",threadId:u}=t;if(!n?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${r.repository.owner.login}/${r.repository.name}`,d=encodeURIComponent(l),p=U(this.config,e),c={...R(e.token||this.config.token),"Content-Type":"application/json"};if(u){let P=await this.config.request({method:"POST",url:`${p}/projects/${d}/merge_requests/${r.number}/discussions/${encodeURIComponent(u)}/notes`,headers:c,body:JSON.stringify({body:n})});return P.body?.id!=null?Ir(r.repository.owner.login,r.repository.name,r.number,P.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let g=(await this.config.request({url:`${p}/projects/${d}/merge_requests/${r.number}`,headers:R(e.token||this.config.token)})).body?.diff_refs;if(!g?.base_sha||!g?.start_sha||!g?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let h={position_type:"text",base_sha:g.base_sha,start_sha:g.start_sha,head_sha:g.head_sha,new_path:o,old_path:o};a==="RIGHT"?h.new_line=i:h.old_line=i;let f=(await this.config.request({method:"POST",url:`${p}/projects/${d}/merge_requests/${r.number}/discussions`,headers:c,body:JSON.stringify({body:n,position:h})})).body?.notes?.[0]?.id;return f!=null?Ir(r.repository.owner.login,r.repository.name,r.number,f):void 0}getNoteUrl(t,e){if(!t)throw new Error('GitLab requires "commentId" for this function.');let{namespace:r,name:n,mergeRequestIid:o,noteId:i}=ei(t);return`${U(this.config,e)}/projects/${encodeURIComponent(`${r}/${n}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(t,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(t,e),headers:R(e.token||this.config.token)})}async deleteComment(t,e={}){await this.deleteNote(t.commentId,e)}async deleteInlineComment(t,e={}){await this.deleteNote(t.commentId,e)}async editNote(t,e,r){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(t,r),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async editInlineComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async resolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!0,e)}async unresolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!1,e)}async setReviewThreadResolved(t,e,r){if(!t.repo||t.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!t.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let n=_(t.repo),o=new URL(`${U(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${t.pullRequestNumber}/discussions/${encodeURIComponent(t.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:R(r.token||this.config.token)})}async approvePullRequest(t,e={}){let{pullRequest:r,comment:n}=t,o=`${r.repository.owner.login}/${r.repository.name}`,i=U(this.config,e),a=encodeURIComponent(o),u=R(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${r.number}/approve`,method:"POST",headers:u}),n&&n.trim()!==""&&await this.postMergeRequestNote(o,r.number,n,e)}async commentOnPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;await this.postMergeRequestNote(o,r.number,n,e)}async requestPullRequestChanges(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;if(!await this.tryRequestChangesMutation(o,r.number,e)){let u=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}`,l=R(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:l})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:l})}await this.postMergeRequestNote(o,r.number,n,e)}async tryRequestChangesMutation(t,e,r){let n=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
|
|
1364
|
+
`,variables:{fullPath:r,iid:t.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=xe(o),u=i.sourceProject?xe(i.sourceProject):null;return{data:hr(i,a,u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)}}getMergeRequestUrl(t,e,r){let n=_(t);return`${U(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${e}`}async getPullRequestDescription(t,e={}){try{return{data:{description:(await this.config.request({url:this.getMergeRequestUrl(t.repo,t.number,e),headers:R(e.token||this.config.token)})).body?.description??""}}}catch{return{data:{description:null}}}}async setPullRequestDescription(t,e={}){return{data:{description:(await this.config.request({method:"PUT",url:this.getMergeRequestUrl(t.repo,t.number,e),headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({description:t.description})})).body?.description??t.description}}}async getFileContents(t,e={}){let r=_(t.repo),n=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/files/${encodeURIComponent(t.path)}/raw`);n.searchParams.set("ref",t.ref);let o=await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)});return{data:new Blob([o.body])}}async getCommentsForPullRequest(t,e={}){let r=_(t.repo),{page:n,perPage:o}=Yo(t.cursor,C),i=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/merge_requests/${t.pullRequestNumber}/notes`);i.searchParams.set("page",n.toString()),i.searchParams.set("per_page",o.toString()),i.searchParams.set("sort","asc"),i.searchParams.set("order_by","created_at");let a=await this.config.request({url:i.toString(),headers:R(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,d={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestNumber},p=a.body.filter(g=>!g.system&&!g.position).map(g=>Rr(g,u,l,d)),c=!!a.headers["x-next-page"],m=c?Zo({page:n+1,perPage:o}):null;return{data:p,pageInfo:{endCursor:m,hasNextPage:c}}}async getReviewsForPullRequest(t,e={}){let r=_(t.repo),n=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=R(e.token||this.config.token),a=U(this.config,e),u=encodeURIComponent(r),[l,d]=await Promise.all([this.config.request({url:`${a}/projects/${u}/merge_requests/${t.pullRequestId}/approvals`,headers:i}),this.fetchAllMergeRequestDiscussions(r,t.pullRequestId,e)]),p=(l.body.approved_by??[]).map(g=>g?.user).filter(g=>!!g).map(g=>{let h=_s(g,n,o),y=`approval-${g.id}`;return{author:h,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),c={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestId},m=d.filter(g=>g.notes.some(h=>!h.system&&!!h.position)).map(g=>{let h=g.notes.filter(w=>!w.system),f=h.filter(w=>!!w.position)[0];if(!f)return null;let P=h.filter(w=>w.id!==f.id).map(w=>Rr(w,n,o,c)),L={...Rr(f,n,o,c),diffLines:[],filename:f.position?.new_path??f.position?.old_path??"",line:f.position?.new_line??f.position?.old_line??null,startLine:f.position?.line_range?.start?.new_line??null,side:ri(f.position),isOutdated:!1,isResolved:!!g.resolved,threadId:g.id,replies:P};return{author:f.author?_s(f.author,n,o):null,body:f.body??"",createdAt:f.created_at?new Date(f.created_at):null,id:g.id,graphQLId:g.id,reviewComments:[L],url:""}}).filter(g=>g!==null);return{data:[...p,...m]}}async getPullRequestDiff(t,e={}){let r=_(t.repo),n=encodeURIComponent(r),o=U(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${n}/merge_requests/${t.pullRequestId}/diffs`,e,{perPage:Vo,maxPages:Jo})).map(si).join("")}async getMergeBase(t,e={}){let r=_(t.repo),n=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/repository/merge_base`);n.searchParams.append("refs[]",t.base),n.searchParams.append("refs[]",t.head);let i=(await this.config.request({url:n.toString(),headers:R(e.token||this.config.token)})).body?.id;if(!i)throw new Error("No merge base found between the specified commits.");return{data:i}}async fetchAllMergeRequestDiscussions(t,e,r){let n=U(this.config,r),o=encodeURIComponent(t);return this.fetchAllPagedGitLabREST(`${n}/projects/${o}/merge_requests/${e}/discussions`,r)}async fetchAllPagedGitLabREST(t,e,{perPage:r=C,maxPages:n=50}={}){let o=R(e.token||this.config.token),i=[],a=1;for(;a<=n;){let u=new URL(t);u.searchParams.set("page",a.toString()),u.searchParams.set("per_page",r.toString());let l=await this.config.request({url:u.toString(),headers:o});i.push(...l.body);let d=l.headers["x-next-page"];if(!d)break;let p=parseInt(`${d}`,10);if(Number.isNaN(p)||p<=a)break;a=p}return i}async addCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when adding a comment to a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`,i=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}/notes`;if(!(await this.config.request({method:"POST",url:i,headers:{...R(e.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:n})})).body?.id)throw new Error("Could not add comment to pull request")}async addInlineCommentToPullRequest(t,e={}){let{pullRequest:r,comment:n,path:o,line:i,side:a="RIGHT",threadId:u}=t;if(!n?.trim())throw new Error("GitLab requires a comment when adding an inline comment to a pull request.");let l=`${r.repository.owner.login}/${r.repository.name}`,d=encodeURIComponent(l),p=U(this.config,e),c={...R(e.token||this.config.token),"Content-Type":"application/json"};if(u){let P=await this.config.request({method:"POST",url:`${p}/projects/${d}/merge_requests/${r.number}/discussions/${encodeURIComponent(u)}/notes`,headers:c,body:JSON.stringify({body:n})});return P.body?.id!=null?br(r.repository.owner.login,r.repository.name,r.number,P.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let g=(await this.config.request({url:`${p}/projects/${d}/merge_requests/${r.number}`,headers:R(e.token||this.config.token)})).body?.diff_refs;if(!g?.base_sha||!g?.start_sha||!g?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let h={position_type:"text",base_sha:g.base_sha,start_sha:g.start_sha,head_sha:g.head_sha,new_path:o,old_path:o};a==="RIGHT"?h.new_line=i:h.old_line=i;let f=(await this.config.request({method:"POST",url:`${p}/projects/${d}/merge_requests/${r.number}/discussions`,headers:c,body:JSON.stringify({body:n,position:h})})).body?.notes?.[0]?.id;return f!=null?br(r.repository.owner.login,r.repository.name,r.number,f):void 0}getNoteUrl(t,e){if(!t)throw new Error('GitLab requires "commentId" for this function.');let{namespace:r,name:n,mergeRequestIid:o,noteId:i}=ni(t);return`${U(this.config,e)}/projects/${encodeURIComponent(`${r}/${n}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(t,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(t,e),headers:R(e.token||this.config.token)})}async deleteComment(t,e={}){await this.deleteNote(t.commentId,e)}async deleteInlineComment(t,e={}){await this.deleteNote(t.commentId,e)}async editNote(t,e,r){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(t,r),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async editInlineComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async resolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!0,e)}async unresolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!1,e)}async setReviewThreadResolved(t,e,r){if(!t.repo||t.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!t.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let n=_(t.repo),o=new URL(`${U(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${t.pullRequestNumber}/discussions/${encodeURIComponent(t.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:R(r.token||this.config.token)})}async approvePullRequest(t,e={}){let{pullRequest:r,comment:n}=t,o=`${r.repository.owner.login}/${r.repository.name}`,i=U(this.config,e),a=encodeURIComponent(o),u=R(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${r.number}/approve`,method:"POST",headers:u}),n&&n.trim()!==""&&await this.postMergeRequestNote(o,r.number,n,e)}async commentOnPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;await this.postMergeRequestNote(o,r.number,n,e)}async requestPullRequestChanges(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;if(!await this.tryRequestChangesMutation(o,r.number,e)){let u=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}`,l=R(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:l})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:l})}await this.postMergeRequestNote(o,r.number,n,e)}async tryRequestChangesMutation(t,e,r){let n=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
|
|
1364
1365
|
mergeRequestRequestChanges(input: { projectPath: $fullPath, iid: $pullRequestId }) {
|
|
1365
1366
|
errors
|
|
1366
1367
|
mergeRequest {
|
|
1367
1368
|
id
|
|
1368
1369
|
}
|
|
1369
1370
|
}
|
|
1370
|
-
}`,o=await E(this.config,{query:n,variables:{fullPath:t,pullRequestId:e.toString()}},r),i=o.body.errors;if(i?.length){if(i.some(
|
|
1371
|
-
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,d=!o,p=d?Bs:Ns,c=new URL(`${le(s,r,o)}${p}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",it.toString()),c.searchParams.set("fields",qr.join(",")),c.searchParams.set("expand","transitions"),n&&(d?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let m=await s.request({url:c.toString(),headers:R(r.token||s.token)}),g=m.body.issues.map(f=>vr(f,a,e,o)),h=!1,y="";return d?(h=g.length==it,y=(parseInt(n??"0",10)+g.length).toString()):(h=!!m.body.nextPageToken,y=m.body.nextPageToken??null),{data:g,pageInfo:{hasNextPage:h,endCursor:y}}},js=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=L(t?.pageSize,{fallback:it,max:it}),l=[...qr],d=a?.Sprint;d&&l.push(d);let p=!o,c=p?Bs:Ns,m=new URL(`${le(s,r,o)}${c}`);m.searchParams.set("jql",i.join(" AND ")),m.searchParams.set("maxResults",u.toString()),m.searchParams.set("fields",l.join(",")),m.searchParams.set("expand","transitions"),n&&(p?m.searchParams.set("startAt",n):m.searchParams.set("nextPageToken",n));let g=await s.request({url:m.toString(),headers:R(r.token||s.token)}),h=g.body.issues.map(P=>vr(P,a,e,o)),y=!1,f="";if(p){let P=parseInt(n??"0",10),v=typeof g.body.startAt=="number"?g.body.startAt:Number.isNaN(P)?0:P,$=g.body.total;y=typeof $=="number"?v+h.length<$:h.length===u,f=(v+h.length).toString()}else y=!!g.body.nextPageToken,f=g.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},dt=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:d,fields:p}=t||{},c=[`project = "${l}"`],m=xs(t.states);return m&&c.push(m),o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(g=>c.push(`labels = "${g}"`)),js(s,{resourceId:d,jql:c,cursor:u,fields:p,pageSize:t.pageSize},e,r)},ct=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:d,fields:p}=t||{},m=["("+l.map(h=>`project = "${h}"`).join(" OR ")+")"],g=xs(t.states);return g&&m.push(g),o&&m.push(`creator in ("${o}")`),n&&n.length!==0&&m.push(`assignee in ("${n.join('", "')}")`),i&&m.push(`comment ~ "${i}"`),a&&a.forEach(h=>m.push(`labels = "${h}"`)),js(s,{resourceId:d,jql:m,fields:p,cursor:u,pageSize:t.pageSize},e,r)},gt=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${le(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},mt=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${le(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},ht=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${le(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},ft=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${le(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:R(e.token||s.token)})).body}};var Be="https://api.atlassian.com/ex/jira",Er=100,ui=5,Ce=class extends M{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await ut(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||Be}/${e.resourceId}/rest/api/2/myself`,headers:R(r.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||Be}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Er.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},metadata:ye("complete"),data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,r={}){let{successes:n,metadata:o}=await te(e.resourceIds,{run:a=>Jr(u=>this.getJiraProjectsForResource({resourceId:a,cursor:u},r)),failureScope:a=>({providerId:"jira",resourceId:a}),concurrency:ui}),i=[];return n.forEach(({result:a})=>{i.push(...a)}),{data:i,metadata:o}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||Be}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Er.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},metadata:ye("complete"),data:l.body.filter(d=>d.accountType!=="app"&&d.active).map(d=>at(d,a,!1))}}async getComponentsForJiraProject(e,r={}){return await ft(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await lt(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await dt(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await ct(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await pt(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await ht(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${r.baseUrl||Be}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await mt(this.config,e,r)}async setIssueLabels(e,r={}){await gt(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||Be}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Er.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var De=class extends F{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await ut(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:R(e?.token||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:R(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await lt(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await dt(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await ct(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await pt(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await ht(this.config,e,r)}async setIssueLabels(e,r={}){await gt(this.config,e,r)}async setIssueComponents(e,r={}){await mt(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:R(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await ft(this.config,e,r)}};var Cr=100,Rt=class{constructor(){this.set=new Set;this.arr=[]}push(...t){let e=t.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}},oe=async(s,t,e,r)=>{let n=t.token||s.token;if(!n)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},Sr=s=>s?s instanceof Date?s:new Date(s):null,li=`
|
|
1371
|
+
}`,o=await E(this.config,{query:n,variables:{fullPath:t,pullRequestId:e.toString()}},r),i=o.body.errors;if(i?.length){if(i.some(Qo))return!1;throw new Error(`Could not request pull request changes: ${ke(i)}`)}let a=o.body.data?.mergeRequestRequestChanges;if(a?.errors&&a.errors.length>0)throw new Error(`Could not request pull request changes: ${a.errors.join(", ")}`);if(!a?.mergeRequest?.id)throw new Error("Could not request pull request changes");return!0}async postMergeRequestNote(t,e,r,n){let o=U(this.config,n),i=encodeURIComponent(t),a=R(n.token||this.config.token);await this.config.request({url:`${o}/projects/${i}/merge_requests/${e}/notes`,method:"POST",headers:{...a,"Content-Type":"application/json"},body:JSON.stringify({body:r})})}};var oi="https://api.atlassian.com/ex/jira",at=100,js=s=>{if(!s||s.length===0)return"statusCategory != Done";let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?null:r?"statusCategory = Done":"statusCategory != Done"},vr=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Fs="/rest/api/2/search/jql",Qs="/rest/api/2/search",Er=(s,t,e,r)=>{let n=s.fields.assignee,o=!r,i=(s.fields[t?.Sprint??""]??[]).filter(a=>typeof a=="object");return{id:s.id,commentCount:s.fields.comment.comments.length,number:s.key,title:s.fields.summary,url:e?`${e}/browse/${s.key}`:null,closedDate:null,createdDate:new Date(s.fields.created),author:ut(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[ut(n,e,o)]:[],description:s.fields.description,repository:null,project:{name:s.fields.project.name,resourceId:r??null,key:s.fields.project.key,namespace:null,id:s.fields.project.id},state:li(s.fields.status),statusTransitions:s.transitions?.map(ii)??[],components:s.fields.components?.map(ai)??[],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(pi),fixVersions:s.fields.fixVersions.map(di)}},ii=s=>{let t;switch(s.to.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{name:s.name,id:s.id,to:{id:s.to.id,name:s.to.name,color:s.to.statusCategory.colorName,category:t}}},ai=s=>({description:s.description??null,id:s.id,name:s.name}),ui=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,ut=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:ui(s,t,e)}),li=s=>{let t;switch(s.statusCategory.name){case"To Do":t="TO_DO";break;case"In Progress":t="IN_PROGRESS";break;default:t="DONE";break}return{id:s.id,name:s.name,color:s.statusCategory.colorName,category:t}},pi=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}),di=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),pe=(s,t,e)=>e?`${t.baseUrl||oi}/${e}`:`${t?.baseUrl||s.baseUrl}`,lt=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${pe(s,e,r)}/rest/api/2/field`,headers:R(e.token||s.token)})).body},pt=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${pe(s,r,o)}/rest/api/2/issue/${n}?fields=${vr.join(",")}&expand=transitions`,headers:R(r.token||s.token)});return{data:Er(a.body,i,e,o)}},dt=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
|
|
1372
|
+
OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,d=!o,p=d?Qs:Fs,c=new URL(`${pe(s,r,o)}${p}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",at.toString()),c.searchParams.set("fields",vr.join(",")),c.searchParams.set("expand","transitions"),n&&(d?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let m=await s.request({url:c.toString(),headers:R(r.token||s.token)}),g=m.body.issues.map(f=>Er(f,a,e,o)),h=!1,y="";return d?(h=g.length==at,y=(parseInt(n??"0",10)+g.length).toString()):(h=!!m.body.nextPageToken,y=m.body.nextPageToken??null),{data:g,pageInfo:{hasNextPage:h,endCursor:y}}},zs=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=D(t?.pageSize,{fallback:at,max:at}),l=[...vr],d=a?.Sprint;d&&l.push(d);let p=!o,c=p?Qs:Fs,m=new URL(`${pe(s,r,o)}${c}`);m.searchParams.set("jql",i.join(" AND ")),m.searchParams.set("maxResults",u.toString()),m.searchParams.set("fields",l.join(",")),m.searchParams.set("expand","transitions"),n&&(p?m.searchParams.set("startAt",n):m.searchParams.set("nextPageToken",n));let g=await s.request({url:m.toString(),headers:R(r.token||s.token)}),h=g.body.issues.map(P=>Er(P,a,e,o)),y=!1,f="";if(p){let P=parseInt(n??"0",10),v=typeof g.body.startAt=="number"?g.body.startAt:Number.isNaN(P)?0:P,L=g.body.total;y=typeof L=="number"?v+h.length<L:h.length===u,f=(v+h.length).toString()}else y=!!g.body.nextPageToken,f=g.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},ct=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKey:l,resourceId:d,fields:p}=t||{},c=[`project = "${l}"`],m=js(t.states);return m&&c.push(m),o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(g=>c.push(`labels = "${g}"`)),zs(s,{resourceId:d,jql:c,cursor:u,fields:p,pageSize:t.pageSize},e,r)},mt=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:d,fields:p}=t||{},m=["("+l.map(h=>`project = "${h}"`).join(" OR ")+")"],g=js(t.states);return g&&m.push(g),o&&m.push(`creator in ("${o}")`),n&&n.length!==0&&m.push(`assignee in ("${n.join('", "')}")`),i&&m.push(`comment ~ "${i}"`),a&&a.forEach(h=>m.push(`labels = "${h}"`)),zs(s,{resourceId:d,jql:m,fields:p,cursor:u,pageSize:t.pageSize},e,r)},gt=async(s,t,e={})=>{let{issue:r,labels:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{labels:n.map(i=>i.name)}};await s.request({method:"PUT",url:`${pe(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},ht=async(s,t,e={})=>{let{issue:r,components:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');let o={fields:{components:n.map(i=>({id:i.id}))}};await s.request({method:"PUT",url:`${pe(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},ft=async(s,t,e={})=>{let{issue:r,status:n}=t;if(!r.project)throw new Error('Jira requires a "project" for this function.');if(!n.id)throw new Error('Jira requires a status "id" for this function.');let o={transition:{id:n.id}};await s.request({method:"POST",url:`${pe(s,e,r.project.resourceId??void 0)}/rest/api/2/issue/${r.id}/transitions`,body:JSON.stringify(o),headers:{...R(e.token||s.token),"Content-Type":"application/json"}})},Rt=async(s,t,e={})=>{let{resourceId:r,projectIdOrKey:n}=t,o=new URL(`${pe(s,e,r)}/rest/api/2/project/${n}/components`);return{data:(await s.request({url:o.toString(),headers:R(e.token||s.token)})).body}};var Be="https://api.atlassian.com/ex/jira",Sr=100,ci=5,Ce=class extends M{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await lt(this.config,e,r);this._issueFieldsCache[e.resourceId]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[e.resourceId]??null}async getResourceUrl(e,r={}){let n=r.token||this.config.token;if(!n)return null;let o=this._resourceUrlCache[n];return o?o[e.resourceId]??null:(await this.getJiraResourcesForCurrentUser(r),this._resourceUrlCache[n]?.[e.resourceId]??null)}async getCurrentUserForResource(e,r={}){let n=await this.getResourceUrl({resourceId:e.resourceId},r),o=await this.config.request({url:`${r.baseUrl||Be}/${e.resourceId}/rest/api/2/myself`,headers:R(r.token||this.config.token)});return{data:{name:o.body.displayName,email:o.body.emailAddress,avatarUrl:o.body.avatarUrls["48x48"],id:o.body.accountId,username:o.body.displayName,url:n?`${n}/jira/people/${o.body.accountId}`:null}}}async getJiraResourcesForCurrentUser(e={}){let r=await this.config.request({url:`${e.baseUrl||"https://api.atlassian.com/"}/oauth/token/accessible-resources`,headers:R(e.token||this.config.token)}),n=e.token||this.config.token,o=n?this._resourceUrlCache[n]||{}:void 0,i=r.body.map(a=>(o&&(o[a.id]=a.url),{avatarUrl:a.avatarUrl,id:a.id,name:a.name,url:a.url}));return n&&(this._resourceUrlCache[n]=o),{data:i}}async getJiraProjectsForResource(e,r={}){let n=new URL(`${r.baseUrl||Be}/${e.resourceId}/rest/api/2/project/search`);n.searchParams.set("maxResults",Sr.toString()),e.cursor&&n.searchParams.set("startAt",e.cursor);let o=await this.config.request({url:n.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:o.body.values.length!==0,endCursor:(o.body.startAt+o.body.values.length).toString()},metadata:te("complete"),data:o.body.values.map(i=>({id:i.id,key:i.key,name:i.name,resourceId:e.resourceId}))}}async getJiraProjectsForResources(e,r={}){let{successes:n,metadata:o}=await re(e.resourceIds,{run:a=>Jr(u=>this.getJiraProjectsForResource({resourceId:a,cursor:u},r)),failureScope:a=>({providerId:"jira",resourceId:a}),concurrency:ci}),i=[];return n.forEach(({result:a})=>{i.push(...a)}),{data:i,metadata:o}}async getAccountsForJiraProject(e,r={}){let{resourceId:n,projectKey:o,cursor:i}=e,a=await this.getResourceUrl({resourceId:n},r),u=new URL(`${r.baseUrl||Be}/${n}/rest/api/2/user/assignable/search`);u.searchParams.set("maxResults",Sr.toString()),i&&u.searchParams.set("startAt",i),u.searchParams.set("project",o);let l=await this.config.request({url:u.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:l.body.length!==0,endCursor:((i?parseInt(i):0)+l.body.length).toString()},metadata:te("complete"),data:l.body.filter(d=>d.accountType!=="app"&&d.active).map(d=>ut(d,a,!1))}}async getComponentsForJiraProject(e,r={}){return await Rt(this.config,e,r)}async getIssue(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await pt(this.config,{...e,fields:n},o,r)}async getIssuesForProject(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await ct(this.config,{...e,fields:n},o,r)}async getIssuesForProjects(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await mt(this.config,{...e,fields:n},o,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=await this.getIssueFieldsForResource({resourceId:e.resourceId},r),o=await this.getResourceUrl({resourceId:e.resourceId},r);return await dt(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await ft(this.config,e,r)}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e;if(!n.project)throw new Error('Jira Cloud requires a "project" for this function.');if(!n.project.resourceId)throw new Error('Jira Cloud requires a project "resourceId" for this function.');let i={accountId:o?.id};await this.config.request({method:"PUT",url:`${r.baseUrl||Be}/${n.project.resourceId}/rest/api/2/issue/${n.id}/assignee`,body:JSON.stringify(i),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"}})}async setIssueComponents(e,r={}){await ht(this.config,e,r)}async setIssueLabels(e,r={}){await gt(this.config,e,r)}async getLabelsForResource(e,r={}){let{resourceId:n,cursor:o}=e,i=new URL(`${r.baseUrl||Be}/${n}/rest/api/2/label`);i.searchParams.set("maxResults",Sr.toString()),o&&i.searchParams.set("startAt",o);let a=await this.config.request({url:i.toString(),headers:R(r.token||this.config.token)});return{pageInfo:{hasNextPage:!a.body.isLast,endCursor:(a.body.startAt+a.body.values.length).toString()},data:a.body.values.map(u=>({color:null,description:null,id:null,name:u}))}}};var De=class extends F{constructor(){super(...arguments);this._issueFieldsCache={}}async getIssueFieldsForResource(e={}){let r=e?.baseUrl||this.config.baseUrl||"";if(!this._issueFieldsCache[r]){let n=await lt(this.config,{},e);this._issueFieldsCache[r]=n.reduce((o,i)=>({...o,[i.name]:i.id}),{})}return this._issueFieldsCache[r]??null}async getCurrentUser(e={}){let r=await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/myself`,headers:R(e?.token||this.config.token)});return{data:{name:r.body.displayName,email:r.body.emailAddress,avatarUrl:r.body.avatarUrls["48x48"],id:r.body.key,username:r.body.displayName,url:null}}}async getJiraProjects(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/project`,headers:R(e?.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getIssue(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await pt(this.config,{...e,fields:o},n,r)}async getIssuesForProject(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await ct(this.config,{...e,fields:o},n,r)}async getIssuesForProjects(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await mt(this.config,{...e,fields:o},n,r)}async getIssuesForResourceForCurrentUser(e,r={}){let n=e.resourceUrl||r.baseUrl||this.config.baseUrl;if(!n)throw new Error('Jira Server requires a "resourceUrl" or "baseUrl" for this function.');let o=await this.getIssueFieldsForResource(r);return await dt(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await ft(this.config,e,r)}async setIssueLabels(e,r={}){await gt(this.config,e,r)}async setIssueComponents(e,r={}){await ht(this.config,e,r)}async getLabels(e={}){return{data:(await this.config.request({url:`${e?.baseUrl||this.config.baseUrl}/rest/api/2/jql/autocompletedata/suggestions?fieldName=labels`,headers:R(e.token||this.config.token)})).body.results.map(({displayName:n})=>({color:null,description:null,id:null,name:n}))}}async getComponentsForJiraProject(e,r={}){return await Rt(this.config,e,r)}};var Dr=100,It=class{constructor(){this.set=new Set;this.arr=[]}push(...t){let e=t.filter(r=>!this.set.has(r.id));this.arr.push(...e),e.forEach(r=>this.set.add(r.id))}get length(){return this.arr.length}get items(){return this.arr}},ie=async(s,t,e,r)=>{let n=t.token||s.token;if(!n)throw new Error("Linear API key is required");let o=await s.request({url:"https://api.linear.app/graphql",method:"POST",headers:{Authorization:n,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:r})});if(o.status>=400)throw new Error(`Linear API request failed: ${o.status} ${o.statusText}`);let i=o.body;if(i.errors)throw new Error(`Linear GraphQL errors: ${i.errors.map(a=>a.message).join(", ")}`);return i.data},Cr=s=>s?s instanceof Date?s:new Date(s):null,mi=`
|
|
1372
1373
|
id
|
|
1373
1374
|
name
|
|
1374
1375
|
description
|
|
@@ -1376,11 +1377,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1376
1377
|
startDate
|
|
1377
1378
|
targetDate
|
|
1378
1379
|
url
|
|
1379
|
-
`,
|
|
1380
|
+
`,Ms=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:Cr(s.startDate),targetDate:Cr(s.targetDate),url:s.url}),Ws=async(s,t,e)=>{let r=`
|
|
1380
1381
|
query GetProjects($first: Int!, $after: String) {
|
|
1381
1382
|
projects(first: $first, after: $after) {
|
|
1382
1383
|
nodes {
|
|
1383
|
-
${
|
|
1384
|
+
${mi}
|
|
1384
1385
|
}
|
|
1385
1386
|
pageInfo {
|
|
1386
1387
|
hasNextPage
|
|
@@ -1388,7 +1389,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1388
1389
|
}
|
|
1389
1390
|
}
|
|
1390
1391
|
}
|
|
1391
|
-
`;return(await
|
|
1392
|
+
`;return(await ie(s,t,r,{first:Dr,after:e})).projects},gi=`
|
|
1392
1393
|
id
|
|
1393
1394
|
name
|
|
1394
1395
|
number
|
|
@@ -1396,11 +1397,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1396
1397
|
startsAt
|
|
1397
1398
|
endsAt
|
|
1398
1399
|
completedAt
|
|
1399
|
-
`,
|
|
1400
|
+
`,Hs=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:Cr(s.completedAt),url:""}),Vs=async(s,t,e)=>{let r=`
|
|
1400
1401
|
query GetCycles($first: Int!, $after: String) {
|
|
1401
1402
|
cycles(first: $first, after: $after) {
|
|
1402
1403
|
nodes {
|
|
1403
|
-
${
|
|
1404
|
+
${gi}
|
|
1404
1405
|
}
|
|
1405
1406
|
pageInfo {
|
|
1406
1407
|
hasNextPage
|
|
@@ -1408,16 +1409,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1408
1409
|
}
|
|
1409
1410
|
}
|
|
1410
1411
|
}
|
|
1411
|
-
`;return(await
|
|
1412
|
+
`;return(await ie(s,t,r,{first:Dr,after:e})).cycles},hi=`
|
|
1412
1413
|
id
|
|
1413
1414
|
name
|
|
1414
1415
|
color
|
|
1415
1416
|
description
|
|
1416
|
-
`,
|
|
1417
|
+
`,Js=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),Ks=async(s,t,e)=>{let r=`
|
|
1417
1418
|
query GetLabels($first: Int!, $after: String) {
|
|
1418
1419
|
projectLabels(first: $first, after: $after) {
|
|
1419
1420
|
nodes {
|
|
1420
|
-
${
|
|
1421
|
+
${hi}
|
|
1421
1422
|
}
|
|
1422
1423
|
pageInfo {
|
|
1423
1424
|
hasNextPage
|
|
@@ -1425,36 +1426,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1425
1426
|
}
|
|
1426
1427
|
}
|
|
1427
1428
|
}
|
|
1428
|
-
`;return(await
|
|
1429
|
+
`;return(await ie(s,t,r,{first:Dr,after:e})).projectLabels};var je=(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))(je||{});function Xs(s,t){return s?`${je[s]}:${t||""}`:t??null}function Zs(s){if(!s)return{category:0};let[t,e]=s.split(":");return t in je?{category:je[t],cursor:e||void 0}:{category:0,cursor:s}}var Ys=100;function yt(s){return s?s instanceof Date?s:new Date(s):null}var rn=`
|
|
1429
1430
|
id
|
|
1430
1431
|
name
|
|
1431
1432
|
key
|
|
1432
1433
|
icon
|
|
1433
|
-
`;function
|
|
1434
|
+
`;function fi(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var en=`
|
|
1434
1435
|
id
|
|
1435
1436
|
name
|
|
1436
1437
|
avatarUrl
|
|
1437
|
-
`;function
|
|
1438
|
+
`;function tn(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var Ri=`
|
|
1438
1439
|
id
|
|
1439
1440
|
name
|
|
1440
|
-
`;function
|
|
1441
|
+
`;function Ii(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var bi=`
|
|
1441
1442
|
id
|
|
1442
1443
|
sortOrder
|
|
1443
1444
|
name
|
|
1444
1445
|
description
|
|
1445
1446
|
status
|
|
1446
1447
|
targetDate
|
|
1447
|
-
`;function
|
|
1448
|
+
`;function yi(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:yt(s.targetDate)}:null}function Pi(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var wi=`
|
|
1448
1449
|
id
|
|
1449
1450
|
name
|
|
1450
1451
|
color
|
|
1451
1452
|
type
|
|
1452
|
-
`;function
|
|
1453
|
+
`;function qi(s){return s?{id:s.id,name:s.name,color:s.color,category:Pi(s.type)}:null}var $r=`
|
|
1453
1454
|
creator {
|
|
1454
|
-
${
|
|
1455
|
+
${en}
|
|
1455
1456
|
}
|
|
1456
1457
|
assignee {
|
|
1457
|
-
${
|
|
1458
|
+
${en}
|
|
1458
1459
|
}
|
|
1459
1460
|
archivedAt
|
|
1460
1461
|
createdAt
|
|
@@ -1462,23 +1463,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1462
1463
|
id
|
|
1463
1464
|
identifier
|
|
1464
1465
|
project {
|
|
1465
|
-
${
|
|
1466
|
+
${Ri}
|
|
1466
1467
|
}
|
|
1467
1468
|
team {
|
|
1468
|
-
${
|
|
1469
|
+
${rn}
|
|
1469
1470
|
}
|
|
1470
1471
|
state {
|
|
1471
|
-
${
|
|
1472
|
+
${wi}
|
|
1472
1473
|
}
|
|
1473
1474
|
title
|
|
1474
1475
|
updatedAt
|
|
1475
1476
|
url
|
|
1476
1477
|
projectMilestone {
|
|
1477
|
-
${
|
|
1478
|
+
${bi}
|
|
1478
1479
|
}
|
|
1479
|
-
`;async function
|
|
1480
|
+
`;async function Ar(s){return{author:tn(await s.creator),assignees:[tn(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:yt(s.archivedAt),createdDate:yt(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:Ii(await s.project,await s.team),state:qi(await s.state),title:s.title,type:null,updatedDate:yt(s.updatedAt),upvoteCount:null,url:s.url,milestone:yi(await s.projectMilestone)}}var bt=`
|
|
1480
1481
|
nodes {
|
|
1481
|
-
${
|
|
1482
|
+
${$r}
|
|
1482
1483
|
}
|
|
1483
1484
|
pageInfo {
|
|
1484
1485
|
hasNextPage
|
|
@@ -1487,10 +1488,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1487
1488
|
`,Ae=class extends M{async fetchIssue(t,e){let r=`
|
|
1488
1489
|
query GetIssue($identifier: String!) {
|
|
1489
1490
|
issue(id: $identifier) {
|
|
1490
|
-
${
|
|
1491
|
+
${$r}
|
|
1491
1492
|
}
|
|
1492
1493
|
}
|
|
1493
|
-
`;return(await
|
|
1494
|
+
`;return(await ie(this.config,e,r,{identifier:t})).issue}async fetchOrganization(t){let e=`
|
|
1494
1495
|
query GetOrganization {
|
|
1495
1496
|
organization {
|
|
1496
1497
|
id
|
|
@@ -1498,15 +1499,15 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1498
1499
|
urlKey
|
|
1499
1500
|
}
|
|
1500
1501
|
}
|
|
1501
|
-
`;return(await
|
|
1502
|
+
`;return(await ie(this.config,t,e)).organization}async fetchTeams(t){let e=`
|
|
1502
1503
|
query GetTeams {
|
|
1503
1504
|
teams {
|
|
1504
1505
|
nodes {
|
|
1505
|
-
${
|
|
1506
|
+
${rn}
|
|
1506
1507
|
}
|
|
1507
1508
|
}
|
|
1508
1509
|
}
|
|
1509
|
-
`;return(await
|
|
1510
|
+
`;return(await ie(this.config,t,e)).teams}async rawRequest(t,e,r){return{data:await ie(this.config,t,e,r)}}async fetchViewer(t){let e=`
|
|
1510
1511
|
query GetViewer {
|
|
1511
1512
|
viewer {
|
|
1512
1513
|
id
|
|
@@ -1515,11 +1516,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1515
1516
|
displayName
|
|
1516
1517
|
}
|
|
1517
1518
|
}
|
|
1518
|
-
`;return(await
|
|
1519
|
+
`;return(await ie(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await Ar(r)}}async getLinearOrganization(t={}){let e=await this.fetchOrganization(t);return{data:{id:e.id,name:e.name,key:e.urlKey,url:`https://linear.app/${e.urlKey}`}}}async getTeamsForCurrentUser(t={}){return{data:(await this.fetchTeams(t)).nodes.map(fi)}}async getProjects(t={},e={}){let r=await Ws(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Ms),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await Vs(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Hs),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await Ks(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Js),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCurrentUser(t={}){return{data:await this.fetchViewer(t)}}async getIssuesForCurrentUser(t,e={}){let{cursor:r}=t,{category:n,cursor:o}=Zs(r),i=await this.fetchViewer(e),a,u,l=new It,d=async(p,c)=>{if(u||n>p)return;let m=await c(Math.max(Ys-l.length,1),n===p?o:void 0);if(!m)return;let g=await Qt(m.nodes.map(Ar));l.push(...g),m.pageInfo.hasNextPage&&(a=p,u=m.pageInfo.endCursor)};return await d(1,async(p,c)=>(await this.rawRequest(e,`
|
|
1519
1520
|
query GetAssignedIssues($first: Int!, $after: String) {
|
|
1520
1521
|
viewer {
|
|
1521
1522
|
issues: assignedIssues(first: $first, after: $after) {
|
|
1522
|
-
${
|
|
1523
|
+
${bt}
|
|
1523
1524
|
}
|
|
1524
1525
|
}
|
|
1525
1526
|
}
|
|
@@ -1527,7 +1528,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1527
1528
|
query GetCreatedIssues($first: Int!, $after: String) {
|
|
1528
1529
|
viewer {
|
|
1529
1530
|
issues: createdIssues(first: $first, after: $after) {
|
|
1530
|
-
${
|
|
1531
|
+
${bt}
|
|
1531
1532
|
}
|
|
1532
1533
|
}
|
|
1533
1534
|
}
|
|
@@ -1552,7 +1553,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1552
1553
|
}]
|
|
1553
1554
|
}
|
|
1554
1555
|
){
|
|
1555
|
-
${
|
|
1556
|
+
${bt}
|
|
1556
1557
|
}
|
|
1557
1558
|
}
|
|
1558
1559
|
`,{first:p,after:c})).data?.issues),await d(5,async(p,c)=>{let g=(await this.rawRequest(e,`
|
|
@@ -1578,7 +1579,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1578
1579
|
){
|
|
1579
1580
|
nodes {
|
|
1580
1581
|
issue {
|
|
1581
|
-
${
|
|
1582
|
+
${$r}
|
|
1582
1583
|
}
|
|
1583
1584
|
}
|
|
1584
1585
|
pageInfo {
|
|
@@ -1587,10 +1588,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
|
|
|
1587
1588
|
}
|
|
1588
1589
|
}
|
|
1589
1590
|
}
|
|
1590
|
-
`,{first:p,after:c})).data?.comments;return g?{nodes:g.nodes.map(y=>y.issue),pageInfo:g.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:
|
|
1591
|
+
`,{first:p,after:c})).data?.comments;return g?{nodes:g.nodes.map(y=>y.issue),pageInfo:g.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:Xs(a,u)}}}async getIssues(t,e={}){let{teams:r,projects:n,labels:o,cursor:i}=t,a=[];if(r&&r.length>0){let m=r.map(g=>`"${g}"`).join(", ");a.push(`team: { id: { in: [${m}] } }`)}if(n&&n.length>0){let m=n.map(g=>`"${g}"`).join(", ");a.push(`project: { id: { in: [${m}] } }`)}if(o&&o.length>0){let m=o.map(g=>`"${g}"`).join(", ");a.push(`labels: { name: { in: [${m}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",l=`
|
|
1591
1592
|
query GetIssues($first: Int!, $after: String) {
|
|
1592
1593
|
issues(first: $first, after: $after${u?", ":""}${u}) {
|
|
1593
|
-
${
|
|
1594
|
+
${bt}
|
|
1594
1595
|
}
|
|
1595
1596
|
}
|
|
1596
|
-
`,p=(await this.rawRequest(e,l,{first:Ks,after:i})).data?.issues;return p?{data:await Ft(p.nodes.map(Dr)),pageInfo:{hasNextPage:p.pageInfo.hasNextPage,endCursor:p.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var Z="https://api.trello.com",en=1e3,Y=(s,t)=>({...R(t),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${t}"`}),yi=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),Pi=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},$e=class extends M{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||Z}/1/members/me`,headers:Y(t.appKey,e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/members/me/boards?fields=name&filter=open`,headers:Y(t.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/lists`,headers:Y(r,e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||Z}/1/members/${n}`,headers:Y(r,e.token||this.config.token)});return{data:yi(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/members`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(m=>r.push(`label:"${m}"`));let d=`${i?`${i}`:""}${r.join(" ")} board:${o}`,p=await this.config.request({url:`${e.baseUrl||Z}/1/search?query=${d}&cards_limit=${en}&card_members=true`,headers:Y(n,e.token||this.config.token)}),c=p.body.cards.length>=en?"unknown":"complete";return{data:p.body.cards.map(m=>Pi(m,l||{})),metadata:ye(c)}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||Z}/1/cards/${e.id}?${r}`,headers:Y(t,n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:o}=t;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:o}=t,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(t,e={}){let{appKey:r,issue:n,labels:o}=t,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(t,e={}){let{appKey:r,issue:n,archived:o}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?closed=${o}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/labels`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var yt={};H(yt,{default:()=>wi});var wi={};var Pt={};H(Pt,{default:()=>qi});var qi={};var Gt={};H(Gt,{decode:()=>$r,decodeV0:()=>Ci,encode:()=>Si,validate:()=>Ei});var B=(e=>(e.Zero="0",e.One="1",e))(B||{}),j=(e=>(e.PullRequest="pr",e.Issue="issue",e))(j||{}),N=(c=>(c.Azure="azure",c.AzureDevOpsServer="azureDevOpsServer",c.Github="github",c.GithubEnterprise="githubEnterprise",c.Gitlab="gitlab",c.GitlabSelfHosted="gitlabSelfHosted",c.Bitbucket="bitbucket",c.BitbucketServer="bitbucketServer",c.Jira="jira",c.JiraServer="jiraServer",c.Linear="linear",c.Trello="trello",c))(N||{});var wt=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var qt=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var vt=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var Et=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var St=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Ct=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Dt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var At=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var $t=class{constructor(){}validate(t){if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.projectId||!t.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider=="jira"?(e.push(""),e.push(t.resourceId)):(e.push(t.domain),e.push("")),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:t[4]==""?null:t[4],accountOrOrgId:null,organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var Lt=class{constructor(){}validate(t){if(!t.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.accountOrOrgId||!t.projectId||!t.entityId)throw new Error("Missing required fields for Trello issue uniqueId");let e=[];return e.push("trello"),e.push("issue"),e.push("1"),e.push(""),e.push(t.accountOrOrgId),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:t[4],organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var Ut=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new qt:new wt;case"bitbucket":case"bitbucketServer":return t==="pr"?new Et:new vt;case"github":case"githubEnterprise":return t==="pr"?new Ct:new St;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new At:new Dt;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new $t;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Lt;default:throw new Error("unknown provider")}},vi=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")},Ei=s=>{if(s.version==="0"){vi(s);return}Ut(s.provider,s.entityType).validate(s)},Si=s=>Ut(s.provider,s.entityType).encode(s),$r=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return Ut(t[0],t[1]).decode(t)},Ci=(s,t,e)=>{if(!e)throw new Error("entityID is required");try{let r=JSON.parse(e);if(!r||!r.length)throw new Error("Invalid pull request uniqueId");let n=[s,t,"0",...r];return Ut(s,t).decode(n)}catch{return{provider:s,entityType:t,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var Tt={};H(Tt,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>an,CHANGES_REQUESTED_BUCKET_ID:()=>kr,CONFLICTS_ACTION_CATEGORY:()=>nn,CONFLICTS_BUCKET_ID:()=>Or,DRAFT_ACTION_CATEGORY:()=>pn,DRAFT_BUCKET_ID:()=>Br,FAILING_CI_ACTION_CATEGORY:()=>sn,FAILING_CI_BUCKET_ID:()=>Tr,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>on,NEEDS_MY_REVIEW_BUCKET_ID:()=>_r,OTHER_ACTION_CATEGORY:()=>dn,OTHER_BUCKET_ID:()=>jr,PINNED_BUCKET_ID:()=>Lr,READY_TO_MERGE_ACTION_CATEGORY:()=>tn,READY_TO_MERGE_BUCKET_ID:()=>Ur,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>un,REVIEWER_COMMENTED_BUCKET_ID:()=>xr,SNOOZED_BUCKET_ID:()=>Fr,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>rn,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Gr,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>ln,WAITING_FOR_REVIEW_BUCKET_ID:()=>Nr,getActionablePullRequests:()=>cn,groupPullRequestsByAssignee:()=>$i,groupPullRequestsByAuthor:()=>Li,groupPullRequestsByGitKrakenTeam:()=>Oi,groupPullRequestsByRepo:()=>Ai,groupPullRequestsByReviewer:()=>Ui,groupPullRequestsByWorkspace:()=>Ti,groupPullRequestsIntoBuckets:()=>Di});var z=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Lr="pinned",Ur="readyToMerge",Gr="unassignedReviewers",Tr="failingCI",Or="conflicts",_r="needsMyReview",kr="changesRequested",xr="reviewerCommented",Nr="waitingForReview",Br="draft",jr="other",Fr="snoozed",tn="readyToMerge",rn="unassignedReviewers",sn="failingCI",nn="conflicts",on="needsMyReview",an="changesRequested",un="reviewerCommented",ln="waitingForReview",pn="draft",dn="other",cn=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:dn,priority:1e3,viewer:{canMerge:!1,isAuthor:!1,isAssignee:!1,isReviewer:!1,shouldMerge:!1,shouldAssignReviewer:!1,waitingOnReviews:!1,shouldReview:!1},failingCI:!1,hasConflicts:!1,changeRequestReviewCount:0,codeSuggestionsCount:0,commentReviewCount:0,approvalReviewCount:0}};t&&(o.viewer.isAuthor=r.author?.id===t.id,o.viewer.isAssignee=r.assignees?.some(u=>u.id===t.id)??!1,o.viewer.isReviewer=r.reviews?.some(u=>u.reviewer.id===t.id)??!1),o.viewer.canMerge=r.permissions?.canMerge??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=r.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=r.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=r.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=r.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(u=>u.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(u=>u.type==="snooze")&&(o.viewer.snoozed=!0));let a=e?.codeSuggestionsCountByPrUuid?.[r.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!t||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&r.mergeableState==="MERGEABLE"&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=tn),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=pn),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=ln,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=un),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=sn),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=nn),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=an),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=rn,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=on,o.viewer.shouldReview=!0),o}),Di=(s,t,e)=>{let r={pinned:z(Lr,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:z(Ur,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:z(Gr,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:z(Tr,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:z(Or,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:z(_r,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:z(kr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:z(xr,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:z(Nr,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:z(Br,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:z(jr,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:z(Fr,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=cn(s,t,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){r[Fr].pullRequests.push(i);return}a.viewer.pinned&&r[Lr].pullRequests.push(i),(!t||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(r[Ur].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[Gr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[Tr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[Or].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[_r].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[kr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[xr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[Nr].pullRequests.push(i),u=!1),a.isDraft&&(r[Br].pullRequests.push(i),u=!1),u&&r[jr].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},Ai=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),ce(t)},$i=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Qe(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),ce(e)},Li=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Qe(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),ce(e)},Ui=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Qe(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),ce(e)},Gi=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],Ti=(s,t)=>{let e="internal-no-workspace",r={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(t.length){let n=t.reduce((o,i)=>(Gi(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=$r(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,d=u.reduce((p,c)=>n[c]?p.concat(n[c]):p,[]);d?.length&&d.forEach(p=>{l=!0;let c=p.id;r[c]?r[c].pullRequests.push(o):r[c]={name:p.name,priority:0,pullRequests:[o],id:c,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return ce(r)},Oi=(s,t,e,r)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(i=>{let a=!1,u=new Set;u.add(i.author?.id),i.assignees?.forEach(l=>u.add(l.id)),i.reviews?.forEach(l=>u.add(l.reviewer.id)),r.forEach(l=>{if(l.members?.some(p=>{let c=t[p.id]?.[e]?.providerID;return c&&u.has(c)})){a=!0;let p=l.id;o[p]?o[p].pullRequests.push(i):o[p]={name:l.name,priority:0,pullRequests:[i],id:p,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,ce(o)};var Ot={};H(Ot,{getPullRequestRank:()=>_i});var _i=(s,t,e)=>{let r=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===t&&(n=i.state),i.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":i.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),s.author?.id===t?r+=1e3:s.assignees?.find(i=>i.id===t)?r+=900:n==="REVIEW_REQUESTED"?r+=800:e&&(r+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:o=="CHANGES_REQUESTED"&&(r+=70),r};var _t={};H(_t,{default:()=>ki});var ki={};var kt={};H(kt,{default:()=>xi});var xi={};var xt={};H(xt,{default:()=>Ni});var Ni={};var gn=s=>{let t={request:s?.request};return{azureDevOps:new we({...t,...s?.azureDevOps}),bitbucket:new qe({...t,...s?.bitbucket}),bitbucketServer:new ve({...t,...s?.bitbucketServer}),github:new Ee({...t,...s?.github}),gitlab:new Se({...t,...s?.gitlab}),jira:new Ce({...t,...s?.jira}),jiraServer:new De({...t,...s?.jiraServer}),linear:new Ae({...t,...s?.linear}),trello:new $e({...t,...s?.trello})}};var mn=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(mn||{});var hn=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(hn||{});var Bi=gn;var ji={azureDevOps:yt,bitbucket:Pt,bitbucketServer:Je,github:Ot,gitlab:_t,gitProvider:Tt,jira:kt,trello:xt,entityIdentifier:Gt};
|
|
1597
|
+
`,p=(await this.rawRequest(e,l,{first:Ys,after:i})).data?.issues;return p?{data:await Qt(p.nodes.map(Ar)),pageInfo:{hasNextPage:p.pageInfo.hasNextPage,endCursor:p.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var Z="https://api.trello.com",sn=1e3,Y=(s,t)=>({...R(t),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${t}"`}),vi=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),Ei=(s,t)=>{let e=new Date(1e3*parseInt(s.id.substring(0,8),16));return{id:s.id,commentCount:s.badges.comments,number:s.idShort.toString(),title:s.name,url:s.url,closedDate:null,createdDate:new Date(e.toISOString()),author:null,updatedDate:new Date(s.dateLastActivity),assignees:s.members.map(r=>({id:r.id,username:r.username,name:r.fullName,email:null,avatarUrl:r.avatarUrl,url:null})),description:null,state:t[s.idList??""]?{id:s.idList,name:t[s.idList].name,color:null}:null,type:null,repository:null,upvoteCount:s.badges.votes,labels:s.labels.map(r=>({color:r.color,description:null,id:r.id,name:r.name}))}},$e=class extends M{async getCurrentUser(t,e={}){let r=await this.config.request({url:`${e.baseUrl||Z}/1/members/me`,headers:Y(t.appKey,e.token||this.config.token)});return{data:{name:r.body.fullName,email:r.body.email,avatarUrl:r.body.avatarHash?`https://trello-members.s3.amazonaws.com/${r.body.id}/${r.body.avatarHash}/50.png`:null,id:r.body.id,username:r.body.username,url:r.body.url}}}async getBoardsForCurrentUser(t,e={}){return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/members/me/boards?fields=name&filter=open`,headers:Y(t.appKey,e.token||this.config.token)})).body.map(n=>({id:n.id,name:n.name}))}}async getListsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/lists`,headers:Y(r,e.token||this.config.token)})).body}}async getAccountForId(t,e={}){let{appKey:r,memberId:n}=t,o=await this.config.request({url:`${e.baseUrl||Z}/1/members/${n}`,headers:Y(r,e.token||this.config.token)});return{data:vi(o.body)}}async getAccountsForTrelloBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/members`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({id:i.id,name:i.fullName,username:i.username,email:null,avatarUrl:null,url:null}))}}async getIssuesForBoard(t,e={}){let r=["-is:archived","sort:edited"],{appKey:n,boardId:o,filterText:i,assigneeLogins:a,labelNamesOrColors:u,trelloBoardListsById:l}=t||{};a&&r.push("@me"),u&&u.forEach(m=>r.push(`label:"${m}"`));let d=`${i?`${i}`:""}${r.join(" ")} board:${o}`,p=await this.config.request({url:`${e.baseUrl||Z}/1/search?query=${d}&cards_limit=${sn}&card_members=true`,headers:Y(n,e.token||this.config.token)}),c=p.body.cards.length>=sn?"unknown":"complete";return{data:p.body.cards.map(m=>Ei(m,l||{})),metadata:te(c)}}async updateIssue(t,e,r,n){return await this.config.request({method:"PUT",url:`${n.baseUrl||Z}/1/cards/${e.id}?${r}`,headers:Y(t,n.token||this.config.token)})}async setIssueStatus(t,e={}){let{appKey:r,issue:n,status:o}=t;if(!o.id)throw new Error('Trello requires a status "id" for this function.');let i=`idList=${o.id}`;if(!(await this.updateIssue(r,n,i,e)).body.id)throw new Error("Could not set issue status")}async setIssueAssignees(t,e={}){let{appKey:r,issue:n,assignees:o}=t,i=o.map(l=>l.id),a=`idMembers=${encodeURIComponent(i.join(","))}`;if(!(await this.updateIssue(r,n,a,e)).body.id)throw new Error("Could not set issue status")}async setIssueLabels(t,e={}){let{appKey:r,issue:n,labels:o}=t,i=o.map(u=>u.id).join(",");if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?idLabels=${encodeURIComponent(i)}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not set issue status")}async setIssueArchived(t,e={}){let{appKey:r,issue:n,archived:o}=t;if(!(await this.config.request({method:"PUT",url:`${e.baseUrl||Z}/1/cards/${n.id}?closed=${o}`,headers:Y(r,e.token||this.config.token)})).body.id)throw new Error("Could not update issue archived status")}async archiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!0},e)}async unArchiveIssue(t,e={}){await this.setIssueArchived({...t,archived:!1},e)}async getLabelsForBoard(t,e={}){let{appKey:r,boardId:n}=t;return{data:(await this.config.request({url:`${e.baseUrl||Z}/1/boards/${n}/labels`,headers:Y(r,e.token||this.config.token)})).body.map(i=>({color:i.color,description:null,id:i.id,name:i.name}))}}};var Pt={};H(Pt,{default:()=>Si});var Si={};var wt={};H(wt,{default:()=>Ci});var Ci={};var Tt={};H(Tt,{decode:()=>Lr,decodeV0:()=>Li,encode:()=>$i,validate:()=>Ai});var B=(e=>(e.Zero="0",e.One="1",e))(B||{}),j=(e=>(e.PullRequest="pr",e.Issue="issue",e))(j||{}),N=(c=>(c.Azure="azure",c.AzureDevOpsServer="azureDevOpsServer",c.Github="github",c.GithubEnterprise="githubEnterprise",c.Gitlab="gitlab",c.GitlabSelfHosted="gitlabSelfHosted",c.Bitbucket="bitbucket",c.BitbucketServer="bitbucketServer",c.Jira="jira",c.JiraServer="jiraServer",c.Linear="linear",c.Trello="trello",c))(N||{});var qt=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.entityId)throw new Error("Missing required fields for Azure DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Azure DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:null,entityId:t[6]}}};var vt=class{constructor(){}validate(t){if(!t.organizationName)throw new Error("organizationName is required");if(!t.projectId)throw new Error("projectId is required");if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.organizationName||!t.projectId||!t.repoId||!t.entityId)throw new Error("Missing required fields for Azure DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="azureDevOpsServer"?e.push(t.domain):e.push(""),e.push(t.organizationName),e.push(t.projectId),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<8)throw new Error("Invalid Azure DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:t[4],projectId:t[5],repoId:t[6],entityId:t[7]}}};var Et=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("issueId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var St=class{constructor(){}validate(t){if(!t.repoId)throw new Error("repoId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.repoId||!t.entityId)throw new Error("Missing required fields for Bitbucket DevOps pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="bitbucketServer"?e.push(t.domain):e.push(""),e.push(t.repoId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<6)throw new Error("Invalid Bitbucket DevOps pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:t[4],entityId:t[5]}}};var Ct=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Dt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Github pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="githubEnterprise"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Github pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var At=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var $t=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for Gitlab pull request uniqueId");let e=[];return e.push(t.provider),e.push("pr"),e.push("1"),t.provider==="gitlabSelfHosted"?e.push(t.domain):e.push(""),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<5)throw new Error("Invalid Gitlab pull request uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:t[4]}}};var Lt=class{constructor(){}validate(t){if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.projectId||!t.entityId)throw new Error("Missing required fields for Jira issue uniqueId");let e=[];return e.push(t.provider),e.push("issue"),e.push("1"),t.provider=="jira"?(e.push(""),e.push(t.resourceId)):(e.push(t.domain),e.push("")),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Jira issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:t[4]==""?null:t[4],accountOrOrgId:null,organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var Ut=class{constructor(){}validate(t){if(!t.accountOrOrgId)throw new Error("accountOrOrgId is required");if(!t.projectId)throw new Error("projectId is required");if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.accountOrOrgId||!t.projectId||!t.entityId)throw new Error("Missing required fields for Trello issue uniqueId");let e=[];return e.push("trello"),e.push("issue"),e.push("1"),e.push(""),e.push(t.accountOrOrgId),e.push(t.projectId),e.push(t.entityId),JSON.stringify(e)}decode(t){if(t.length<7)throw new Error("Invalid Trello issue uniqueId, check version");return{provider:t[0],entityType:t[1],version:t[2],domain:t[3]==""?null:t[3],resourceId:null,accountOrOrgId:t[4],organizationName:null,projectId:t[5],repoId:null,entityId:t[6]}}};var Gt=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new vt:new qt;case"bitbucket":case"bitbucketServer":return t==="pr"?new St:new Et;case"github":case"githubEnterprise":return t==="pr"?new Dt:new Ct;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new $t:new At;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Lt;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Ut;default:throw new Error("unknown provider")}},Di=s=>{if(!s.entityType)throw new Error("entityType is required");if(!s.provider)throw new Error("provider is required");if(!s.entityId)throw new Error("entityID is required")},Ai=s=>{if(s.version==="0"){Di(s);return}Gt(s.provider,s.entityType).validate(s)},$i=s=>Gt(s.provider,s.entityType).encode(s),Lr=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return Gt(t[0],t[1]).decode(t)},Li=(s,t,e)=>{if(!e)throw new Error("entityID is required");try{let r=JSON.parse(e);if(!r||!r.length)throw new Error("Invalid pull request uniqueId");let n=[s,t,"0",...r];return Gt(s,t).decode(n)}catch{return{provider:s,entityType:t,version:"0",domain:"",resourceId:null,accountOrOrgId:null,organizationName:null,projectId:null,repoId:null,entityId:e}}};var Ot={};H(Ot,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>pn,CHANGES_REQUESTED_BUCKET_ID:()=>xr,CONFLICTS_ACTION_CATEGORY:()=>un,CONFLICTS_BUCKET_ID:()=>_r,DRAFT_ACTION_CATEGORY:()=>mn,DRAFT_BUCKET_ID:()=>jr,FAILING_CI_ACTION_CATEGORY:()=>an,FAILING_CI_BUCKET_ID:()=>Or,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>ln,NEEDS_MY_REVIEW_BUCKET_ID:()=>kr,OTHER_ACTION_CATEGORY:()=>gn,OTHER_BUCKET_ID:()=>Fr,PINNED_BUCKET_ID:()=>Ur,READY_TO_MERGE_ACTION_CATEGORY:()=>nn,READY_TO_MERGE_BUCKET_ID:()=>Gr,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>dn,REVIEWER_COMMENTED_BUCKET_ID:()=>Nr,SNOOZED_BUCKET_ID:()=>Qr,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>on,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>Tr,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>cn,WAITING_FOR_REVIEW_BUCKET_ID:()=>Br,getActionablePullRequests:()=>hn,groupPullRequestsByAssignee:()=>Ti,groupPullRequestsByAuthor:()=>Oi,groupPullRequestsByGitKrakenTeam:()=>Ni,groupPullRequestsByRepo:()=>Gi,groupPullRequestsByReviewer:()=>_i,groupPullRequestsByWorkspace:()=>xi,groupPullRequestsIntoBuckets:()=>Ui});var z=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Ur="pinned",Gr="readyToMerge",Tr="unassignedReviewers",Or="failingCI",_r="conflicts",kr="needsMyReview",xr="changesRequested",Nr="reviewerCommented",Br="waitingForReview",jr="draft",Fr="other",Qr="snoozed",nn="readyToMerge",on="unassignedReviewers",an="failingCI",un="conflicts",ln="needsMyReview",pn="changesRequested",dn="reviewerCommented",cn="waitingForReview",mn="draft",gn="other",hn=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:gn,priority:1e3,viewer:{canMerge:!1,isAuthor:!1,isAssignee:!1,isReviewer:!1,shouldMerge:!1,shouldAssignReviewer:!1,waitingOnReviews:!1,shouldReview:!1},failingCI:!1,hasConflicts:!1,changeRequestReviewCount:0,codeSuggestionsCount:0,commentReviewCount:0,approvalReviewCount:0}};t&&(o.viewer.isAuthor=r.author?.id===t.id,o.viewer.isAssignee=r.assignees?.some(u=>u.id===t.id)??!1,o.viewer.isReviewer=r.reviews?.some(u=>u.reviewer.id===t.id)??!1),o.viewer.canMerge=r.permissions?.canMerge??!0,o.hasConflicts=r.mergeableState==="CONFLICTS",o.failingCI=r.headCommit?.buildStatuses?.some(u=>u.state==="ERROR"||u.state==="FAILED")||r.mergeableState==="FAILING_CHECKS",o.commentReviewCount=r.reviews?.filter(u=>u.state==="COMMENTED").length??0,o.approvalReviewCount=r.reviews?.filter(u=>u.state==="APPROVED").length??0,o.changeRequestReviewCount=r.reviews?.filter(u=>u.state==="CHANGES_REQUESTED").length??0;let i=e?.enrichedItemsByUniqueId?.[r.uuid];i!=null&&(o.viewer.enrichedItems=i,i.some(u=>u.type==="pin")&&(o.viewer.pinned=!0,o.priority-=800),i.some(u=>u.type==="snooze")&&(o.viewer.snoozed=!0));let a=e?.codeSuggestionsCountByPrUuid?.[r.uuid]?.count||0;return a&&(o.codeSuggestionsCount=a),(!t||o.viewer.isAuthor||o.viewer.isAssignee&&!o.viewer.isReviewer)&&o.viewer.canMerge&&!o.isDraft&&!o.failingCI&&r.mergeableState==="MERGEABLE"&&(o.viewer.shouldMerge=!0,o.suggestedActionCategory=nn),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=mn),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=cn,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=dn),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=an),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=un),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=pn),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=on,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=ln,o.viewer.shouldReview=!0),o}),Ui=(s,t,e)=>{let r={pinned:z(Ur,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:z(Gr,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:z(Tr,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:z(Or,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:z(_r,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:z(kr,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:z(xr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:z(Nr,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:z(Br,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:z(jr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:z(Fr,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:z(Qr,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=hn(s,t,e).reduce((i,a)=>(i[a.uuid]=a,i),{});return s.forEach(i=>{let a=o[i.uuid],u=!0;if(a.viewer.snoozed){r[Qr].pullRequests.push(i);return}a.viewer.pinned&&r[Ur].pullRequests.push(i),(!t||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(r[Gr].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[Tr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[Or].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[_r].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[kr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[xr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[Nr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[Br].pullRequests.push(i),u=!1),a.isDraft&&(r[jr].pullRequests.push(i),u=!1),u&&r[Fr].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},Gi=s=>{let t={};return s.forEach(e=>{let r=e.repository.id;t[r]?t[r].pullRequests.push(e):t[r]={name:e.repository.name,priority:0,pullRequests:[e],id:r}}),me(t)},Ti=s=>{let t="internal-no-assignees",e={[t]:{name:"No assignees",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.assignees&&r.assignees.length?r.assignees.forEach(n=>{let o=n.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n,name:Qe(n,`Unknown Assignee ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),me(e)},Oi=s=>{let t="internal-no-author",e={[t]:{name:"No author",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{if(r.author){let n=r.author.id;e[n]?e[n].pullRequests.push(r):e[n]={accountData:r.author,name:Qe(r.author,`Unknown Author ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:n}}else e[t].pullRequests.push(r)}),me(e)},_i=s=>{let t="internal-no-reviewer",e={[t]:{name:"No reviewers",priority:-1,pullRequests:[],id:t,faIconName:"user-slash"}};return s.forEach(r=>{r.reviews&&r.reviews.length?r.reviews.forEach(n=>{let o=n.reviewer.id;e[o]?e[o].pullRequests.push(r):e[o]={accountData:n.reviewer,name:Qe(n.reviewer,`Unknown Reviewer ${Object.keys(e).length}`),priority:0,pullRequests:[r],id:o}}):e[t].pullRequests.push(r)}),me(e)},ki=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],xi=(s,t)=>{let e="internal-no-workspace",r={[e]:{name:"No workspace",priority:-1,pullRequests:[],id:e,faIconName:"folder-xmark"}};if(t.length){let n=t.reduce((o,i)=>(ki(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Lr(o.uuid),a=i==="github"?o.repository.graphQLId:o.repository.id,u=i==="azure"?[`${i}-${a}`,`${o.repository.project}-${o.repository.owner.login}`]:[`${i}-${a}`],l=!1,d=u.reduce((p,c)=>n[c]?p.concat(n[c]):p,[]);d?.length&&d.forEach(p=>{l=!0;let c=p.id;r[c]?r[c].pullRequests.push(o):r[c]={name:p.name,priority:0,pullRequests:[o],id:c,faIconName:"folder"}}),l||r[e].pullRequests.push(o)})}else r[e].pullRequests=s;return me(r)},Ni=(s,t,e,r)=>{let n="internal-no-team",o={[n]:{name:"No team",priority:-1,pullRequests:[],id:n}};return r.length?s.forEach(i=>{let a=!1,u=new Set;u.add(i.author?.id),i.assignees?.forEach(l=>u.add(l.id)),i.reviews?.forEach(l=>u.add(l.reviewer.id)),r.forEach(l=>{if(l.members?.some(p=>{let c=t[p.id]?.[e]?.providerID;return c&&u.has(c)})){a=!0;let p=l.id;o[p]?o[p].pullRequests.push(i):o[p]={name:l.name,priority:0,pullRequests:[i],id:p,teamData:l}}}),a||o[n].pullRequests.push(i)}):o[n].pullRequests=s,me(o)};var _t={};H(_t,{getPullRequestRank:()=>Bi});var Bi=(s,t,e)=>{let r=0,n,o;return s.reviews?.forEach(i=>{i.reviewer.id===t&&(n=i.state),i.state==="CHANGES_REQUESTED"?o="CHANGES_REQUESTED":i.state==="APPROVED"&&o!=="CHANGES_REQUESTED"&&(o="APPROVED")}),o||(o="REVIEW_REQUESTED"),s.author?.id===t?r+=1e3:s.assignees?.find(i=>i.id===t)?r+=900:n==="REVIEW_REQUESTED"?r+=800:e&&(r+=700),o==="APPROVED"?s.mergeableState==="MERGEABLE"?r+=100:s.mergeableState==="CONFLICTS"?r+=90:r+=80:o=="CHANGES_REQUESTED"&&(r+=70),r};var kt={};H(kt,{default:()=>ji});var ji={};var xt={};H(xt,{default:()=>Fi});var Fi={};var Nt={};H(Nt,{default:()=>Qi});var Qi={};var fn=s=>{let t={request:s?.request};return{azureDevOps:new we({...t,...s?.azureDevOps}),bitbucket:new qe({...t,...s?.bitbucket}),bitbucketServer:new ve({...t,...s?.bitbucketServer}),github:new Ee({...t,...s?.github}),gitlab:new Se({...t,...s?.gitlab}),jira:new Ce({...t,...s?.jira}),jiraServer:new De({...t,...s?.jiraServer}),linear:new Ae({...t,...s?.linear}),trello:new $e({...t,...s?.trello})}};var Rn=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(Rn||{});var In=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(In||{});var zi=fn;var Mi={azureDevOps:Pt,bitbucket:wt,bitbucketServer:Ke,github:_t,gitlab:kt,gitProvider:Ot,jira:xt,trello:Nt,entityIdentifier:Tt};
|