@gitkraken/provider-apis 0.52.0 → 0.53.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/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var xt=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var Rn=Object.getOwnPropertyNames;var In=Object.prototype.hasOwnProperty;var H=(s,t)=>{for(var e in t)xt(s,e,{get:t[e],enumerable:!0})},bn=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Rn(t))!In.call(s,n)&&n!==e&&xt(s,n,{get:()=>t[n],enumerable:!(r=fn(t,n))||r.enumerable});return s};var yn=s=>bn(xt({},"__esModule",{value:!0}),s);var Oi={};H(Oi,{AzureDevOps:()=>Pe,AzureDevopsUtils:()=>It,Bitbucket:()=>we,BitbucketServer:()=>qe,BitbucketServerUtils:()=>Je,BitbucketUtils:()=>bt,EntityIdentifierProviderType:()=>N,EntityIdentifierUtils:()=>Lt,EntityType:()=>j,EntityVersion:()=>B,GitBuildStatusStage:()=>jr,GitBuildStatusState:()=>Ue,GitDiffLineType:()=>Nt,GitHub:()=>ve,GitHubIssueCloseReason:()=>dn,GitHubUtils:()=>Gt,GitIssueState:()=>ge,GitLab:()=>Se,GitLabUtils:()=>Tt,GitMergeStrategy:()=>Ie,GitProviderUtils:()=>Ut,GitPullRequestMergeableState:()=>ee,GitPullRequestReviewState:()=>V,GitPullRequestState:()=>ie,GraphQLErrors:()=>I,Jira:()=>Ce,JiraServer:()=>De,JiraUtils:()=>Ot,Linear:()=>Ae,PullRequestAsyncStatus:()=>pn,Trello:()=>$e,TrelloUtils:()=>_t,Utils:()=>Ti,default:()=>Gi,isFetch:()=>ze});module.exports=yn(Oi);var ts=require("diff");var jr=(n=>(n.Build="build",n.Production="production",n.Staging="staging",n.Test="test",n))(jr||{}),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||{}),Ie=(o=>(o.MergeCommit="MERGE_COMMIT",o.Rebase="REBASE",o.RebaseThenMergeCommit="REBASE_THEN_MERGE_COMMIT",o.FastForward="FAST_FORWARD",o.Squash="SQUASH",o))(Ie||{}),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||{}),Nt=(r=>(r.ADDED="ADDED",r.DELETED="DELETED",r.UNMODIFIED="UNMODIFIED",r))(Nt||{});var Fr={APPROVED:0,COMMENTED:1,REVIEW_REQUESTED:2,CHANGES_REQUESTED:3},J=s=>!s||s.length===0?null:s.reduce((t,e)=>Fr[e.state]>Fr[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 Pn=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},Mr=s=>s?s.reduce((t,e)=>(t[e]=!0,t),{}):void 0,ae=(s,t,e)=>!s||t.some(r=>s[r])?e:"",Wr=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 Bt(s){return(await Promise.allSettled(s)).map(e=>Sn(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))},wn=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}},qn=s=>{if(!(!s||typeof s!="object"||!("code"in s)||typeof s.code!="string"))return s.code},Hr=s=>{if(typeof s=="string")return s;if(s instanceof Error)return s.message},vn=s=>{let t=wn(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=qn(s);if(e&&Pn.has(e))return"network";let r=Hr(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"},En=(s,t)=>{let e=Hr(t);return{scope:s,kind:vn(t),...e?{message:e}:{}}},be=(s,t=[])=>({completeness:s,...t.length?{failures:t}:{}}),Qr={complete:0,unknown:1,partial:2},zr=(s,t)=>Qr[s]>=Qr[t]?s:t,me=s=>s?s.id||`${s.namespace}/${s.name}`:void 0;async function te(s,{run:t,failureScope:e,completeness:r}){let n=await Promise.all(s.map(async u=>{try{return{scope:u,result:await t(u)}}catch(l){return{scope:u,error:l}}})),o=[],i=[],a="complete";return n.forEach(u=>{if("error"in u){o.push(En(e(u.scope),u.error)),a=zr(a,"partial");return}if(u.result===void 0)return;let l=u.result;a=zr(a,r?r(l):"complete"),i.push({scope:u.scope,result:l})}),{successes:i,metadata:be(a,o)}}function Sn(s,t=void 0){return s?.status==="fulfilled"?s.value:t}async function Vr(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 ge=(e=>(e.Open="OPEN",e.Closed="CLOSED",e))(ge||{});var jt=(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))(jt||{});var $=100;var Jr=globalThis.fetch;var Cn=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},Ft=s=>async({url:t,...e})=>{let r=await s(t,e);return Cn(r)};var ze=(s,t=!1)=>s.name==="fetch"||t;var M=class{constructor(t){let e=t?.request||Jr;this.config={...t,request:ze(e,t?.forceIsFetch)?Ft(e):e}}updateConfig(t){this.config={...this.config,...t,request:t.request&&ze(t.request,t?.forceIsFetch??this.config.forceIsFetch)?Ft(t.request):this.config.request}}},F=class extends M{};var Dn="https://app.vssps.visualstudio.com/_apis",An="https://vssps.dev.azure.com/",$n="https://dev.azure.com",q=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT),Kr=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/"),Qt=(s,t)=>{let e=t.baseUrl||s.baseUrl||Dn;return e=e.replace(/\/$/,""),e},C=(s,t)=>{let e=t.baseUrl||s.baseUrl||$n;return e=e.replace(/\/$/,""),e},zt=(s,t)=>{let e=t.baseUrl||s.baseUrl||An;return e=e.replace(/\/$/,""),e};var Ln={active:"OPEN",completed:"MERGED",abandoned:"CLOSED"},Un={OPEN:"active",MERGED:"completed",CLOSED:"abandoned"},ye=100,Gn=200,Tn=200,Xr=s=>{if(!s||s.length===0)return"active";let t=Array.from(new Set(s.map(e=>Un[e])));return t.length===1?t[0]:"all"},On=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] = ''"]},_n=s=>{if(typeof s!="string")return s;let t=s.charAt(0).toUpperCase()+s.slice(1);return jt[t]??0},kn=new Set([2,3,4,5]),xn={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,Nn=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"}},Mt=(s,t,e,r,n,o)=>`${s}|${t}|${e}|${r}|${n}|${o}`,Zr=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]}},Yr=(s,t,e,r,n)=>`${s}|${t}|${e}|${r}|${n}`,Wt=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:xn[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:Ln[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:Kr(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:Nn(t.mergeStatus),labels:t.labels?.map(i=>({color:null,description:null,id:i.id,name:i.name}))??[],permissions:null}},es=(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}),Bn=(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()}))??[]}},Pe=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`${C(this.config,o)}/${encodeURIComponent(e)}/${encodeURIComponent(r)}/_apis/git/repositories/${encodeURIComponent(n)}`}async getCurrentUser(e={},r={}){if(r.isPAT||this.config.isPAT)throw new Error("Azure DevOps does not support PATs for this function.");let n=`${Qt(this.config,r)}/profile/profiles/me`,o=await this.config.request({url:n,headers:q(this.config,r)});return{data:{id:o.body.id,name:o.body.displayName,username:o.body.displayName,email:o.body.emailAddress,avatarUrl:null,url:null}}}async getCurrentUserForInstance(e,r={}){let o=(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/ConnectionData`,headers:q(this.config,r)})).body.authorizedUser;if(o.providerDisplayName==="Anonymous")throw new Error("Current user not found.");return{data:{id:o.id,name:o.providerDisplayName,username:o.providerDisplayName,email:o.properties.Account.$value,avatarUrl:null,url:null}}}async getUserForCommit(e,r={}){if(!e.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.repo.namespace)}/${encodeURIComponent(e.repo.project)}/_apis/git/repositories/${encodeURIComponent(e.repo.name)}/commits/${e.oid}`,headers:q(this.config,r)})).body.author;return{data:{name:o.name,email:o.email,avatarUrl:o.imageUrl}}}async getOrgsForUser(e,r={}){let n=`${Qt(this.config,r)}/accounts?memberId=${e.userId}&api-version=6.0`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.accountId,name:i.accountName}))}}async getCollectionsForUser(e,r={}){let n=`${C(this.config,r)}/_apis/projectCollections`;return{data:(await this.config.request({url:n,headers:q(this.config,r)})).body.value.map(i=>({id:i.id,name:i.name}))}}async getAzureProjects(e,r={}){let n=new URL(`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/_apis/projects`);n.searchParams.set("$top",$.toString()),e.cursor&&n.searchParams.set("$skip",e.cursor);let o=await this.config.request({url:n.toString(),headers:q(this.config,r)}),i=o.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!i,endCursor:i||null},data:o.body.value.map(a=>({id:a.id,name:a.name,namespace:e.namespace}))}}async getAzureProjectScopeDescriptor(e,r={}){let{namespace:n,projectId:o}=e;return{data:{scope:(await this.config.request({url:`${zt(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(`${zt(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:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories/${encodeURIComponent(e.name)}`,headers:q(this.config,r)});return{data:es(e.namespace,n.body)}}async getRepos(e,r={}){let n=[],o=[];return await Promise.all(e.map(async i=>{try{let a=await this.getRepo(i,r);n.push(a.data)}catch(a){o.push({input:i,error:a})}})),{data:n,errors:o}}async getReposForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/git/repositories`,headers:q(this.config,r)})).body.value.map(o=>es(e.namespace,o))}}async getRefs(e,r,n={}){if(!r.repo.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let o=new URL(`${C(this.config,n)}/${encodeURIComponent(r.repo.namespace)}/${encodeURIComponent(r.repo.project)}/_apis/git/repositories/${encodeURIComponent(r.repo.name)}/refs`);o.searchParams.set("filter",e),o.searchParams.set("$top",$.toString()),r.cursor&&o.searchParams.set("continuationToken",r.cursor);let i=await this.config.request({url:o.toString(),headers:q(this.config,n)}),a=i.headers["x-ms-continuationtoken"];return{pageInfo:{hasNextPage:!!a,endCursor:a||null},data:i.body.value.map(u=>({name: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 Vr([...i],10,async([a,u])=>{try{let l=await this.config.request({url:`${C(this.config,n)}/${encodeURIComponent(u)}/_apis/git/repositories/${encodeURIComponent(a)}`,headers:q(this.config,n)}),{remoteUrl:d,sshUrl:p}=l.body;d&&p&&o.set(a,{cloneUrlHTTPS:d,cloneUrlSSH:p})}catch{}}),o}async getPullRequestsForRepoBase(e,r={},n=ye){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),g=`searchCriteria.status=${Xr(e.states)}`;return c&&(g+=`&searchCriteria.reviewerId=${encodeURIComponent(c)}`),u&&(g+=`&searchCriteria.creatorId=${encodeURIComponent(u)}`),await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(i.namespace)}/${encodeURIComponent(i.project||"")}/_apis/git/repositories/${encodeURIComponent(i.name)}/pullRequests?${g}&%24top=${p}&%24skip=${(d-1)*p}`,headers:q(this.config,r)})}async getPullRequestsForRepo(e,r={}){let n=L(e.pageSize,{fallback:ye}),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:ye}),{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:me(p)}),completeness:p=>p.body.value.length===o?"unknown":"complete"}),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(g=>Ge(p,g,l)));return{data:x(d,e.states),metadata:a}}async getPullRequestsForProjectBase(e,r={},n=ye){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,g=L(e.pageSize,{fallback:n}),m=d??(u&&u.length?u[0]:void 0),h=new URL(`${C(this.config,r)}/${encodeURIComponent(o)}/${encodeURIComponent(i)}/_apis/git/pullRequests`);return h.searchParams.set("searchCriteria.status",Xr(e.states)),h.searchParams.set("$top",g.toString()),h.searchParams.set("$skip",((c-1)*g).toString()),p?.id&&p?.project===i&&h.searchParams.set("searchCriteria.repositoryId",p.id),m&&h.searchParams.set("searchCriteria.reviewerId",m),l&&h.searchParams.set("searchCriteria.creatorId",l),await this.config.request({url:h.toString(),headers:q(this.config,r)})}async getPullRequestsForProject(e,r={}){let n=L(e.pageSize,{fallback:ye}),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:ye}),{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:me(e.repo)}),completeness:p=>p.body.value.length===o?"unknown":"complete"}),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(g=>Ge(p,g,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:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/git/repositories/${i}/pullrequests/${a}?includeCommits=true?api-version=6.0`,headers:{...q(this.config,r)}});if(!u.body.mergeStatus)throw new Error("Could not fetch pull request");return{data:u.body.mergeStatus}}async updatePullRequest(e,r,n){return await this.config.request({method:"PATCH",url:`${C(this.config,n)}/${encodeURIComponent(e.repository.owner.login)}/${encodeURIComponent(e.repository.project)}/_apis/git/repositories/${e.repository.name}/pullrequests/${e.id}?api-version=6.0`,body:r,headers:{...q(this.config,n),"Content-Type":"application/json"}})}async closePullRequest(e,r={}){let{pullRequest:n}=e,o={status:"abandoned"};if(!(await this.updatePullRequest(n,JSON.stringify(o),r)).body.status)throw new Error("Could not close pull request")}async mergePullRequest(e,r={}){let{pullRequest:n,mergeStrategy:o}=e,i;switch(o){case"MERGE_COMMIT":{i="noFastForward";break}case"REBASE":{i="rebase";break}case"REBASE_THEN_MERGE_COMMIT":{i="rebaseMerge";break}case"SQUASH":{i="squash";break}}let a={completionOptions:{mergeStrategy:i},lastMergeSourceCommit:{commitId:n.headRef?.oid},status:"completed"};if(!(await this.updatePullRequest(n,JSON.stringify(a),r)).body.status)throw new Error("Could not merge pull request")}async addPullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i={name:o.name};if(!(await this.config.request({method:"POST",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels?api-version=6.0`,body:JSON.stringify(i),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request label")}async removePullRequestLabel(e,r={}){let{pullRequest:n,label:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');await this.config.request({method:"DELETE",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/labels/${encodeURIComponent(o.name)}?api-version=6.0`,headers:{...q(this.config,r)}})}async setPullRequestLabels(e,r={}){let{pullRequest:n,labels:o}=e;if(!n.repository.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=n.labels;if(!i)throw new Error('Azure DevOps requires "labels" for this function.');for(let a of o)i.find(u=>u.id===a.id)||await this.addPullRequestLabel({pullRequest:n,label:a},r);for(let a of i)o.find(u=>a.id===u.id)||await this.removePullRequestLabel({pullRequest:n,label:a},r)}async setPullRequestAsDraft(e,r={}){let{pullRequest:n,isDraft:o}=e,i={isDraft:o};if(!(await this.updatePullRequest(n,JSON.stringify(i),r)).body.status)throw new Error("Could not set the pull request as draft")}async addPullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o,isRequired:i}=e,a={id:o.id,isRequired:i};if(!(await this.config.request({method:"PUT",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,body:JSON.stringify(a),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.id)throw new Error("Could not add pull request reviewer")}async removePullRequestReviewer(e,r={}){let{pullRequest:n,reviewer:o}=e;await this.config.request({method:"DELETE",url:`${C(this.config,r)}/${encodeURIComponent(n.repository.owner.login)}/${encodeURIComponent(n.repository.project)}/_apis/git/repositories/${n.repository.name}/pullrequests/${n.id}/reviewers/${o.id}?api-version=6.0`,headers:{...q(this.config,r),Accept:"application/json"}})}async setPullRequestReviewers(e,r={}){let{pullRequest:n,reviewers:o}=e;for(let i of o)n.assignees.find(a=>a.id===i.id)||await this.addPullRequestReviewer({pullRequest:n,reviewer:i,isRequired:!0},r);for(let i of n.assignees)o.find(a=>i.id===a.id)||await this.removePullRequestReviewer({pullRequest:n,reviewer:i},r)}async getIssuesForAzureProject(e,r={}){let{page:n,assigneeLogins:o,authorLogin:i,mentionLogin:a,labelNames:u,statusByWorkItemIdByStatusId:l}=e||{},d=n||1,p=Math.min(L(e.pageSize,{fallback:Gn}),Tn),c=["[System.TeamProject] = @project",...On(e.states)];i&&c.push(`[System.CreatedBy] = '${i.replace("'","''")}'`),o&&o[0]&&c.push(`[System.AssignedTo] = '${o[0].replace("'","''")}'`),a&&c.push("[System.Id] IN (@recentMentions)"),u&&u.forEach(A=>c.push(`[System.Tags] Contains '${A}'`));let g=`Select [Microsoft.VSTS.Common.ClosedDate], [Microsoft.VSTS.Common.ResolvedDate] From WorkItems Where ${c.join(" AND ")} order by [System.CreatedDate] desc`,m=await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/wiql?api-version=6.0`,body:JSON.stringify({query:g}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}}),h=m.body.workItems.slice((d-1)*p,p*d).map(A=>A.id),y=m.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:`${C(this.config,r)}/${encodeURIComponent(e.namespace)}/${encodeURIComponent(e.project)}/_apis/wit/workitemsbatch?api-version=6.0`,body:JSON.stringify({ids:h,$expand:"Links"}),method:"POST",headers:{...q(this.config,r),"Content-Type":"application/json"}});return{pageInfo:{hasNextPage:P,nextPage:P?d+1:null,currentPage:d,totalCount:y,totalPages:f},data:v.body.value.map(A=>Bn(e.namespace,e.project,A,l||{}))}}async getPermissionsForRepos(e,r={}){let{namespace:n,repos:o}=e,i={4:["canPush","canCreateWebhook"],1024:["isAdmin"],2048:["isAdmin"],4096:["isAdmin"],8192:["isAdmin"]},a=p=>{let c="2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87",g=`repoV2/${p.projectId}/${p.id}`;return Object.keys(i).map(m=>({securityNamespaceId:c,token:g,permissions:m}))},u={alwaysAllowAdministrators:!1,evaluations:o.flatMap(a)};return{data:(await this.config.request({method:"POST",url:`${C(this.config,r)}/${encodeURIComponent(n)}/_apis/security/permissionevaluationbatch?api-version=7.0`,body:JSON.stringify(u),headers:{...q(this.config,r),"Content-Type":"application/json"}})).body.evaluations.reduce((p,c)=>{let[,g,m]=c.token.split("/"),h=`${g}/${m}`,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:`${C(this.config,n)}/${encodeURIComponent(e.project.namespace)}/${encodeURIComponent(e.project.name)}/_apis/wit/workitems/${e.id}?api-version=6.0`,body:JSON.stringify(r),headers:{...q(this.config,n),"Content-Type":"application/json-patch+json"}})}async setIssueStatus(e,r={}){let{issue:n,status:o}=e,i=[{op:"add",path:"/fields/System.State",value:o.name}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue status")}async setIssueAssignee(e,r={}){let{issue:n,assignee:o}=e,i=[{op:"add",path:"/fields/System.AssignedTo",value:o?.name??""}];if(!(await this.updateIssue(n,i,r)).body.fields?.["System.State"])throw new Error("Could not set issue assignee")}async setIssueLabels(e,r={}){let{issue:n,labels:o}=e,a=[{op:"replace",path:"/fields/System.Tags",value:o.map(l=>l.name).join(";")}];if(!(await this.updateIssue(n,a,r)).body.fields?.["System.Tags"])throw new Error("Could not set issue tags")}async getIssueTypesForAzureProject(e,r={}){if(!e.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/workitemtypes?api-version=6.0`,headers:{...q(this.config,r)}})).body.value}}async getLabelsForProject(e,r={}){let{namespace:n,project:o}=e;return{data:(await this.config.request({url:`${C(this.config,r)}/${encodeURIComponent(n)}/${encodeURIComponent(o||"")}/_apis/wit/tags?api-version=6.0`,headers:{...q(this.config,r)}})).body.value.map(a=>({color:null,description:null,id:a.id,name:a.name,url:a.url}))}}async getPullRequestForRepo(e,r={}){let{repo:n,number:o}=e;if(!n.project)throw new Error('Azure DevOps requires a "project" (name or ID) for this function.');let i=await this.config.request({url:`${this.getRepoApiUrl(n.namespace,n.project,n.name,r)}/pullrequests/${o}?api-version=7.1`,headers:q(this.config,r)}),a=await this.fetchRemoteInfoByRepoId(e.includeRemoteInfo,[{namespace:n.namespace,pullRequests:[i.body]}],r);return{data: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],g=1e3,m=[],h=0;for(;;){let S=(await this.config.request({url:`${n}/pullrequests/${e.pullRequestId}/iterations/${c.id}/changes?api-version=7.1&$top=${g}&$skip=${h}`,headers:o})).body.changeEntries??[];if(S.length===0||(m.push(...S),S.length<g))break;h+=S.length}if(m.length===0)return"";let y=5,f=[],P=new TextDecoder,v=w=>w instanceof ArrayBuffer?P.decode(w):typeof w=="string"?w:"",A=async(w,S)=>{try{let 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""}},D=w=>{if(typeof w=="number")return{add:(w&1)!==0,rename:(w&8)!==0,delete:(w&16)!==0};let S=w.toLowerCase().split(",").map(pe=>pe.trim());return{add:S.includes("add"),rename:S.includes("rename"),delete:S.includes("delete")}};for(let w=0;w<m.length;w+=y){let S=m.slice(w,w+y),pe=await Promise.all(S.map(async fe=>{let{add:Re,rename:kt,delete:de}=D(fe.changeType),Le=fe.originalPath??fe.item.originalPath,T=fe.item.path,Fe=de?T??Le??"":T??"",Br=kt||de?Le??Fe:Fe,[cn,mn]=await Promise.all([Re?Promise.resolve(""):A(Br,l),de?Promise.resolve(""):A(Fe,d)]),gn=Re?"/dev/null":`a${Br}`,hn=de?"/dev/null":`b${Fe}`;return(0,ts.createTwoFilesPatch)(gn,hn,cn,mn)}));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:Mt(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=Wt(e.threadId),p=e.pullRequest.repository.owner.login,c=e.pullRequest.repository.project,g=e.pullRequest.repository.name,m=String(e.pullRequest.id);if(d.namespace!==p||d.project!==c||d.repoName!==g||d.prId!==m)throw new Error(`Azure thread ID context mismatch: threadId targets ${d.namespace}/${d.project}/${d.repoName} pull request ${d.prId}, but input.pullRequest targets ${p}/${c}/${g} pull request ${m}.`);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 Mt(p,c,g,Number(m),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 Yr(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=Zr(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=Zr(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=Wt(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=Wt(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)=>Mt(n,o,i,a,f,P),g=f=>Yr(n,o,i,a,f),m=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 A=v.author?.id;if(!A)continue;let D=P.filter(T=>T.id!==v.id),w=f.threadContext,S=w?.rightFileStart?{side:"RIGHT",start:w.rightFileStart,end:w.rightFileEnd}:w?.leftFileStart?{side:"LEFT",start:w.leftFileStart,end:w.leftFileEnd}:null,pe=S?.end?.line??S?.start.line??null,fe=S?.start&&S.end&&S.start.line!==S.end.line?S.start.line:null,Re=w?.filePath??"",kt=Re.startsWith("/")?Re.slice(1):Re,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:kt,replies:D.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:kn.has(_n(f.status)),line:pe,startLine:fe,side:S?.side??null,threadId:g(f.id)},Le=m.get(A);Le?Le.push(de):m.set(A,[de])}let h=[],y=new Set;for(let f of d.body.value){if(f.hasDeclined)continue;let P=f.vote??0,v=m.get(f.id);P===0&&!v?.length||(h.push({id:f.id,author:he(f),body:"",createdAt:null,url:"",reviewComments:v??[]}),y.add(f.id))}for(let[f,P]of m){if(y.has(f)||!P.length)continue;let v=P[0].author;v&&h.push({id:f,author:v,body:"",createdAt:null,url:"",reviewComments:P})}return{data:h}}};var G=(s,t={})=>R(t.token||s.token,t.isPAT||s.isPAT);var O="https://api.bitbucket.org/2.0",jn={OPEN:"OPEN",MERGED:"MERGED",DECLINED:"CLOSED",SUPERSEDED:"CLOSED"},Fn={OPEN:["OPEN"],MERGED:["MERGED"],CLOSED:["DECLINED","SUPERSEDED"]},We=50,rs=s=>{let t=!s||s.length===0?["OPEN"]:Array.from(new Set(s.flatMap(r=>Fn[r]))),e=t.map(r=>`state="${r}"`).join(" OR ");return t.length>1?`(${e})`:e},Qn=s=>s.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),ss=s=>{let t=s?.trim();if(!t)return null;let e=Qn(t);return`(title ~ "${e}" OR description ~ "${e}")`},ns=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}),os=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},Ht=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}),Vt=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:jn[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:os(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:os(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}}},Mn=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}}},we=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:Ht(r.body)}}async getRepos(t,e={}){let r=[],n=[];return await Promise.all(t.map(async o=>{try{let i=await this.getRepo(o,e);r.push(i.data)}catch(i){n.push({input:o,error:i})}})),{data:r,errors:n}}async getReposForWorkspace(t,e={}){let r=new URL(`${O}/repositories/${encodeURIComponent(t.workspace)}`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",$.toString()),t.minimumRole&&r.searchParams.set("role",t.minimumRole);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(Ht)}}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:Mn(u)}})}}async getReposForCurrentUser(t,e={}){let r=new URL(`${O}/repositories`);r.searchParams.set("role","member"),r.searchParams.set("pagelen",$.toString()),t.cursor&&r.searchParams.set("after",t.cursor);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("after")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(Ht)}}async getBranches(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/branches`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",$.toString());let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>{let a=new Date(i.target.date);return{name:i.name,commit:{oid:i.target.hash,authoredDate:a,committedDate:a}}})}}async getTags(t,e={}){let r=new URL(`${O}/repositories/${t.repo.namespace}/${t.repo.name}/refs/tags`);r.searchParams.set("pagelen",$.toString()),t.cursor&&r.searchParams.set("page",t.cursor);let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next,i=null;return n.body.next&&(i=new URL(n.body.next).searchParams.get("page")),{pageInfo:{hasNextPage:o,endCursor:i},data:n.body.values.map(a=>{let u=new Date(a.target.date);return{name:a.name,commit:{oid:a.target.hash,authoredDate:u,committedDate:u}}})}}async getWorkspacesForCurrentUser(t={},e={}){let r=new URL(`${O}/user/workspaces`);r.searchParams.set("page",t?.page?.toString()||"1"),r.searchParams.set("pagelen","50"),t?.administrator!==void 0&&r.searchParams.set("administrator",t.administrator.toString());let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug}))}}async getWorkspacesForUser(t,e={}){let r=new URL(`${O}/user/permissions/workspaces`);r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen","50");let n=await this.config.request({url:r.toString(),headers:G(this.config,e)}),o=!!n.body.next;return{pageInfo:{hasNextPage:o,nextPage:o?n.body.page+1:null},data:n.body.values.map(i=>({id:i.workspace.uuid,slug:i.workspace.slug,name:i.workspace.name}))}}async getPullRequestsForUserAndWorkspace(t,e={}){let r=new URL(`${O}/workspaces/${t.workspaceSlug}/pullrequests/${t.userId}`);r.searchParams.set("fields","+values.participants,+values.destination.repository.links.clone.*,+values.source.repository.links.clone.*"),r.searchParams.set("page",t.page?.toString()||"1"),r.searchParams.set("pagelen",L(t.pageSize,{fallback:We,max:We}).toString());let n=[rs(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=ss(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:ns(i.body),data:i.body.values.map(Vt)}}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=rs(t.states);n.length&&(o+=` AND (${n.join(t.useOrFilter?" OR ":" AND ")})`);let i=ss(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(Vt(o))}),{pageInfo:ns(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:me(i)}),completeness:i=>i.body.next?"partial":"complete"}),o=[];return r.forEach(({result:i})=>{i.body.values.forEach(a=>{o.push(Vt(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]: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 Je={};H(Je,{normalizePermissions:()=>Jt,restApiPullRequestToCommonPullRequest:()=>Wn});var Wn=s=>Te(s),Jt=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}},is=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}),as=50,Hn={OPEN:"OPEN",MERGED:"MERGED",CLOSED:"DECLINED"},us=s=>{if(!s||s.length===0)return"OPEN";let t=Array.from(new Set(s.map(e=>Hn[e])));return t.length===1?t[0]:"ALL"},ls=(s,t)=>typeof s!="number"||t<=0?null:Math.floor(s/t)+1,qe=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:g})=>i?i===p:a===c||a===d||a===g);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:is(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(is)}}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:Jt(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",us(t.states)),r.searchParams.set("start",t.page?.toString()||"0"),r.searchParams.set("limit",L(t.pageSize,{fallback:as}).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:ls(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:me(i)}),completeness:i=>i.body.isLastPage?"complete":"partial"}),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",us(t.states)),r.searchParams.set("start",t.page?.toString()||"0");let n=L(t.pageSize,{fallback:as});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:ls(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 Ss=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 Vn={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]},ps=15,ds=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=Vn[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",Jn=`${Xe}/graphql`,Ze=`
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=`
3
3
  description
4
4
  dueOn
5
5
  id
@@ -7,7 +7,7 @@ number
7
7
  state
8
8
  title
9
9
  url
10
- `,Kn=`
10
+ `,ro=`
11
11
  ... on CheckRun {
12
12
  completedAt
13
13
  conclusion
@@ -21,7 +21,7 @@ color
21
21
  description
22
22
  id
23
23
  name
24
- `,cs=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.")},Xn=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),cs(e),Ke.test(e)&&(e=e.replace(Ke,"")),`${e}/api/graphql`):Jn},X=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),cs(e),Ke.test(e)&&(e=e.replace(Ke,"")),`${e}/api/v3`):Xe},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:Xn(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},Zn={user:!0,"user:email":!0,"read:user":!0},re=s=>s.some(t=>Zn[t]),Q=(s=!1,t=!1,e)=>`
24
+ `,hs=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.")},so=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),hs(e),Ke.test(e)&&(e=e.replace(Ke,"")),`${e}/api/graphql`):to},X=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),hs(e),Ke.test(e)&&(e=e.replace(Ke,"")),`${e}/api/v3`):Xe},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:so(s,e),method:"POST",headers:r,body:JSON.stringify(t)})},no={user:!0,"user:email":!0,"read:user":!0},re=s=>s.some(t=>no[t]),Q=(s=!1,t=!1,e)=>`
25
25
  __typename
26
26
  ${ae(e,["graphQLId"],"id")}
27
27
  ${ae(e,["id"],"databaseId")}
@@ -30,7 +30,7 @@ ${ae(e,["name","username"],"login")}
30
30
  ${t?ae(e,["email"],"email"):""}
31
31
  ${ae(e,["avatarUrl"],`avatarUrl${s?"(size: $avatarSize)":""}`)}
32
32
  ${ae(e,["url"],"url")}
33
- `,Yn=(s=!1)=>`
33
+ `,oo=(s=!1)=>`
34
34
  latestReviews(first: 100) {
35
35
  nodes {
36
36
  author {
@@ -38,20 +38,20 @@ latestReviews(first: 100) {
38
38
  ${Q(!1,s)}
39
39
  }
40
40
  ... on EnterpriseUserAccount {
41
- ${Kt(!1)}
41
+ ${Yt(!1)}
42
42
  }
43
43
  }
44
44
  state
45
45
  }
46
46
  }
47
- `,ms=(s=!1)=>`
47
+ `,fs=(s=!1)=>`
48
48
  __typename
49
49
  id
50
50
  databaseId
51
51
  login
52
52
  avatarUrl${s?"(size: $avatarSize)":""}
53
53
  url
54
- `,Kt=(s=!1)=>`
54
+ `,Yt=(s=!1)=>`
55
55
  __typename
56
56
  id
57
57
  login
@@ -69,10 +69,10 @@ author {
69
69
  ${Q(!1,t)}
70
70
  }
71
71
  ... on Bot {
72
- ${ms(!1)}
72
+ ${fs(!1)}
73
73
  }
74
74
  ... on EnterpriseUserAccount {
75
- ${Kt(!1)}
75
+ ${Yt(!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")?Kn:""}
88
+ ${!e||K(e,"CHECK_RUN")?ro:""}
89
89
  ... on StatusContext {
90
90
  context
91
91
  createdAt
@@ -161,7 +161,7 @@ reviewRequests(first: 100) {
161
161
  }
162
162
  }
163
163
  }
164
- ${!e||K(e,"LATEST_REVIEWS")?Yn(t):""}
164
+ ${!e||K(e,"LATEST_REVIEWS")?oo(t):""}
165
165
  additions
166
166
  deletions
167
167
  changedFiles
@@ -176,7 +176,7 @@ labels(first: 100) {
176
176
  }
177
177
  }
178
178
  ${!e||K(e,"VIEWER_CAN_MERGE_AS_ADMIN")?"viewerCanMergeAsAdmin":""}
179
- `,eo=(s=!1,t)=>`
179
+ `,io=(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
- ${ms(!1)}
188
+ ${fs(!1)}
189
189
  }
190
190
  ... on EnterpriseUserAccount {
191
- ${Kt(!1)}
191
+ ${Yt(!1)}
192
192
  }
193
193
  }
194
194
  closedAt
@@ -224,7 +224,7 @@ labels(first: 100) {
224
224
  ${Ye}
225
225
  }
226
226
  }
227
- `,to={"-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"},ro=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),Xt=s=>{let t=[];return(s.match(ro)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];to[n]&&t.push(r)}}),t},Zt="is:open",gs=s=>{if(!s||s.length===0)return Zt;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"},hs=s=>{if(!s||s.length===0)return Zt;let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?"":r?"is:closed":"is:open"},Yt=(s,t,e,r)=>{let n=s==="issue",o=r.stateQualifier??Zt;return{query:`
227
+ `,ao={"-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"},uo=new RegExp('(([^\\s]+:)?\\"(?:[^\\"\\\\]|\\\\.)*\\"?)|([^\\"\\s]+)',"g"),er=s=>{let t=[];return(s.match(uo)??[]).forEach(r=>{if(r.includes(":")&&r!="is:closed"){let n=r.split(":")[0];ao[n]&&t.push(r)}}),t},tr="is:open",Rs=s=>{if(!s||s.length===0)return tr;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"},Is=s=>{if(!s||s.length===0)return tr;let t=new Set(s),e=t.has("OPEN"),r=t.has("CLOSED");return e&&r?"":r?"is:closed":"is:open"},rr=(s,t,e,r)=>{let n=s==="issue",o=r.stateQualifier??tr;return{query:`
228
228
  query SearchIssuesOrPullRequests($query: String! $after: String) {
229
229
  search(type:ISSUE query:$query first: ${r.maxPageSize} after:$after) {
230
230
  pageInfo {
@@ -233,18 +233,18 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
233
233
  }
234
234
  nodes {
235
235
  ... on ${n?"Issue":"PullRequest"} {
236
- ${n?eo(r.supportsEmail,r.enterpriseVersion??null):et(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
236
+ ${n?io(r.supportsEmail,r.enterpriseVersion??null):et(r.supportsDrafts??!1,r.supportsEmail,r.enterpriseVersion??null)}
237
237
  }
238
238
  }
239
239
  }
240
- }`,variables:{query:`is:${s} ${o} ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},so="Field 'isDraft' doesn't exist on type 'PullRequest'",tt=(s=[])=>s.some(t=>t?.message===so),no=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,oo=`
240
+ }`,variables:{query:`is:${s} ${o} ${r.includeFromArchivedRepos?"":"archived:false"} ${t}`,after:e}}},lo="Field 'isDraft' doesn't exist on type 'PullRequest'",tt=(s=[])=>s.some(t=>t?.message===lo),po=/@@ -(\d+)(?:,\d+ | )\+(\d+)(?:,\d+ | )@@(?:\\n)?/,co=`
241
241
  \
242
- +`,fs=(s,t,e,r)=>{let n=no.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(oo,`
242
+ +`,bs=(s,t,e,r)=>{let n=po.exec(s);if(!n||!n[0]||!n[1])return[];let o=parseInt(n[1],10),i=parseInt(n[2],10),a=s.replace(co,`
243
243
  +`).split(`
244
- `).slice(1),u=o-1,l=i-1,d=a.map(g=>{let m,h;switch(g[0]){case"-":{m="DELETED",u+=1,h=`${g.slice(1)}
245
- `;break}case"+":{m="ADDED",l+=1,h=`${g.slice(1)}
246
- `;break}default:m="UNMODIFIED",l+=1,u+=1,h=`${g}
247
- `}return{line:h,oldLineNumber:m!=="ADDED"?u:null,newLineNumber:m!=="DELETED"?l:null,type:m}}),p=e,c=t;if(p!==null&&c!==null&&r!==null&&p<c){let g=0,m=d.length,h=r==="LEFT"?"oldLineNumber":"newLineNumber";for(let y=0;y<d.length;y++){let P=d[y][h];P===p?g=y:P===c&&(m=y)}d=d.slice(g,m+1)}return d},Rs=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 Is=`mutation DeleteIssueComment(
244
+ `).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
+ `;break}case"+":{g="ADDED",l+=1,h=`${m.slice(1)}
246
+ `;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},ys=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 Ps=`mutation DeleteIssueComment(
248
248
  $issueCommentId: ID!
249
249
  ) {
250
250
  deleteIssueComment(input: {
@@ -252,7 +252,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
252
252
  }) {
253
253
  clientMutationId
254
254
  }
255
- }`,bs=`mutation DeletePullRequestReviewComment(
255
+ }`,ws=`mutation DeletePullRequestReviewComment(
256
256
  $pullRequestReviewCommentId: ID!
257
257
  ) {
258
258
  deletePullRequestReviewComment(input: {
@@ -262,7 +262,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
262
262
  id
263
263
  }
264
264
  }
265
- }`,ys=`mutation UpdateIssueComment(
265
+ }`,qs=`mutation UpdateIssueComment(
266
266
  $issueCommentId: ID!,
267
267
  $body: String!
268
268
  ) {
@@ -275,7 +275,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
275
275
  body
276
276
  }
277
277
  }
278
- }`,Ps=`mutation ResolveReviewThread(
278
+ }`,vs=`mutation ResolveReviewThread(
279
279
  $pullRequestReviewThreadId: ID!
280
280
  ) {
281
281
  resolveReviewThread(input: {
@@ -286,7 +286,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
286
286
  isResolved
287
287
  }
288
288
  }
289
- }`,ws=`mutation UnresolveReviewThread(
289
+ }`,Es=`mutation UnresolveReviewThread(
290
290
  $pullRequestReviewThreadId: ID!
291
291
  ) {
292
292
  unresolveReviewThread(input: {
@@ -297,7 +297,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
297
297
  isResolved
298
298
  }
299
299
  }
300
- }`,qs=`mutation UpdatePullRequestReviewComment(
300
+ }`,Ss=`mutation UpdatePullRequestReviewComment(
301
301
  $pullRequestReviewCommentId: ID!,
302
302
  $body: String!
303
303
  ) {
@@ -310,7 +310,7 @@ query SearchIssuesOrPullRequests($query: String! $after: String) {
310
310
  body
311
311
  }
312
312
  }
313
- }`;var vs=s=>`
313
+ }`;var Cs=s=>`
314
314
  query GetPullRequestComments(
315
315
  $namespace: String!
316
316
  $name: String!
@@ -356,7 +356,7 @@ query GetPullRequestComments(
356
356
  }
357
357
  }
358
358
  }
359
- `;var er=`
359
+ `;var sr=`
360
360
  id
361
361
  databaseId
362
362
  owner {
@@ -369,7 +369,7 @@ defaultBranchRef {
369
369
  name
370
370
  }
371
371
  viewerPermission
372
- `,io={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},ao={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},uo={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},lo={OPEN:"OPEN",CLOSED:"CLOSED"},po=["ADMIN","MAINTAIN","TRIAGE","WRITE"],sr=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),co=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),tr=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:co(s.viewerPermission)}),mo=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),Es=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:mo(s.permissions)}),go=s=>({path:s.path,isDirectory:s.type==="tree"}),ho={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},fo={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},W=(s,t=fo)=>{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},Ro=(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]},Io=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],rr=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:io[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:ho[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:Io(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:Ro(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:uo[s.mergeStateStatus]??ao[s.mergeable],milestone:s.milestone?nr(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(sr)??[],permissions:{canMerge:po.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},bo=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:g,databaseId:m,fullDatabaseId:h,id:y,path:f,publishedAt:P,url:v}=p,A=o??u,D=i??l,w=a??d;return{author:c?{avatarUrl:c.avatarUrl,email:null,name:c.login}:null,body:g,createdAt:P?new Date(P):null,diffLines:fs(p.diffHunk,A,D,w),id:h??m.toString(),isOutdated:r,isResolved:n,graphQLId:y,threadId:t,filename:f,replies:e.nodes?.filter(k).slice(1).map(yo)??[],url:v,line:A,startLine:D,side:w}},yo=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}),Po=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:lo[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?nr(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(sr)??[]}},nr=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}),ve=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(Xe)?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=Mr(e.fields),o=await this.getScopes(r),i=await b(this.config,{query:`
372
+ `,go={APPROVED:"APPROVED",CHANGES_REQUESTED:"CHANGES_REQUESTED",COMMENTED:"COMMENTED",REVIEW_REQUESTED:"REVIEW_REQUESTED"},mo={MERGEABLE:"MERGEABLE",CONFLICTING:"CONFLICTS",UNKNOWN:"UNKNOWN"},ho={BEHIND:"BEHIND",BLOCKED:"BLOCKED",UNKNOWN:"UNKNOWN_AND_BLOCKED",UNSTABLE:"UNSTABLE",CLEAN:null,DIRTY:null,DRAFT:null,HAS_HOOKS:null},fo={OPEN:"OPEN",CLOSED:"CLOSED"},Ro=["ADMIN","MAINTAIN","TRIAGE","WRITE"],ir=s=>({color:`#${s.color}`,description:s.description,graphQLId:s.id,id:null,name:s.name}),Io=s=>({canCreateWebhook:s==="ADMIN",canPush:s==="ADMIN"||s==="MAINTAIN"||s==="WRITE",isAdmin:s==="ADMIN"}),nr=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:Io(s.viewerPermission)}),bo=s=>({canCreateWebhook:s.admin,canPush:s.admin||s.maintain||s.push,isAdmin:s.admin}),Ds=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:bo(s.permissions)}),yo=s=>({path:s.path,isDirectory:s.type==="tree"}),Po={OPEN:"OPEN",CLOSED:"CLOSED",MERGED:"MERGED"},wo={id:!0,graphQLId:!0,name:!0,username:!0,email:!0,avatarUrl:!0,url:!0},W=(s,t=wo)=>{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},qo=(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]},vo=s=>({ERROR:"ERROR",EXPECTED:"PENDING",FAILURE:"FAILED",PENDING:"PENDING",SUCCESS:"SUCCESS"})[s],or=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:go[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:Po[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:vo(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:qo(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:ho[s.mergeStateStatus]??mo[s.mergeable],milestone:s.milestone?ar(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(ir)??[],permissions:{canMerge:Ro.includes(s.repository.viewerPermission),canMergeAndBypassProtections:s.viewerCanMergeAsAdmin??!1}}},Eo=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,$=o??u,A=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:bs(p.diffHunk,$,A,w),id:h??g.toString(),isOutdated:r,isResolved:n,graphQLId:y,threadId:t,filename:f,replies:e.nodes?.filter(k).slice(1).map(So)??[],url:v,line:$,startLine:A,side:w}},So=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}),Co=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:fo[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?ar(s.milestone):null,labels:s.labels?.nodes?.filter(k).map(ir)??[]}},ar=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(Xe)?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
373
  query getCurrentUser {
374
374
  viewer {
375
375
  ${Q(!1,re(o),n)}
@@ -389,7 +389,7 @@ query getAccountsForRepo($owner: String!, $name: String! $cursor: String, $first
389
389
  }
390
390
  }
391
391
  }
392
- `,variables:{owner:o,name:i,cursor:a,first:$}},r);if(!u.body.data)throw new I("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(l=>W(l))??[]}}async getUserForCommit(e,r={}){let n=await b(this.config,{query:`
392
+ `,variables:{owner:o,name:i,cursor:a,first:C}},r);if(!u.body.data)throw new I("Could not fetch accounts for repo",u.body.errors);return{pageInfo:u.body.data.repository?.assignableUsers?.pageInfo??{endCursor:null,hasNextPage:!1},data:u.body.data.repository?.assignableUsers?.nodes?.map(l=>W(l))??[]}}async getUserForCommit(e,r={}){let n=await b(this.config,{query:`
393
393
  query getUserForCommit(
394
394
  $owner: String!
395
395
  $name: String!
@@ -435,7 +435,7 @@ mutation createCommitOnBranch(
435
435
  }
436
436
  }
437
437
  }
438
- `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([d,p])=>({contents:Ss.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:`
438
+ `,variables:{branchName:u.name,expectedHeadOid:u.oid,fileChanges:{additions:Object.entries(i).map(([d,p])=>({contents:As.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
439
  query getAccountForEmail($query: String! $avatarSize: Int) {
440
440
  search(query: $query, type: USER, first: 1) {
441
441
  nodes {
@@ -470,7 +470,7 @@ query getOrgsForCurrentUser($cursor: String, $first: Int!) {
470
470
  }
471
471
  }
472
472
  }
473
- `,variables:{cursor:e.cursor,first:$}},r);if(!n.body.data)throw new I("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.body.data.viewer.organizations.pageInfo,data:o.map(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,r={}){let n=await b(this.config,{query:`
473
+ `,variables:{cursor:e.cursor,first:C}},r);if(!n.body.data)throw new I("Could not fetch orgs for current user",n.body.errors);let o=n.body.data.viewer.organizations.nodes||[];return{pageInfo:n.body.data.viewer.organizations.pageInfo,data:o.map(i=>({id:i.databaseId.toString(),graphQLId:i.id,username:i.login,name:i.name||null,email:i.email||null,avatarUrl:i.avatarUrl}))}}async getOrgMembers(e,r={}){let n=await b(this.config,{query:`
474
474
  query getOrgMember($cursor: String, $first: Int!, $login: String!) {
475
475
  viewer {
476
476
  organization(login: $login) {
@@ -486,22 +486,22 @@ query getOrgMember($cursor: String, $first: Int!, $login: String!) {
486
486
  }
487
487
  }
488
488
  }
489
- `,variables:{cursor:e.cursor,first:$,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:`
489
+ `,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
490
  query getRepo($owner: String!, $name: String!) {
491
491
  repository(owner: $owner, name: $name) {
492
- ${er}
492
+ ${sr}
493
493
  }
494
494
  }
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:tr(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},d)=>`
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:nr(n.body.data.repository)}}async getRepos(e,r={}){let n=e.map(({namespace:u,name:l},d)=>`
496
496
  getRepo_${d}: repository(owner: "${u}", name: "${l}") {
497
- ${er}
497
+ ${sr}
498
498
  }
499
499
  `).join(`
500
500
  `),o=await b(this.config,{query:`
501
501
  query batchGetRepos {
502
502
  ${n}
503
503
  }
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(tr(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,Es)}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,Es)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await b(this.config,{query:`
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(nr(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,Ds)}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,Ds)}async getReposForUsernames(e,r={}){if(!e.usernames.length)return{pageInfo:{endCursor:null,hasNextPage:!1},data:[]};let n=await b(this.config,{query:`
505
505
  query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
506
506
  search(query: $query, type: REPOSITORY, first: $first, after: $cursor) {
507
507
  pageInfo {
@@ -510,12 +510,12 @@ query getReposForUsernames($query: String!, $cursor: String, $first: Int!) {
510
510
  }
511
511
  nodes {
512
512
  ... on Repository {
513
- ${er}
513
+ ${sr}
514
514
  }
515
515
  }
516
516
  }
517
517
  }
518
- `,variables:{query:`fork:true ${e.usernames.map(i=>`user:${i}`).join(" ")}`,cursor:e.cursor,first:$}},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(tr)}}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:`
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(nr)}}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
519
  query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: String, $first: Int!) {
520
520
  repository(owner: $owner, name: $name) {
521
521
  refs(refPrefix: $refPrefix first: $first after: $cursor) {
@@ -536,7 +536,7 @@ query getRefs($owner: String!, $name: String!, $refPrefix: String!, $cursor: Str
536
536
  }
537
537
  }
538
538
  }
539
- `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:$}},n),i=o.body.data?.repository;if(!i)throw new I("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,r={}){return this.getRefs("refs/heads/",e,r)}async getTags(e,r={}){return this.getRefs("refs/tags/",e,r)}async getBlame(e,r={}){let n=await b(this.config,{query:`
539
+ `,variables:{owner:r.repo.namespace,name:r.repo.name,refPrefix:e,cursor:r.cursor,first:C}},n),i=o.body.data?.repository;if(!i)throw new I("Ref repository not found.",o.body.errors);let a=i.refs;return a?{pageInfo:a.pageInfo,data:(a.nodes||[]).map(u=>{let l=u.target?.oid?u.target:null;return{name:u.name,commit:l?{oid:l.oid,authoredDate:new Date(l.authoredDate),committedDate:new Date(l.committedDate)}:null}})}:{pageInfo:{endCursor:null,hasNextPage:!1},data:[]}}async getBranches(e,r={}){return this.getRefs("refs/heads/",e,r)}async getTags(e,r={}){return this.getRefs("refs/tags/",e,r)}async getBlame(e,r={}){let n=await b(this.config,{query:`
540
540
  query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
541
541
  repository(owner: $owner, name: $name) {
542
542
  object(expression: $ref) {
@@ -575,7 +575,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
575
575
  }
576
576
  }
577
577
  }
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=re(o),a=gs(e.states),u=p=>{let c=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return Yt("pr",c,e.cursor,{maxPageSize:e.maxPageSize??ps,supportsEmail:i,supportsDrafts:p,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos,stateQualifier:a})},l=await b(this.config,u(!0),r);l.body.errors&&tt(l.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(l=await b(this.config,u(!1),r));let{data:d}=l.body;if(!d)throw new I("Could not search pull requests",l.body.errors);return{pageInfo:{hasNextPage:d.search.pageInfo.hasNextPage,endCursor:d.search.pageInfo.endCursor},data:x(d.search.nodes?.filter(k).map(rr)||[],e.states)}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=re(o),a=hs(e.states),u=await b(this.config,Yt("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??ds,enterpriseVersion:n,stateQualifier:a}),r),{data:l}=u.body;if(!l)throw new I("Could not search issues",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(k).map(Po)||[]}}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},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,g=Xt(l||"");return a.forEach(m=>{g.push(`repo:${m.namespace}/${m.name}`)}),n&&n.forEach(m=>{g.push(`assignee:${m}`)}),o&&g.push(`updated:<${o}`),i&&g.push(`author:${i}`),u&&g.push(`review-requested:${u}`),d&&g.push(`mentions:${d}`),p&&p.forEach(m=>{g.push(`label:"${m}"`)}),this.searchPullRequests({query:`sort:updated ${g.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=re(o),a=p=>({query:`query getPullRequest(
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=re(o),a=Rs(e.states),u=p=>{let c=p&&typeof e.isDraft=="boolean"?`${e.query} draft:${e.isDraft}`:e.query;return rr("pr",c,e.cursor,{maxPageSize:e.maxPageSize??gs,supportsEmail:i,supportsDrafts:p,enterpriseVersion:n,includeFromArchivedRepos:e.includeFromArchivedRepos,stateQualifier:a})},l=await b(this.config,u(!0),r);l.body.errors&&tt(l.body.errors)&&(this.config.baseUrl||r.baseUrl)&&(l=await b(this.config,u(!1),r));let{data:d}=l.body;if(!d)throw new I("Could not search pull requests",l.body.errors);return{pageInfo:{hasNextPage:d.search.pageInfo.hasNextPage,endCursor:d.search.pageInfo.endCursor},data:x(d.search.nodes?.filter(k).map(or)||[],e.states)}}async searchIssues(e,r={}){let n=await this.getEnterpriseVersion(r),o=await this.getScopes(r),i=re(o),a=Is(e.states),u=await b(this.config,rr("issue",e.query,e.cursor,{supportsEmail:i,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize??ms,enterpriseVersion:n,stateQualifier:a}),r),{data:l}=u.body;if(!l)throw new I("Could not search issues",u.body.errors);return{pageInfo:{hasNextPage:l.search.pageInfo.hasNextPage,endCursor:l.search.pageInfo.endCursor},data:l.search.nodes?.filter(k).map(Co)||[]}}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},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=er(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=re(o),a=p=>({query:`query getPullRequest(
579
579
  $owner: String!
580
580
  $name: String!
581
581
  $number: Int!
@@ -588,7 +588,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
588
588
  ${et(p,i,n)}
589
589
  }
590
590
  }
591
- }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),r);u.body.errors&&tt(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?rr(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=re(o),a=p=>({query:`query getPullRequest(
591
+ }`,variables:{owner:e.repo.namespace,name:e.repo.name,number:e.number}}),u=await b(this.config,a(!0),r);u.body.errors&&tt(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?or(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=re(o),a=p=>({query:`query getPullRequest(
592
592
  $graphQLId: ID!
593
593
  ) {
594
594
  node(id: $graphQLId) {
@@ -596,7 +596,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
596
596
  ${et(p,i,n)}
597
597
  }
598
598
  }
599
- }`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),r);u.body.errors&&tt(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?rr(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!) {
599
+ }`,variables:{graphQLId:e.graphQLId}}),u=await b(this.config,a(!0),r);u.body.errors&&tt(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?or(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
600
  closePullRequest(input: { pullRequestId: $pullRequestGraphQLId }) {
601
601
  pullRequest {
602
602
  id
@@ -669,7 +669,7 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
669
669
  }
670
670
  }
671
671
  }
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:bs,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:Is,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:ys,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:qs,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:Ps,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:ws,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(
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:ws,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:Ps,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:qs,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:Ss,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:vs,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:Es,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
673
  $threadId: ID!,
674
674
  $body: String!
675
675
  ) {
@@ -799,13 +799,13 @@ query getBlame($owner: String!, $name: String!, $ref: String!, $path: String!) {
799
799
  }
800
800
  }
801
801
  }
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,g)=>{if(!g.comments.nodes?.[0]?.pullRequestReview)return c;let m=g.comments.nodes[0].pullRequestReview,h=bo(g);return h&&(c[m.id]||(c[m.id]=[]),c[m.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:vs(o),variables:{namespace:i,name:a,pullRequestNumber:u,cursor:l,first:$}},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(Rs)??[],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(c=>{i.push(`label:"${c}"`)});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},r),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)]),l={},d=[],p=c=>{l[c.id]||(l[c.id]=!0,d.push(c))};return a?.data.forEach(p),u?.data.forEach(p),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:d}}async setPullRequestLabels(e,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!]) {
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=Eo(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:Cs(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(ys)??[],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(c=>{i.push(`label:"${c}"`)});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},r),o==="null"?null:this.searchIssues({query:`assignee:${e.username} ${i.join(" ")}`,cursor:o,includeFromArchivedRepos:e.includeFromArchivedRepos,maxPageSize:e.maxPageSize},r)]),l={},d=[],p=c=>{l[c.id]||(l[c.id]=!0,d.push(c))};return a?.data.forEach(p),u?.data.forEach(p),{pageInfo:{hasNextPage:a?.pageInfo.hasNextPage||u?.pageInfo.hasNextPage||!1,endCursor:`${a?.pageInfo.hasNextPage&&a?.pageInfo.endCursor||"null"};${u?.pageInfo.hasNextPage&&u?.pageInfo.endCursor||"null"}`},data:d}}async setPullRequestLabels(e,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
803
  updatePullRequest(input: { pullRequestId: $pullRequestGraphQLId, labelIds: $labelGraphQLIds }) {
804
804
  pullRequest {
805
805
  id
806
806
  }
807
807
  }
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=Xt(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!) {
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=er(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
809
  closeIssue(input: { issueId: $issueGraphQLId, stateReason: $reason }) {
810
810
  issue {
811
811
  id
@@ -855,7 +855,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
855
855
  }
856
856
  }
857
857
  }
858
- `,variables:{owner:n,name:o,cursor:i,first:$}},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(nr)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await b(this.config,{query:`
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(ar)??[]}}async getLabelsForRepo(e,r={}){let{repo:{namespace:n,name:o},cursor:i}=e,a=await b(this.config,{query:`
859
859
  query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first: Int!) {
860
860
  repository(owner: $owner, name: $name) {
861
861
  labels(first: $first, after: $cursor) {
@@ -869,7 +869,7 @@ query getLabelsForRepo($owner: String!, $name: String! $cursor: String, $first:
869
869
  }
870
870
  }
871
871
  }
872
- `,variables:{owner:n,name:o,cursor:i,first:$}},r);if(!a.body.data)throw new I("Could not fetch labels",a.body.errors);return{pageInfo:a.body.data.repository.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:a.body.data.repository.labels?.nodes?.map(sr)??[]}}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(go)}}};var wo="https://gitlab.com/api/v4",qo="https://gitlab.com/api/graphql",or=/\/api\/v\d+$/,Cs=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(/\/$/,""),Cs(e),or.test(e)||(e=e+"/api/v4"),e):wo},vo=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),Cs(e),or.test(e)&&(e=e.replace(or,"")),`${e}/api/graphql`):qo},E=(s,t,e)=>{let r=R(e.token||s.token);return s.request({url:vo(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},ke=s=>s?.map(t=>`"${t.message}"`).join(", ");var gr=s=>s.split("/").slice(0,-1).join("/"),hr=s=>s.split("/").at(-1)??"",Ds=s=>{let t=parseInt(`${s["x-next-page"]}`,10);return Number.isNaN(t)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:t}},rt=s=>({id:s.id.replace(Ee,""),graphQLId:s.id,namespace:gr(s.fullPath),name:hr(s.fullPath),webUrl:s.webUrl}),xe=s=>({id:s.id.replace(Ee,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:gr(s.fullPath),name:hr(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Eo={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},So={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Us="gid://gitlab/User/",Ee="gid://gitlab/Project/",Co="gid://gitlab/MergeRequest/",Do="gid://gitlab/Issue/",Ao="gid://gitlab/ProjectLabel/",$o="gid://gitlab/Milestone/",Lo="gid://gitlab/Ci::Build/",fr=`
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(ir)??[]}}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(yo)}}};var Do="https://gitlab.com/api/v4",Ao="https://gitlab.com/api/graphql",ur=/\/api\/v\d+$/,$s=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(/\/$/,""),$s(e),ur.test(e)||(e=e+"/api/v4"),e):Do},$o=(s,t)=>{let e=t.baseUrl||s.baseUrl;return e?(e=e.replace(/\/$/,""),$s(e),ur.test(e)&&(e=e.replace(ur,"")),`${e}/api/graphql`):Ao},E=(s,t,e)=>{let r=R(e.token||s.token);return s.request({url:$o(s,e),method:"POST",headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(t)})},ke=s=>s?.map(t=>`"${t.message}"`).join(", ");var st=s=>s.split("/").slice(0,-1).join("/"),nt=s=>s.split("/").at(-1)??"",lr=s=>{let t=parseInt(`${s["x-next-page"]}`,10);return Number.isNaN(t)?{hasNextPage:!1,nextPage:null}:{hasNextPage:!0,nextPage:t}},rt=s=>({id:s.id.replace(fe,""),graphQLId:s.id,namespace:st(s.fullPath),name:nt(s.fullPath),webUrl:s.webUrl}),xe=s=>({id:s.id.replace(fe,""),graphQLId:s.id,httpsUrl:s.httpUrlToRepo,namespace:st(s.fullPath),name:nt(s.fullPath),sshUrl:s.sshUrlToRepo,webUrl:s.webUrl}),Lo={assigned:"assignedMergeRequests",authored:"authoredMergeRequests",reviewRequested:"reviewRequestedMergeRequests"},Uo={CAN_BE_MERGED:"MERGEABLE",CANNOT_BE_MERGED:"CONFLICTS",CANNOT_BE_MERGED_RECHECK:"UNKNOWN",UNCHECKED:"UNKNOWN",CHECKING:"UNKNOWN"};var Os="gid://gitlab/User/",fe="gid://gitlab/Project/",Go="gid://gitlab/MergeRequest/",_s="gid://gitlab/Issue/",To="gid://gitlab/ProjectLabel/",Oo="gid://gitlab/Milestone/",_o="gid://gitlab/Ci::Build/",br=`
873
873
  description
874
874
  dueDate
875
875
  id
@@ -878,7 +878,7 @@ startDate
878
878
  state
879
879
  title
880
880
  webPath
881
- `,ir=`
881
+ `,pr=`
882
882
  id
883
883
  fullPath
884
884
  webUrl
@@ -899,7 +899,7 @@ username
899
899
  publicEmail
900
900
  avatarUrl
901
901
  webUrl
902
- `,Rr=`
902
+ `,yr=`
903
903
  color
904
904
  description
905
905
  id
@@ -910,7 +910,7 @@ httpUrlToRepo
910
910
  fullPath
911
911
  sshUrlToRepo
912
912
  webUrl
913
- `,ar=`
913
+ `,dr=`
914
914
  author {
915
915
  ${se}
916
916
  }
@@ -927,7 +927,7 @@ id
927
927
  iid
928
928
  labels {
929
929
  nodes {
930
- ${Rr}
930
+ ${yr}
931
931
  }
932
932
  }
933
933
  state
@@ -938,9 +938,9 @@ upvotes
938
938
  userNotesCount
939
939
  webUrl
940
940
  milestone {
941
- ${fr}
941
+ ${br}
942
942
  }
943
- `,Uo=`
943
+ `,ko=`
944
944
  stages {
945
945
  nodes {
946
946
  jobs {
@@ -956,7 +956,7 @@ stages {
956
956
  name
957
957
  }
958
958
  }
959
- `,ur=(s,t,e)=>`
959
+ `,cr=(s,t,e)=>`
960
960
  id
961
961
  state
962
962
  author {
@@ -1001,19 +1001,19 @@ reviewers {
1001
1001
  mergeStatusEnum
1002
1002
  labels {
1003
1003
  nodes {
1004
- ${Rr}
1004
+ ${yr}
1005
1005
  }
1006
1006
  }
1007
1007
  ${s?`project { ${Ne} archived } sourceProject { ${Ne} }`:""}
1008
- ${t?`milestone { ${fr} }`:""}
1009
- ${e?`headPipeline { ${Uo} }`:""}
1010
- `,_=s=>`${s.namespace}/${s.name}`,Go=s=>`${s.namespace}/${s.name}`,To=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),Oo=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),lr=s=>({id:s.id.replace(Ee,""),graphQLId:s.id,namespace:gr(s.fullPath),name:hr(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:Oo(s.userPermissions)}),_o=s=>({path:s.path,isDirectory:s.type==="tree"}),ko={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},xo={OPEN:"opened",MERGED:"merged",CLOSED:"closed"},As=s=>{if(!s||s.length===0)return"state: opened";let t=Array.from(new Set(s));return t.length>1?"":`state: ${xo[t[0]]}`},$s=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"}`},ue=100,No=20,Bo=250,st=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,ne=(s,t,e)=>{let r=st(s.avatarUrl,t,e);return{id:s.id.replace(Us,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},Ir=s=>({color:s.color,description:s.description,id:s.id.replace(Ao,""),graphQLId:s.id,name:s.title}),jo=(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,Fo=(s,t,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:ne(s,t,e),state:s.mergeRequestInteraction?.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},pr=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>Fo(i,r,n)):null;return{id:s.id.replace(Co,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:ko[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?ne(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:jo(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(Lo,"")}`}))??[])??[]},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=>ne(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:So[s.mergeStatusEnum],milestone:s.milestone?br(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(Ir)??[],permissions:null}},dr=(s,t,e,r)=>({author:ne(s.author,e,r),assignees:s.assignees.nodes.map(n=>ne(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(Do,""),labels:s.labels?.nodes?.map(Ir)??[],number:s.iid,repository:{id:t.id.replace(Ee,""),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?br(s.milestone,t.webUrl):null}),br=(s,t)=>({id:s.id.replace($o,""),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}),Qo=s=>Buffer.from(JSON.stringify(s),"utf8").toString("base64"),zo=(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}}},Mo=(s,t,e)=>({id:s.id.toString(),graphQLId:`${Us}${s.id}`,name:s.name,username:s.username,email:s.email??null,avatarUrl:st(s.avatar_url,t,e),url:s.web_url}),Ls=(s,t,e)=>({avatarUrl:st(s.avatar_url,t,e)??"",email:null,name:s.name}),Wo=s=>s?.new_line!=null?"RIGHT":s?.old_line!=null?"LEFT":null,Ho=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(`
1008
+ ${t?`milestone { ${br} }`:""}
1009
+ ${e?`headPipeline { ${ko} }`:""}
1010
+ `,_=s=>`${s.namespace}/${s.name}`,xo=s=>`${s.namespace}/${s.name}`,No=s=>/Field '[^']+' (?:doesn'?t|does not) exist on type|Field '[^']+' is not defined|undefined field '[^']+' on type/i.test(s.message),Bo=s=>({canCreateWebhook:s.adminOperations,canPush:s.pushCode,isAdmin:s.adminOperations}),gr=s=>({id:s.id.replace(fe,""),graphQLId:s.id,namespace:st(s.fullPath),name:nt(s.fullPath),webUrl:s.webUrl,httpsUrl:s.httpUrlToRepo,sshUrl:s.sshUrlToRepo,defaultBranch:s.repository?.rootRef?{name:s.repository.rootRef}:null,permissions:Bo(s.userPermissions)}),jo=s=>({path:s.path,isDirectory:s.type==="tree"}),Fo={opened:"OPEN",merged:"MERGED",closed:"CLOSED"},Qo={OPEN:"opened",MERGED:"merged",CLOSED:"closed"},Ls=s=>{if(!s||s.length===0)return"state: opened";let t=Array.from(new Set(s));return t.length>1?"":`state: ${Qo[t[0]]}`},Us=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"}`},ue=100,zo=20,Mo=250,ot=(s,t,e)=>!t&&s?.startsWith("/")?`https://gitlab.com${s}`:t&&s?.startsWith("/")&&e?`${e.replace(/\/+?$/,"")}${s}`:s,ne=(s,t,e)=>{let r=ot(s.avatarUrl,t,e);return{id:s.id.replace(Os,""),graphQLId:s.id,name:s.name,username:s.username,email:s.publicEmail??null,avatarUrl:r,url:s.webUrl}},Pr=s=>({color:s.color,description:s.description,id:s.id.replace(To,""),graphQLId:s.id,name:s.title}),Wo=(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,Ho=(s,t,e)=>{let r={APPROVED:"APPROVED",REQUESTED_CHANGES:"CHANGES_REQUESTED",REVIEWED:"COMMENTED",UNAPPROVED:"REVIEW_REQUESTED",UNREVIEWED:"REVIEW_REQUESTED"};return{reviewer:ne(s,t,e),state:s.mergeRequestInteraction?.reviewState?r[s.mergeRequestInteraction.reviewState]:"REVIEW_REQUESTED"}},mr=(s,t,e,r,n)=>{let o=s.reviewers?.nodes?s.reviewers.nodes.map(i=>Ho(i,r,n)):null;return{id:s.id.replace(Go,""),graphQLId:s.id,title:s.title,description:s.description,number:parseInt(s.iid,10),state:Fo[s.state],commentCount:s.userNotesCount||0,upvoteCount:s.upvotes,author:s.author?ne(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:Wo(a.status,a.allowFailure),stage:i.name??null,startedAt:new Date(a.createdAt),url:`${t.webUrl}/-/jobs/${a.id.replace(_o,"")}`}))??[])??[]},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=>ne(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:Uo[s.mergeStatusEnum],milestone:s.milestone?wr(s.milestone,t.webUrl):null,labels:s.labels?.nodes?.map(Pr)??[],permissions:null}},hr=(s,t,e,r)=>({author:ne(s.author,e,r),assignees:s.assignees.nodes.map(n=>ne(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(_s,""),labels:s.labels?.nodes?.map(Pr)??[],number:s.iid,repository:{id:t.id.replace(fe,""),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?wr(s.milestone,t.webUrl):null}),wr=(s,t)=>({id:s.id.replace(Oo,""),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}),Vo=s=>Buffer.from(JSON.stringify(s),"utf8").toString("base64"),Jo=(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}}},Rr=(s,t,e)=>({id:s.id.toString(),graphQLId:`${Os}${s.id}`,name:s.name,username:s.username,email:s.email??null,avatarUrl:ot(s.avatar_url,t,e),url:s.web_url}),Gs=(s,t,e)=>({avatarUrl:ot(s.avatar_url,t,e)??"",email:null,name:s.name}),Ts=s=>s.replace(/^\/+/,"").split("/")[0]==="groups",Ko=s=>{let t=s.references?.full;if(t){let r=t.includes("#")?t.slice(0,t.lastIndexOf("#")):t;if(r&&!Ts(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||Ts(o)?void 0:o}catch{return}},Xo=(s,t,e)=>{let r=Ko(s);return{author:s.author?Rr(s.author,t,e):null,assignees:(s.assignees??[]).map(n=>Rr(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:`${_s}${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:`${fe}${s.project_id}`,id:s.project_id.toString(),name:r?nt(r):"",owner:{login:r?st(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}},Zo=s=>s?.new_line!=null?"RIGHT":s?.old_line!=null?"LEFT":null,Yo=s=>{let t=s.old_path||s.new_path,e=s.new_path||s.old_path,r=[`diff --git a/${t} b/${e}`];return s.new_file&&s.b_mode?r.push(`new file mode ${s.b_mode}`):s.deleted_file&&s.a_mode?r.push(`deleted file mode ${s.a_mode}`):s.a_mode&&s.b_mode&&s.a_mode!==s.b_mode&&(r.push(`old mode ${s.a_mode}`),r.push(`new mode ${s.b_mode}`)),s.renamed_file&&(r.push(`rename from ${s.old_path}`),r.push(`rename to ${s.new_path}`)),s.diff&&s.diff.length>0?(r.push(`--- ${s.new_file?"/dev/null":`a/${t}`}`),r.push(`+++ ${s.deleted_file?"/dev/null":`b/${e}`}`),`${r.join(`
1011
1011
  `)}
1012
1012
  ${s.diff.endsWith(`
1013
1013
  `)?s.diff:`${s.diff}
1014
1014
  `}`):`${r.join(`
1015
1015
  `)}
1016
- `},Gs="|",mr=(s,t,e,r)=>[s,t,e.toString(),r.toString()].join(Gs),Vo=s=>{let t=s.split(Gs);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]}},cr=(s,t,e,r)=>({author:s.author?Mo(s.author,t,e):null,body:s.body,createdAt:s.created_at?new Date(s.created_at):null,id:mr(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:`
1016
+ `},ks="|",Ir=(s,t,e,r)=>[s,t,e.toString(),r.toString()].join(ks),ei=s=>{let t=s.split(ks);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]}},fr=(s,t,e,r)=>({author:s.author?Rr(s.author,t,e):null,body:s.body,createdAt:s.created_at?new Date(s.created_at):null,id:Ir(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
1017
  query getCurrentUser {
1018
1018
  currentUser {
1019
1019
  ${se}
@@ -1035,7 +1035,7 @@ query getUserForCommit($fullPath: ID!, $oid: String!) {
1035
1035
  }
1036
1036
  }
1037
1037
  }
1038
- `,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=st(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:`
1038
+ `,variables:{fullPath:r,oid:t.oid}},e)).body.data?.project?.repository?.tree?.lastCommit;if(!o)throw new Error("Commit not found.");let i=ot(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
1039
  query getAccountForEmail($email: String!) {
1040
1040
  users(search: $email) {
1041
1041
  nodes {
@@ -1073,19 +1073,19 @@ query getAccountsForRepo(
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=>ne(u,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))??[]}}async getRepo(t,e={}){let r=_(t),n=await E(this.config,{query:`
1074
1074
  query getRepo($fullPath: ID!) {
1075
1075
  project(fullPath: $fullPath) {
1076
- ${ir}
1076
+ ${pr}
1077
1077
  }
1078
1078
  }
1079
- `,variables:{fullPath:r}},e);if(!n.body.data?.project)throw new Error(`Repository ${r} not found`);return{data:lr(n.body.data.project)}}async getReposBase(t,e={}){let n=t.map(_).map((u,l)=>`
1079
+ `,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
1080
  getRepo_${l}: project(fullPath: "${u}") {
1081
- ${ir}
1081
+ ${pr}
1082
1082
  }
1083
1083
  `).join(`
1084
1084
  `),o=await E(this.config,{query:`
1085
1085
  query batchGetRepos {
1086
1086
  ${n}
1087
1087
  }
1088
- `},e);if(!o.body.data)throw new Error(ke(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(lr(d)):a.push({input:u})}),{data:i,errors:a}}async getRepos(t,e={}){let r=[];for(let i=0;i<t.length;i+=15)r.push(t.slice(i,i+15));return(await Promise.all(r.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(t,e={}){let r=await E(this.config,{query:`
1088
+ `},e);if(!o.body.data)throw new Error(ke(o.body.errors)||o.statusText||"Unknown error");let i=[],a=[];return t.forEach((u,l)=>{let d=o.body.data[`getRepo_${l}`];d?i.push(gr(d)):a.push({input:u})}),{data:i,errors:a}}async getRepos(t,e={}){let r=[];for(let i=0;i<t.length;i+=15)r.push(t.slice(i,i+15));return(await Promise.all(r.map(i=>this.getReposBase(i,e)))).reduce((i,a)=>({data:[...i.data,...a.data],errors:[...i.errors,...a.errors]}),{data:[],errors:[]})}async getReposForCurrentUser(t,e={}){let r=await E(this.config,{query:`
1089
1089
  query getReposForCurrentUser($after: String) {
1090
1090
  projects(membership: true first: 100 after: $after) {
1091
1091
  pageInfo {
@@ -1093,11 +1093,11 @@ query getReposForCurrentUser($after: String) {
1093
1093
  hasNextPage
1094
1094
  }
1095
1095
  nodes {
1096
- ${ir}
1096
+ ${pr}
1097
1097
  }
1098
1098
  }
1099
1099
  }
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(lr)}}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",$.toString());let n=await this.config.request({url:r.toString(),headers:R(e.token||this.config.token)});return{pageInfo:Ds(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",$.toString());let i=await this.config.request({url:o.toString(),headers:R(r.token||this.config.token)});return{pageInfo:Ds(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=Eo[t.association],o=As(t.states),i=L(t.pageSize,{fallback:ue,max:ue}),a=await E(this.config,{query:`
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:lr(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:lr(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=Lo[t.association],o=Ls(t.states),i=L(t.pageSize,{fallback:ue,max:ue}),a=await E(this.config,{query:`
1101
1101
  query getPullRequestsForUser($username: String! $cursor: String $labelNames: [String!]) {
1102
1102
  user(username: $username) {
1103
1103
  ${n}(${o} first: ${i} after:$cursor labels: $labelNames${r?` ${r}`:""}) {
@@ -1106,12 +1106,12 @@ query getPullRequestsForUser($username: String! $cursor: String $labelNames: [St
1106
1106
  hasNextPage
1107
1107
  }
1108
1108
  nodes {
1109
- ${ur(!0,!0,!0)}
1109
+ ${cr(!0,!0,!0)}
1110
1110
  }
1111
1111
  }
1112
1112
  }
1113
1113
  }
1114
- `,variables:{username:t.username,cursor:t.cursor,labelNames:t.labelNames}},e);if(!a.body.data)throw new Error(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=>pr(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 D=t.repos&&t.repos[c];i[c]==="null"?l.push(null):l.push(this.getPullRequestsForUser({username:t.username,association:"authored",cursor:i[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...D&&{repo:D}},e)),a[c]==="null"?d.push(null):d.push(this.getPullRequestsForUser({username:t.username,association:"assigned",cursor:a[c],includeFromArchivedRepos:t.includeFromArchivedRepos,labelNames:t.labelNames,...D&&{repo:D}},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,...D&&{repo:D}},e)),c++}while(c<(t.repos?.length||0));let g=[l,d,p].flat(),m=await Promise.all(g),h={},y=[],f=D=>{h[D.id]||(h[D.id]=!0,y.push(D))},P=!1,A=m.map((D,w)=>{let S="";return D&&D.data.forEach(f),D?.pageInfo.hasNextPage?(P=!0,S+=`${D.pageInfo.endCursor||"null"}`):S+="null",t.repos?.length&&(w+1)%t.repos.length!==0?S+="-":w+1<m.length&&(S+=";"),S}).join("");return{pageInfo:{hasNextPage:P,endCursor:A},data:y}}getVariablesForPullRequests(t){let{updatedBefore:e,isDraft:r,authorLogin:n,assigneeLogins:o,labelNames:i,reviewRequestedLogin:a}=t||{},u={},l=[],d=[],p=(c,g,m)=>{l.push(`$${c}: ${m}`),d.push(`${c}: $${c}`),u[c]=g};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=As(t.states),u=L(t.pageSize,{fallback:ue,max:ue}),{variables:l,variableTypes:d,mergeRequestArguments:p}=this.getVariablesForPullRequests(t),c={fullPath:i,...l},g=await E(this.config,{query:`
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=>mr(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 A=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,...A&&{repo:A}},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,...A&&{repo:A}},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,...A&&{repo:A}},e)),c++}while(c<(t.repos?.length||0));let m=[l,d,p].flat(),g=await Promise.all(m),h={},y=[],f=A=>{h[A.id]||(h[A.id]=!0,y.push(A))},P=!1,$=g.map((A,w)=>{let S="";return A&&A.data.forEach(f),A?.pageInfo.hasNextPage?(P=!0,S+=`${A.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:$},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=Ls(t.states),u=L(t.pageSize,{fallback:ue,max:ue}),{variables:l,variableTypes:d,mergeRequestArguments:p}=this.getVariablesForPullRequests(t),c={fullPath:i,...l},m=await E(this.config,{query:`
1115
1115
  query getPullRequestsForRepo(
1116
1116
  $fullPath: ID!
1117
1117
  $after: String
@@ -1136,7 +1136,7 @@ query getPullRequestsForRepo(
1136
1136
  hasNextPage
1137
1137
  }
1138
1138
  nodes {
1139
- ${ur(!1,!0,!0)}
1139
+ ${cr(!1,!0,!0)}
1140
1140
  sourceProject {
1141
1141
  ${Ne}
1142
1142
  }
@@ -1144,7 +1144,7 @@ query getPullRequestsForRepo(
1144
1144
  }
1145
1145
  }
1146
1146
  }
1147
- `,variables:{...c,after:n}},e),m=[],h=g.body.data?.project;if(!r&&h?.archived)return{pageInfo:null,data:[]};let y=rt(h||{id:"",fullPath:"",webUrl:""});return(h?.mergeRequests?.nodes||[]).forEach(P=>{let v=P.sourceProject?xe(P.sourceProject):null;m.push(pr(P,y,v,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.mergeRequests?.pageInfo,data:x(m,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!) {
1147
+ `,variables:{...c,after:n}},e),g=[],h=m.body.data?.project;if(!r&&h?.archived)return{pageInfo:null,data:[]};let y=rt(h||{id:"",fullPath:"",webUrl:""});return(h?.mergeRequests?.nodes||[]).forEach(P=>{let v=P.sourceProject?xe(P.sourceProject):null;g.push(mr(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
1148
  mergeRequestUpdate(input: { projectPath: $fullPath, iid: $pullRequestId, state: CLOSED }) {
1149
1149
  errors,
1150
1150
  mergeRequest {
@@ -1209,18 +1209,18 @@ query getPullRequestsForRepo(
1209
1209
  id
1210
1210
  }
1211
1211
  }
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=Go(t),n=await E(this.config,{query:`
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=xo(t),n=await E(this.config,{query:`
1213
1213
  query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1214
1214
  project(fullPath: $projectId) {
1215
1215
  id
1216
1216
  fullPath
1217
1217
  webUrl
1218
1218
  issue(iid: $issueNumber) {
1219
- ${ar}
1219
+ ${dr}
1220
1220
  }
1221
1221
  }
1222
1222
  }
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:dr(n.body.data.project.issue,rt(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=$s(t.states),a=L(t.pageSize,{fallback:ue,max:ue}),{variables:u,variableTypes:l,issueArguments:d}=this.getVariablesForIssues(t),p={fullPath:o,...u},c=`
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:hr(n.body.data.project.issue,rt(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=Us(t.states),a=L(t.pageSize,{fallback:ue,max:ue}),{variables:u,variableTypes:l,issueArguments:d}=this.getVariablesForIssues(t),p={fullPath:o,...u},c=`
1224
1224
  query GetIssuesFromProject(
1225
1225
  $fullPath: ID!
1226
1226
  $after: String
@@ -1240,7 +1240,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1240
1240
  ${d.length?d.join(" "):""}
1241
1241
  ) {
1242
1242
  nodes {
1243
- ${ar}
1243
+ ${dr}
1244
1244
  }
1245
1245
  pageInfo {
1246
1246
  endCursor
@@ -1248,7 +1248,7 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1248
1248
  }
1249
1249
  }
1250
1250
  }
1251
- }`,g=await E(this.config,{query:c,variables:{...p,after:r}},e),m=[],h=g.body.data?.project,y=rt(h||{id:"",fullPath:"",webUrl:""});return(h?.issues?.nodes||[]).forEach(P=>{m.push(dr(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl))}),{pageInfo:h?.issues?.pageInfo??{endCursor:null,hasNextPage:!1},data:m.sort((P,v)=>(P.updatedDate||P.createdDate).getTime()-(v.updatedDate||v.createdDate).getTime())}}async getIssuesForRepos(t,e={}){let{cursor:r}=t||{},n=$s(t.states),o=L(t.pageSize,{fallback:ue,max:ue}),i=t.repoIds.map(h=>h.toString().startsWith(Ee)?h:`${Ee}${h}`),{variables:a,variableTypes:u,issueArguments:l}=this.getVariablesForIssues(t),d={projectIds:i,...a},p=`
1251
+ }`,m=await E(this.config,{query:c,variables:{...p,after:r}},e),g=[],h=m.body.data?.project,y=rt(h||{id:"",fullPath:"",webUrl:""});return(h?.issues?.nodes||[]).forEach(P=>{g.push(hr(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=Us(t.states),o=L(t.pageSize,{fallback:ue,max:ue}),i=t.repoIds.map(h=>h.toString().startsWith(fe)?h:`${fe}${h}`),{variables:a,variableTypes:u,issueArguments:l}=this.getVariablesForIssues(t),d={projectIds:i,...a},p=`
1252
1252
  query GetIssuesFromProject(
1253
1253
  $projectIds: [ID!]
1254
1254
  $after: String
@@ -1274,12 +1274,12 @@ query GetSingleIssue($projectId: ID!, $issueNumber: String!) {
1274
1274
  ${l.length?l.join(" "):""}
1275
1275
  ) {
1276
1276
  nodes {
1277
- ${ar}
1277
+ ${dr}
1278
1278
  }
1279
1279
  }
1280
1280
  }
1281
1281
  }
1282
- }`,c=await E(this.config,{query:p,variables:{...d,after:r}},e),g=[];return(c.body.data?.projects?.nodes||[]).forEach(h=>{if(!t.includeFromArchivedRepos&&h.archived)return;let y=rt(h);(h.issues?.nodes||[]).forEach(P=>g.push(dr(P,y,this.getIsSelfHosted(e),this.config.baseUrl??e.baseUrl)))}),{pageInfo:c.body?.data?.projects?.pageInfo??{endCursor:null,hasNextPage:!1},data:g.sort((h,y)=>(h.updatedDate||h.createdDate).getTime()-(y.updatedDate||y.createdDate).getTime())}}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!) {
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=rt(h);(h.issues?.nodes||[]).forEach(P=>m.push(hr(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="scope"in t?t.scope??"assigned_to_me":"assigned_to_me",n="assigneeUsername"in t?t.assigneeUsername:void 0,o="page"in t&&t.page?.toString()||"1",i=L("pageSize"in t?t.pageSize:void 0,{fallback:C,max:C}),a=new URL(`${U(this.config,e)}/issues`);a.searchParams.set("scope",r),a.searchParams.set("state","opened"),n&&a.searchParams.set("assignee_username",n),a.searchParams.set("page",o),a.searchParams.set("per_page",i.toString());let u=await this.config.request({url:a.toString(),headers:R(e.token||this.config.token)});return{pageInfo:lr(u.headers),data:u.body.map(l=>Xo(l,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
1283
  updateIssue(input: { projectPath: $fullPath, iid: $issueId, stateEvent: $status }) {
1284
1284
  issue {
1285
1285
  id
@@ -1319,7 +1319,7 @@ query getLabelsForRepo(
1319
1319
  webUrl
1320
1320
  milestones(after: $after) {
1321
1321
  nodes {
1322
- ${fr}
1322
+ ${br}
1323
1323
  }
1324
1324
  pageInfo {
1325
1325
  endCursor
@@ -1328,7 +1328,7 @@ query getLabelsForRepo(
1328
1328
  }
1329
1329
  }
1330
1330
  }
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=>br(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:`
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=>wr(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
1332
  query getLabelsForRepo(
1333
1333
  $fullPath: ID!
1334
1334
  $after: String
@@ -1338,7 +1338,7 @@ query getLabelsForRepo(
1338
1338
  ) {
1339
1339
  labels(after: $after) {
1340
1340
  nodes {
1341
- ${Rr}
1341
+ ${yr}
1342
1342
  }
1343
1343
  pageInfo {
1344
1344
  endCursor
@@ -1347,28 +1347,28 @@ query getLabelsForRepo(
1347
1347
  }
1348
1348
  }
1349
1349
  }
1350
- `,variables:{fullPath:`${r}/${n}`,after:o}},e);return{pageInfo:i.body.data?.project?.labels?.pageInfo??{endCursor:null,hasNextPage:!1},data:i.body.data?.project?.labels?.nodes?.map(Ir)??[]}}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(_o),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:`
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(Pr)??[]}}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(jo),pageInfo:{endCursor:i?i.substring(1,i.indexOf(">")):null,hasNextPage:!!i}}}async getPullRequestForRepo(t,e={}){let r=_(t.repo),o=(await E(this.config,{query:`
1351
1351
  query getPullRequestForRepo($fullPath: ID!, $iid: String!) {
1352
1352
  project(fullPath: $fullPath) {
1353
1353
  ${Ne}
1354
1354
  archived
1355
1355
  mergeRequest(iid: $iid) {
1356
- ${ur(!1,!0,!0)}
1356
+ ${cr(!1,!0,!0)}
1357
1357
  sourceProject {
1358
1358
  ${Ne}
1359
1359
  }
1360
1360
  }
1361
1361
  }
1362
1362
  }
1363
- `,variables:{fullPath:r,iid:t.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=xe(o),u=i.sourceProject?xe(i.sourceProject):null;return{data:pr(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}=zo(t.cursor,$),i=new URL(`${U(this.config,e)}/projects/${encodeURIComponent(r)}/merge_requests/${t.pullRequestNumber}/notes`);i.searchParams.set("page",n.toString()),i.searchParams.set("per_page",o.toString()),i.searchParams.set("sort","asc"),i.searchParams.set("order_by","created_at");let a=await this.config.request({url:i.toString(),headers:R(e.token||this.config.token)}),u=this.getIsSelfHosted(e),l=this.config.baseUrl??e.baseUrl,d={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestNumber},p=a.body.filter(m=>!m.system&&!m.position).map(m=>cr(m,u,l,d)),c=!!a.headers["x-next-page"],g=c?Qo({page:n+1,perPage:o}):null;return{data:p,pageInfo:{endCursor:g,hasNextPage:c}}}async getReviewsForPullRequest(t,e={}){let r=_(t.repo),n=this.getIsSelfHosted(e),o=this.config.baseUrl??e.baseUrl,i=R(e.token||this.config.token),a=U(this.config,e),u=encodeURIComponent(r),[l,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(m=>m?.user).filter(m=>!!m).map(m=>{let h=Ls(m,n,o),y=`approval-${m.id}`;return{author:h,body:"",createdAt:l.body.updated_at?new Date(l.body.updated_at):null,id:y,graphQLId:y,reviewComments:[],url:l.body.web_url??""}}),c={namespace:t.repo.namespace,name:t.repo.name,mergeRequestIid:t.pullRequestId},g=d.filter(m=>m.notes.some(h=>!h.system&&!!h.position)).map(m=>{let h=m.notes.filter(w=>!w.system),f=h.filter(w=>!!w.position)[0];if(!f)return null;let P=h.filter(w=>w.id!==f.id).map(w=>cr(w,n,o,c)),A={...cr(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:Wo(f.position),isOutdated:!1,isResolved:!!m.resolved,threadId:m.id,replies:P};return{author:f.author?Ls(f.author,n,o):null,body:f.body??"",createdAt:f.created_at?new Date(f.created_at):null,id:m.id,graphQLId:m.id,reviewComments:[A],url:""}}).filter(m=>m!==null);return{data:[...p,...g]}}async getPullRequestDiff(t,e={}){let r=_(t.repo),n=encodeURIComponent(r),o=U(this.config,e);return(await this.fetchAllPagedGitLabREST(`${o}/projects/${n}/merge_requests/${t.pullRequestId}/diffs`,e,{perPage:No,maxPages:Bo})).map(Ho).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=$,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?mr(r.repository.owner.login,r.repository.name,r.number,P.body.id):void 0}if(!o?.trim())throw new Error("GitLab requires a file path when adding an inline comment to a pull request.");if(!Number.isInteger(i)||i<1)throw new Error("GitLab requires a positive line number when adding an inline comment to a pull request.");if(a!=="LEFT"&&a!=="RIGHT")throw new Error('GitLab requires side to be either "LEFT" or "RIGHT".');let m=(await this.config.request({url:`${p}/projects/${d}/merge_requests/${r.number}`,headers:R(e.token||this.config.token)})).body?.diff_refs;if(!m?.base_sha||!m?.start_sha||!m?.head_sha)throw new Error("Could not resolve merge request diff refs required to create an inline comment");let h={position_type:"text",base_sha:m.base_sha,start_sha:m.start_sha,head_sha:m.head_sha,new_path:o,old_path:o};a==="RIGHT"?h.new_line=i:h.old_line=i;let f=(await this.config.request({method:"POST",url:`${p}/projects/${d}/merge_requests/${r.number}/discussions`,headers:c,body:JSON.stringify({body:n,position:h})})).body?.notes?.[0]?.id;return f!=null?mr(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}=Vo(t);return`${U(this.config,e)}/projects/${encodeURIComponent(`${r}/${n}`)}/merge_requests/${o}/notes/${i}`}async deleteNote(t,e){await this.config.request({method:"DELETE",url:this.getNoteUrl(t,e),headers:R(e.token||this.config.token)})}async deleteComment(t,e={}){await this.deleteNote(t.commentId,e)}async deleteInlineComment(t,e={}){await this.deleteNote(t.commentId,e)}async editNote(t,e,r){if(!e?.trim())throw new Error("GitLab requires a body when editing a comment.");if(!(await this.config.request({method:"PUT",url:this.getNoteUrl(t,r),headers:{...R(r.token||this.config.token),"Content-Type":"application/json"},body:JSON.stringify({body:e})})).body?.id)throw new Error("Could not edit comment")}async editComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async editInlineComment(t,e={}){await this.editNote(t.commentId,t.body,e)}async resolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!0,e)}async unresolveReviewThread(t,e={}){await this.setReviewThreadResolved(t,!1,e)}async setReviewThreadResolved(t,e,r){if(!t.repo||t.pullRequestNumber==null)throw new Error("GitLab requires input.repo and input.pullRequestNumber to locate the discussion to (un)resolve.");if(!t.threadId)throw new Error("GitLab requires input.threadId to (un)resolve a discussion.");let n=_(t.repo),o=new URL(`${U(this.config,r)}/projects/${encodeURIComponent(n)}/merge_requests/${t.pullRequestNumber}/discussions/${encodeURIComponent(t.threadId)}`);o.searchParams.set("resolved",e?"true":"false"),await this.config.request({url:o.toString(),method:"PUT",headers:R(r.token||this.config.token)})}async approvePullRequest(t,e={}){let{pullRequest:r,comment:n}=t,o=`${r.repository.owner.login}/${r.repository.name}`,i=U(this.config,e),a=encodeURIComponent(o),u=R(e.token||this.config.token);await this.config.request({url:`${i}/projects/${a}/merge_requests/${r.number}/approve`,method:"POST",headers:u}),n&&n.trim()!==""&&await this.postMergeRequestNote(o,r.number,n,e)}async commentOnPullRequest(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when commenting on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;await this.postMergeRequestNote(o,r.number,n,e)}async requestPullRequestChanges(t,e={}){let{pullRequest:r,comment:n}=t;if(!n||n.trim()==="")throw new Error("GitLab requires a comment when requesting changes on a pull request.");let o=`${r.repository.owner.login}/${r.repository.name}`;if(!await this.tryRequestChangesMutation(o,r.number,e)){let u=`${U(this.config,e)}/projects/${encodeURIComponent(o)}/merge_requests/${r.number}`,l=R(e.token||this.config.token);(await this.config.request({url:`${u}/approvals`,method:"GET",headers:l})).body?.user_has_approved&&await this.config.request({url:`${u}/unapprove`,method:"POST",headers:l})}await this.postMergeRequestNote(o,r.number,n,e)}async tryRequestChangesMutation(t,e,r){let n=`mutation MergeRequestRequestChanges($fullPath: ID!, $pullRequestId: String!) {
1363
+ `,variables:{fullPath:r,iid:t.number.toString()}},e)).body.data?.project,i=o?.mergeRequest;if(!o||!i)return{data:null};let a=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
1364
  mergeRequestRequestChanges(input: { projectPath: $fullPath, iid: $pullRequestId }) {
1365
1365
  errors
1366
1366
  mergeRequest {
1367
1367
  id
1368
1368
  }
1369
1369
  }
1370
- }`,o=await E(this.config,{query:n,variables:{fullPath:t,pullRequestId:e.toString()}},r),i=o.body.errors;if(i?.length){if(i.some(To))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 Jo="https://api.atlassian.com/ex/jira",nt=100,Ts=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"},yr=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Os="/rest/api/2/search/jql",_s="/rest/api/2/search",Pr=(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:ot(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[ot(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:Yo(s.fields.status),statusTransitions:s.transitions?.map(Ko)??[],components:s.fields.components?.map(Xo)??[],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(ei),fixVersions:s.fields.fixVersions.map(ti)}},Ko=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}}},Xo=s=>({description:s.description??null,id:s.id,name:s.name}),Zo=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,ot=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:Zo(s,t,e)}),Yo=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}},ei=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}),ti=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),le=(s,t,e)=>e?`${t.baseUrl||Jo}/${e}`:`${t?.baseUrl||s.baseUrl}`,it=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${le(s,e,r)}/rest/api/2/field`,headers:R(e.token||s.token)})).body},at=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${le(s,r,o)}/rest/api/2/issue/${n}?fields=${yr.join(",")}&expand=transitions`,headers:R(r.token||s.token)});return{data:Pr(a.body,i,e,o)}},ut=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1371
- OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,d=!o,p=d?_s:Os,c=new URL(`${le(s,r,o)}${p}`);c.searchParams.set("jql",l),c.searchParams.set("maxResults",nt.toString()),c.searchParams.set("fields",yr.join(",")),c.searchParams.set("expand","transitions"),n&&(d?c.searchParams.set("startAt",n):c.searchParams.set("nextPageToken",n));let g=await s.request({url:c.toString(),headers:R(r.token||s.token)}),m=g.body.issues.map(f=>Pr(f,a,e,o)),h=!1,y="";return d?(h=m.length==nt,y=(parseInt(n??"0",10)+m.length).toString()):(h=!!g.body.nextPageToken,y=g.body.nextPageToken??null),{data:m,pageInfo:{hasNextPage:h,endCursor:y}}},ks=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,jql:i,fields:a}=t||{},u=L(t?.pageSize,{fallback:nt,max:nt}),l=[...yr],d=a?.Sprint;d&&l.push(d);let p=!o,c=p?_s:Os,g=new URL(`${le(s,r,o)}${c}`);g.searchParams.set("jql",i.join(" AND ")),g.searchParams.set("maxResults",u.toString()),g.searchParams.set("fields",l.join(",")),g.searchParams.set("expand","transitions"),n&&(p?g.searchParams.set("startAt",n):g.searchParams.set("nextPageToken",n));let m=await s.request({url:g.toString(),headers:R(r.token||s.token)}),h=m.body.issues.map(P=>Pr(P,a,e,o)),y=!1,f="";if(p){let P=parseInt(n??"0",10),v=typeof m.body.startAt=="number"?m.body.startAt:Number.isNaN(P)?0:P,A=m.body.total;y=typeof A=="number"?v+h.length<A:h.length===u,f=(v+h.length).toString()}else y=!!m.body.nextPageToken,f=m.body.nextPageToken??null;return{data:h,pageInfo:{hasNextPage:y,endCursor:f}}},lt=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}"`],g=Ts(t.states);return g&&c.push(g),o&&c.push(`creator in ("${o}")`),n&&n.length!==0&&c.push(`assignee in ("${n.join('", "')}")`),i&&c.push(`comment ~ "${i}"`),a&&a.forEach(m=>c.push(`labels = "${m}"`)),ks(s,{resourceId:d,jql:c,cursor:u,fields:p,pageSize:t.pageSize},e,r)},pt=async(s,t,e,r={})=>{let{assigneeLogins:n,authorLogin:o,mentionLogin:i,labelNames:a,cursor:u,projectKeys:l,resourceId:d,fields:p}=t||{},g=["("+l.map(h=>`project = "${h}"`).join(" OR ")+")"],m=Ts(t.states);return m&&g.push(m),o&&g.push(`creator in ("${o}")`),n&&n.length!==0&&g.push(`assignee in ("${n.join('", "')}")`),i&&g.push(`comment ~ "${i}"`),a&&a.forEach(h=>g.push(`labels = "${h}"`)),ks(s,{resourceId:d,jql:g,fields:p,cursor:u,pageSize:t.pageSize},e,r)},dt=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"}})},ct=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"}})},mt=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"}})},gt=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",wr=100,Ce=class extends M{constructor(){super(...arguments);this._resourceUrlCache={};this._issueFieldsCache={}}async getIssueFieldsForResource(e,r={}){if(!this._issueFieldsCache[e.resourceId]){let n=await it(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",wr.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:be("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=>Wr(u=>this.getJiraProjectsForResource({resourceId:a,cursor:u},r)),failureScope:a=>({providerId:"jira",resourceId:a})}),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",wr.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:be("complete"),data:l.body.filter(d=>d.accountType!=="app"&&d.active).map(d=>ot(d,a,!1))}}async getComponentsForJiraProject(e,r={}){return await gt(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 at(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 lt(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 pt(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 ut(this.config,{...e,fields:n},o,r)}async setIssueStatus(e,r={}){await mt(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 ct(this.config,e,r)}async setIssueLabels(e,r={}){await dt(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",wr.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 it(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 at(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 lt(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 pt(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 ut(this.config,{...e,fields:o},n,r)}async setIssueStatus(e,r={}){await mt(this.config,e,r)}async setIssueLabels(e,r={}){await dt(this.config,e,r)}async setIssueComponents(e,r={}){await ct(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 gt(this.config,e,r)}};var vr=100,ht=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},qr=s=>s?s instanceof Date?s:new Date(s):null,ri=`
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(No))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 ti="https://api.atlassian.com/ex/jira",it=100,xs=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"},qr=["assignee","comment","summary","created","creator","updated","votes","issuetype","status","labels","components","project","fixVersions","description"],Ns="/rest/api/2/search/jql",Bs="/rest/api/2/search",vr=(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:at(s.fields.creator,e,o),updatedDate:new Date(s.fields.updated),assignees:n?[at(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:oi(s.fields.status),statusTransitions:s.transitions?.map(ri)??[],components:s.fields.components?.map(si)??[],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(ii),fixVersions:s.fields.fixVersions.map(ai)}},ri=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}}},si=s=>({description:s.description??null,id:s.id,name:s.name}),ni=(s,t,e)=>e&&s.name?`${t}/secure/ViewProfile.jspa?name=${encodeURIComponent(s.name)}`:`${t}/jira/people/${s.accountId}`,at=(s,t,e)=>({id:(e?s.key:s.accountId)??"",name:s.displayName,email:s.emailAddress,avatarUrl:s.avatarUrls["48x48"],username:s.displayName,url:ni(s,t,e)}),oi=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}},ii=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}),ai=s=>({id:s.id,description:s.description,name:s.name,archived:s.archived,released:s.released,releaseDate:s.releaseDate?new Date(s.releaseDate):null}),le=(s,t,e)=>e?`${t.baseUrl||ti}/${e}`:`${t?.baseUrl||s.baseUrl}`,ut=async(s,t,e={})=>{let{resourceId:r}=t;return(await s.request({url:`${le(s,e,r)}/rest/api/2/field`,headers:R(e.token||s.token)})).body},lt=async(s,t,e,r={})=>{let{number:n,resourceId:o,fields:i}=t||{},a=await s.request({url:`${le(s,r,o)}/rest/api/2/issue/${n}?fields=${qr.join(",")}&expand=transitions`,headers:R(r.token||s.token)});return{data:vr(a.body,i,e,o)}},pt=async(s,t,e,r={})=>{let{cursor:n,resourceId:o,labelNames:i,fields:a}=t||{},u=["statusCategory != Done",`(creator = currentUser() OR assignee = currentUser()
1371
+ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUser())`];i&&i.forEach(f=>u.push(`labels = "${f}"`));let l=`${u.join(" AND ")} ORDER BY updated DESC`,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=`
1372
1372
  id
1373
1373
  name
1374
1374
  description
@@ -1376,11 +1376,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1376
1376
  startDate
1377
1377
  targetDate
1378
1378
  url
1379
- `,xs=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:qr(s.startDate),targetDate:qr(s.targetDate),url:s.url}),Ns=async(s,t,e)=>{let r=`
1379
+ `,Fs=s=>({id:s.id,name:s.name,description:s.description??null,state:s.state,startDate:Sr(s.startDate),targetDate:Sr(s.targetDate),url:s.url}),Qs=async(s,t,e)=>{let r=`
1380
1380
  query GetProjects($first: Int!, $after: String) {
1381
1381
  projects(first: $first, after: $after) {
1382
1382
  nodes {
1383
- ${ri}
1383
+ ${li}
1384
1384
  }
1385
1385
  pageInfo {
1386
1386
  hasNextPage
@@ -1388,7 +1388,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1388
1388
  }
1389
1389
  }
1390
1390
  }
1391
- `;return(await oe(s,t,r,{first:vr,after:e})).projects},si=`
1391
+ `;return(await oe(s,t,r,{first:Cr,after:e})).projects},pi=`
1392
1392
  id
1393
1393
  name
1394
1394
  number
@@ -1396,11 +1396,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1396
1396
  startsAt
1397
1397
  endsAt
1398
1398
  completedAt
1399
- `,Bs=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:qr(s.completedAt),url:""}),js=async(s,t,e)=>{let r=`
1399
+ `,zs=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:Sr(s.completedAt),url:""}),Ms=async(s,t,e)=>{let r=`
1400
1400
  query GetCycles($first: Int!, $after: String) {
1401
1401
  cycles(first: $first, after: $after) {
1402
1402
  nodes {
1403
- ${si}
1403
+ ${pi}
1404
1404
  }
1405
1405
  pageInfo {
1406
1406
  hasNextPage
@@ -1408,16 +1408,16 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1408
1408
  }
1409
1409
  }
1410
1410
  }
1411
- `;return(await oe(s,t,r,{first:vr,after:e})).cycles},ni=`
1411
+ `;return(await oe(s,t,r,{first:Cr,after:e})).cycles},di=`
1412
1412
  id
1413
1413
  name
1414
1414
  color
1415
1415
  description
1416
- `,Fs=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),Qs=async(s,t,e)=>{let r=`
1416
+ `,Ws=s=>({id:s.id,name:s.name,color:s.color,description:s.description??null}),Hs=async(s,t,e)=>{let r=`
1417
1417
  query GetLabels($first: Int!, $after: String) {
1418
1418
  projectLabels(first: $first, after: $after) {
1419
1419
  nodes {
1420
- ${ni}
1420
+ ${di}
1421
1421
  }
1422
1422
  pageInfo {
1423
1423
  hasNextPage
@@ -1425,36 +1425,36 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1425
1425
  }
1426
1426
  }
1427
1427
  }
1428
- `;return(await oe(s,t,r,{first:vr,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 zs(s,t){return s?`${je[s]}:${t||""}`:t??null}function Ms(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 Ws=100;function Rt(s){return s?s instanceof Date?s:new Date(s):null}var Js=`
1428
+ `;return(await oe(s,t,r,{first:Cr,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 Vs(s,t){return s?`${je[s]}:${t||""}`:t??null}function Js(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 Ks=100;function bt(s){return s?s instanceof Date?s:new Date(s):null}var Ys=`
1429
1429
  id
1430
1430
  name
1431
1431
  key
1432
1432
  icon
1433
- `;function oi(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var Hs=`
1433
+ `;function ci(s){return{id:s.id,name:s.name,key:s.key,iconUrl:s.icon}}var Xs=`
1434
1434
  id
1435
1435
  name
1436
1436
  avatarUrl
1437
- `;function Vs(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var ii=`
1437
+ `;function Zs(s){return s?{id:s.id,name:s.name,username:s.name,email:null,avatarUrl:s.avatarUrl??null,url:null}:null}var gi=`
1438
1438
  id
1439
1439
  name
1440
- `;function ai(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var ui=`
1440
+ `;function mi(s,t){if(s)return{id:s.id,name:s.name,key:t?.key||null,namespace:null,resourceId:t?.id||null}}var hi=`
1441
1441
  id
1442
1442
  sortOrder
1443
1443
  name
1444
1444
  description
1445
1445
  status
1446
1446
  targetDate
1447
- `;function li(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:Rt(s.targetDate)}:null}function pi(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var di=`
1447
+ `;function fi(s){return s?{id:s.id,number:s.sortOrder,title:s.name,description:s.description??null,isOpen:s.status!=="done",url:"",startDate:null,dueDate:bt(s.targetDate)}:null}function Ri(s){switch(s){case"completed":case"canceled":return"DONE";case"started":return"IN_PROGRESS";default:return"TO_DO"}}var Ii=`
1448
1448
  id
1449
1449
  name
1450
1450
  color
1451
1451
  type
1452
- `;function ci(s){return s?{id:s.id,name:s.name,color:s.color,category:pi(s.type)}:null}var Sr=`
1452
+ `;function bi(s){return s?{id:s.id,name:s.name,color:s.color,category:Ri(s.type)}:null}var Ar=`
1453
1453
  creator {
1454
- ${Hs}
1454
+ ${Xs}
1455
1455
  }
1456
1456
  assignee {
1457
- ${Hs}
1457
+ ${Xs}
1458
1458
  }
1459
1459
  archivedAt
1460
1460
  createdAt
@@ -1462,23 +1462,23 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1462
1462
  id
1463
1463
  identifier
1464
1464
  project {
1465
- ${ii}
1465
+ ${gi}
1466
1466
  }
1467
1467
  team {
1468
- ${Js}
1468
+ ${Ys}
1469
1469
  }
1470
1470
  state {
1471
- ${di}
1471
+ ${Ii}
1472
1472
  }
1473
1473
  title
1474
1474
  updatedAt
1475
1475
  url
1476
1476
  projectMilestone {
1477
- ${ui}
1477
+ ${hi}
1478
1478
  }
1479
- `;async function Er(s){return{author:Vs(await s.creator),assignees:[Vs(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:Rt(s.archivedAt),createdDate:Rt(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:ai(await s.project,await s.team),state:ci(await s.state),title:s.title,type:null,updatedDate:Rt(s.updatedAt),upvoteCount:null,url:s.url,milestone:li(await s.projectMilestone)}}var ft=`
1479
+ `;async function Dr(s){return{author:Zs(await s.creator),assignees:[Zs(await s.assignee)].filter(t=>t!=null),commentCount:null,closedDate:bt(s.archivedAt),createdDate:bt(s.createdAt),description:s.description??null,id:s.id,labels:[],number:s.identifier,repository:null,project:mi(await s.project,await s.team),state:bi(await s.state),title:s.title,type:null,updatedDate:bt(s.updatedAt),upvoteCount:null,url:s.url,milestone:fi(await s.projectMilestone)}}var It=`
1480
1480
  nodes {
1481
- ${Sr}
1481
+ ${Ar}
1482
1482
  }
1483
1483
  pageInfo {
1484
1484
  hasNextPage
@@ -1487,7 +1487,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1487
1487
  `,Ae=class extends M{async fetchIssue(t,e){let r=`
1488
1488
  query GetIssue($identifier: String!) {
1489
1489
  issue(id: $identifier) {
1490
- ${Sr}
1490
+ ${Ar}
1491
1491
  }
1492
1492
  }
1493
1493
  `;return(await oe(this.config,e,r,{identifier:t})).issue}async fetchOrganization(t){let e=`
@@ -1502,7 +1502,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1502
1502
  query GetTeams {
1503
1503
  teams {
1504
1504
  nodes {
1505
- ${Js}
1505
+ ${Ys}
1506
1506
  }
1507
1507
  }
1508
1508
  }
@@ -1515,11 +1515,11 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1515
1515
  displayName
1516
1516
  }
1517
1517
  }
1518
- `;return(await oe(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await Er(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(oi)}}async getProjects(t={},e={}){let r=await Ns(this.config,e,t.cursor??void 0);return{data:r.nodes.map(xs),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await js(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Bs),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await Qs(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Fs),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}=Ms(r),i=await this.fetchViewer(e),a,u,l=new ht,d=async(p,c)=>{if(u||n>p)return;let g=await c(Math.max(Ws-l.length,1),n===p?o:void 0);if(!g)return;let m=await Bt(g.nodes.map(Er));l.push(...m),g.pageInfo.hasNextPage&&(a=p,u=g.pageInfo.endCursor)};return await d(1,async(p,c)=>(await this.rawRequest(e,`
1518
+ `;return(await oe(this.config,t,e)).viewer}async getIssue(t,e={}){let r=await this.fetchIssue(t.number,e);return{data:await Dr(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(ci)}}async getProjects(t={},e={}){let r=await Qs(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Fs),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getCycles(t={},e={}){let r=await Ms(this.config,e,t.cursor??void 0);return{data:r.nodes.map(zs),pageInfo:{hasNextPage:r.pageInfo.hasNextPage,endCursor:r.pageInfo.endCursor??null}}}async getLabels(t={},e={}){let r=await Hs(this.config,e,t.cursor??void 0);return{data:r.nodes.map(Ws),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}=Js(r),i=await this.fetchViewer(e),a,u,l=new Rt,d=async(p,c)=>{if(u||n>p)return;let m=await c(Math.max(Ks-l.length,1),n===p?o:void 0);if(!m)return;let g=await Ft(m.nodes.map(Dr));l.push(...g),m.pageInfo.hasNextPage&&(a=p,u=m.pageInfo.endCursor)};return await d(1,async(p,c)=>(await this.rawRequest(e,`
1519
1519
  query GetAssignedIssues($first: Int!, $after: String) {
1520
1520
  viewer {
1521
1521
  issues: assignedIssues(first: $first, after: $after) {
1522
- ${ft}
1522
+ ${It}
1523
1523
  }
1524
1524
  }
1525
1525
  }
@@ -1527,7 +1527,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1527
1527
  query GetCreatedIssues($first: Int!, $after: String) {
1528
1528
  viewer {
1529
1529
  issues: createdIssues(first: $first, after: $after) {
1530
- ${ft}
1530
+ ${It}
1531
1531
  }
1532
1532
  }
1533
1533
  }
@@ -1552,10 +1552,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1552
1552
  }]
1553
1553
  }
1554
1554
  ){
1555
- ${ft}
1555
+ ${It}
1556
1556
  }
1557
1557
  }
1558
- `,{first:p,after:c})).data?.issues),await d(5,async(p,c)=>{let m=(await this.rawRequest(e,`
1558
+ `,{first:p,after:c})).data?.issues),await d(5,async(p,c)=>{let g=(await this.rawRequest(e,`
1559
1559
  query GetCommentedIssues($first: Int!, $after: String) {
1560
1560
  comments(
1561
1561
  first: $first
@@ -1578,7 +1578,7 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1578
1578
  ){
1579
1579
  nodes {
1580
1580
  issue {
1581
- ${Sr}
1581
+ ${Ar}
1582
1582
  }
1583
1583
  }
1584
1584
  pageInfo {
@@ -1587,10 +1587,10 @@ OR comment ~ currentUser() OR summary ~ currentUser() OR description ~ currentUs
1587
1587
  }
1588
1588
  }
1589
1589
  }
1590
- `,{first:p,after:c})).data?.comments;return m?{nodes:m.nodes.map(y=>y.issue),pageInfo:m.pageInfo}:void 0}),{data:l.items,pageInfo:{hasNextPage:!!u,endCursor:zs(a,u)}}}async getIssues(t,e={}){let{teams:r,projects:n,labels:o,cursor:i}=t,a=[];if(r&&r.length>0){let g=r.map(m=>`"${m}"`).join(", ");a.push(`team: { id: { in: [${g}] } }`)}if(n&&n.length>0){let g=n.map(m=>`"${m}"`).join(", ");a.push(`project: { id: { in: [${g}] } }`)}if(o&&o.length>0){let g=o.map(m=>`"${m}"`).join(", ");a.push(`labels: { name: { in: [${g}] } }`)}let u=a.length>0?`filter: { ${a.join(", ")} }`:"",l=`
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:Vs(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
1591
  query GetIssues($first: Int!, $after: String) {
1592
1592
  issues(first: $first, after: $after${u?", ":""}${u}) {
1593
- ${ft}
1593
+ ${It}
1594
1594
  }
1595
1595
  }
1596
- `,p=(await this.rawRequest(e,l,{first:Ws,after:i})).data?.issues;return p?{data:await Bt(p.nodes.map(Er)),pageInfo:{hasNextPage:p.pageInfo.hasNextPage,endCursor:p.pageInfo.endCursor??null}}:{data:[],pageInfo:{hasNextPage:!1,endCursor:null}}}};var Z="https://api.trello.com",Ks=1e3,Y=(s,t)=>({...R(t),Authorization:`OAuth oauth_consumer_key="${s}", oauth_token="${t}"`}),mi=s=>({id:s.id,username:s.username,url:s.url,name:s.fullName,email:s.email,avatarUrl:s.avatarUrl}),gi=(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:mi(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(g=>r.push(`label:"${g}"`));let d=`${i?`${i}`:""}${r.join(" ")} board:${o}`,p=await this.config.request({url:`${e.baseUrl||Z}/1/search?query=${d}&cards_limit=${Ks}&card_members=true`,headers:Y(n,e.token||this.config.token)}),c=p.body.cards.length>=Ks?"unknown":"complete";return{data:p.body.cards.map(g=>gi(g,l||{})),metadata:be(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 It={};H(It,{default:()=>hi});var hi={};var bt={};H(bt,{default:()=>fi});var fi={};var Lt={};H(Lt,{decode:()=>Cr,decodeV0:()=>yi,encode:()=>bi,validate:()=>Ii});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 yt=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 Pt=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 wt=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 qt=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 vt=class{constructor(){}validate(t){if(!t.entityId)throw new Error("entityId is required")}encode(t){if(this.validate(t),!t.entityId)throw new Error("Missing required fields for 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 Et=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 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 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 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 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 Dt=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 At=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 $t=(s,t)=>{if(t!=="issue"&&t!=="pr")throw new Error("unknown entityType");switch(s){case"azure":case"azureDevOpsServer":return t==="pr"?new Pt:new yt;case"bitbucket":case"bitbucketServer":return t==="pr"?new qt:new wt;case"github":case"githubEnterprise":return t==="pr"?new Et:new vt;case"gitlab":case"gitlabSelfHosted":return t==="pr"?new Ct:new St;case"jira":case"jiraServer":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new Dt;case"trello":if(t==="pr")throw new Error("EntityType PullRequest is not valid for Jira");return new At;default:throw new Error("unknown provider")}},Ri=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")},Ii=s=>{if(s.version==="0"){Ri(s);return}$t(s.provider,s.entityType).validate(s)},bi=s=>$t(s.provider,s.entityType).encode(s),Cr=s=>{let t=JSON.parse(s);if(!t||!t.length)throw new Error("invalid issue unique id");return $t(t[0],t[1]).decode(t)},yi=(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 $t(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 Ut={};H(Ut,{CHANGES_REQUESTED_ACTION_CATEGORY:()=>rn,CHANGES_REQUESTED_BUCKET_ID:()=>Tr,CONFLICTS_ACTION_CATEGORY:()=>en,CONFLICTS_BUCKET_ID:()=>Ur,DRAFT_ACTION_CATEGORY:()=>on,DRAFT_BUCKET_ID:()=>kr,FAILING_CI_ACTION_CATEGORY:()=>Ys,FAILING_CI_BUCKET_ID:()=>Lr,NEEDS_MY_REVIEW_ACTION_CATEGORY:()=>tn,NEEDS_MY_REVIEW_BUCKET_ID:()=>Gr,OTHER_ACTION_CATEGORY:()=>an,OTHER_BUCKET_ID:()=>xr,PINNED_BUCKET_ID:()=>Dr,READY_TO_MERGE_ACTION_CATEGORY:()=>Xs,READY_TO_MERGE_BUCKET_ID:()=>Ar,REVIEWER_COMMENTED_ACTION_CATEGORY:()=>sn,REVIEWER_COMMENTED_BUCKET_ID:()=>Or,SNOOZED_BUCKET_ID:()=>Nr,UNASSIGNED_REVIEWERS_ACTION_CATEGORY:()=>Zs,UNASSIGNED_REVIEWERS_BUCKET_ID:()=>$r,WAITING_FOR_REVIEW_ACTION_CATEGORY:()=>nn,WAITING_FOR_REVIEW_BUCKET_ID:()=>_r,getActionablePullRequests:()=>un,groupPullRequestsByAssignee:()=>qi,groupPullRequestsByAuthor:()=>vi,groupPullRequestsByGitKrakenTeam:()=>Di,groupPullRequestsByRepo:()=>wi,groupPullRequestsByReviewer:()=>Ei,groupPullRequestsByWorkspace:()=>Ci,groupPullRequestsIntoBuckets:()=>Pi});var z=(s,t,e,r)=>({id:s,faIconName:e,name:t,priority:r,pullRequests:[]}),Dr="pinned",Ar="readyToMerge",$r="unassignedReviewers",Lr="failingCI",Ur="conflicts",Gr="needsMyReview",Tr="changesRequested",Or="reviewerCommented",_r="waitingForReview",kr="draft",xr="other",Nr="snoozed",Xs="readyToMerge",Zs="unassignedReviewers",Ys="failingCI",en="conflicts",tn="needsMyReview",rn="changesRequested",sn="reviewerCommented",nn="waitingForReview",on="draft",an="other",un=(s,t,e)=>s.map(r=>{let o={...r,...{suggestedActionCategory:an,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=Xs),(!t||o.viewer.isAuthor)&&r.isDraft&&(o.suggestedActionCategory=on),(!t||o.viewer.isAuthor)&&r.reviewDecision==="REVIEW_REQUESTED"&&(o.suggestedActionCategory=nn,o.viewer.waitingOnReviews=!0),(!t||o.viewer.isAuthor)&&r.reviewDecision==="COMMENTED"&&(o.suggestedActionCategory=sn),(!t||o.viewer.isAuthor)&&o.failingCI&&(o.suggestedActionCategory=Ys),(!t||o.viewer.isAuthor)&&o.hasConflicts&&(o.suggestedActionCategory=en),(!t||o.viewer.isAuthor)&&(r.reviewDecision==="CHANGES_REQUESTED"||o.codeSuggestionsCount>0)&&(o.suggestedActionCategory=rn),(!t||o.viewer.isAuthor)&&!r.reviews?.length&&(o.suggestedActionCategory=Zs,o.viewer.shouldAssignReviewer=!0),t&&r.reviews?.some(u=>u.reviewer.id===t.id&&u.state==="REVIEW_REQUESTED")&&(o.suggestedActionCategory=tn,o.viewer.shouldReview=!0),o}),Pi=(s,t,e)=>{let r={pinned:z(Dr,"Pinned","thumbtack",e?.bucketPriorityOverride?.pinned??-1),readyToMerge:z(Ar,"Ready to Merge","code-merge",e?.bucketPriorityOverride?.readyToMerge??0),unassignedReviewers:z($r,"Unassigned Reviewers","user-plus",e?.bucketPriorityOverride?.unassignedReviewers??1),failingCI:z(Lr,"Failing CI","circle-x",e?.bucketPriorityOverride?.failingCI??2),conflicts:z(Ur,"Resolve Conflicts","triangle-exclamation",e?.bucketPriorityOverride?.conflicts??3),needsMyReview:z(Gr,"Needs My Review","eye",e?.bucketPriorityOverride?.needsMyReview??4),changesRequested:z(Tr,"Suggested Changes","file-plus",e?.bucketPriorityOverride?.changesRequested??5),reviewerCommented:z(Or,"Reviewer Commented","comment",e?.bucketPriorityOverride?.reviewerCommented??6),waitingForReview:z(_r,"Waiting for Review","circle-pause",e?.bucketPriorityOverride?.waitingForReview??7),draft:z(kr,"Draft","compass-drafting",e?.bucketPriorityOverride?.draft??8),other:z(xr,"Other","ellipsis",e?.bucketPriorityOverride?.other??9),snoozed:z(Nr,"Snoozed","snooze",e?.bucketPriorityOverride?.snoozed??10)},o=un(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[Nr].pullRequests.push(i);return}a.viewer.pinned&&r[Dr].pullRequests.push(i),(!t||a.viewer.isAuthor||a.viewer.isAssignee&&!a.viewer.isReviewer)&&!a.isDraft&&a.viewer.canMerge&&a.mergeableState==="MERGEABLE"&&(r[Ar].pullRequests.push(i),u=!1),a.viewer.shouldAssignReviewer&&(r[$r].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.failingCI&&(r[Lr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.hasConflicts&&(r[Ur].pullRequests.push(i),u=!1),a.viewer.shouldReview&&(r[Gr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&(a.reviewDecision==="CHANGES_REQUESTED"||a.codeSuggestionsCount>0)&&(r[Tr].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="COMMENTED"&&(r[Or].pullRequests.push(i),u=!1),(!t||a.viewer.isAuthor)&&a.reviewDecision==="REVIEW_REQUESTED"&&(r[_r].pullRequests.push(i),u=!1),a.isDraft&&(r[kr].pullRequests.push(i),u=!1),u&&r[xr].pullRequests.push(i)}),Object.values(r).forEach(i=>{i.pullRequests.sort((a,u)=>o[a.uuid].priority-o[u.uuid].priority)}),r},wi=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)},qi=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)},vi=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)},Ei=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)},Si=s=>s.azureProject?[`${s.azureProject}-${s.azureOrganizationId}`]:s.providerData?.repositories.nodes.map(t=>`${s.provider}-${t.repositoryId}`)??[],Ci=(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)=>(Si(i).forEach(u=>{o[u]?o[u].push(i):o[u]=[i]}),o),{});s.forEach(o=>{let{provider:i}=Cr(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)},Di=(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 Gt={};H(Gt,{getPullRequestRank:()=>Ai});var Ai=(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 Tt={};H(Tt,{default:()=>$i});var $i={};var Ot={};H(Ot,{default:()=>Li});var Li={};var _t={};H(_t,{default:()=>Ui});var Ui={};var ln=s=>{let t={request:s?.request};return{azureDevOps:new Pe({...t,...s?.azureDevOps}),bitbucket:new we({...t,...s?.bitbucket}),bitbucketServer:new qe({...t,...s?.bitbucketServer}),github:new ve({...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 pn=(i=>(i.Conflicts="conflicts",i.Failure="failure",i.NotSet="notSet",i.Queued="queued",i.RejectedByPolicy="rejectedByPolicy",i.Succeeded="succeeded",i))(pn||{});var dn=(e=>(e.Completed="COMPLETED",e.NotPlanned="NOT_PLANNED",e))(dn||{});var Gi=ln;var Ti={azureDevOps:It,bitbucket:bt,bitbucketServer:Je,github:Gt,gitlab:Tt,gitProvider:Ut,jira:Ot,trello:_t,entityIdentifier:Lt};
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};