@preventive/triage 1.0.0-alpha.63 → 1.0.0-alpha.64

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/out/view.js CHANGED
@@ -1,4 +1,4 @@
1
- import"./chunk-R3NZFXVR.js";import{a as e,b as t,c as n,f as r,g as i,h as a,j as o}from"./chunk-OGNTXZYM.js";import{$b as s,$c as c,Ab as l,Ac as u,Ae as d,Af as f,Ba as p,Bb as m,Bc as h,Be as g,Bf as _,C as v,Cc as ee,Ce as te,Cf as ne,D as re,Dc as ie,De as ae,Df as oe,Ec as se,Ef as ce,Fc as le,Fe as ue,G as y,Gd as de,Ge as fe,H as pe,Hd as me,He as he,I as ge,Ib as _e,Id as ve,Jd as ye,K as be,Kb as xe,Kd as Se,L as b,Mb as Ce,N as we,Ob as Te,P as Ee,Pb as De,Pd as Oe,Q as ke,Qb as Ae,Qc as je,Qd as Me,Qe as Ne,R as Pe,Rb as Fe,Rc as Ie,Re as Le,S as Re,Sb as ze,T as x,Tb as Be,Ua as Ve,Ub as He,V as Ue,Va as We,Vb as Ge,Wa as Ke,Wc as qe,Xa as Je,Xb as S,Xc as Ye,Ya as Xe,Yb as Ze,Yc as Qe,Zb as $e,Zc as et,_b as tt,_c as nt,ac as rt,ad as it,bc as at,bd as ot,c as st,cb as ct,cc as C,d as w,db as lt,dc as ut,dd as dt,e as ft,eb as pt,ec as mt,ed as ht,f as gt,fc as _t,fd as vt,gb as yt,gc as T,h as bt,hb as E,hc as xt,i as St,ia as Ct,ib as wt,ic as Tt,ja as Et,jb as Dt,jc as Ot,k as kt,ka as At,kc as jt,l as Mt,la as Nt,lb as Pt,lc as Ft,m as It,ma as Lt,mb as Rt,mc as zt,me as Bt,na as Vt,nc as Ht,ne as Ut,o as Wt,oa as Gt,oc as Kt,oe as qt,p as Jt,pc as Yt,pf as Xt,q as Zt,qc as Qt,qe as $t,qf as en,r as tn,ra as nn,rc as rn,re as an,rf as on,s as sn,sc as D,sd as cn,se as ln,sf as un,t as dn,tc as O,te as k,tf as fn,ue as pn,uf as mn,v as hn,vb as gn,ve as _n,vf as A,w as j,wb as vn,we as yn,wf as bn,x as M,xb as xn,xc as Sn,xe as Cn,xf as wn,y as Tn,yb as En,yc as Dn,ye as N,zb as On,zc as kn,ze as An}from"./chunk-BZP3CT2V.js";import"./chunk-JCIIBLKR.js";import"./chunk-E3LFSUDJ.js";import"./chunk-JMG5DXII.js";import{d as jn}from"./chunk-J2FWBXFV.js";import{D as Mn,L as Nn,N as Pn,T as Fn,Y as In,_ as P,b as Ln,ba as Rn,ea as zn,n as Bn,t as Vn,u as Hn,v as Un,x as Wn,y as Gn}from"./chunk-DCBXCBLL.js";import{g as Kn,h as qn}from"./chunk-65PLAG3I.js";import"./chunk-NRPC74AM.js";import"./chunk-7BKKYVWR.js";import{f as F}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import"./chunk-VFWMQ3LG.js";import{F as Jn,G as Yn,N as Xn,O as Zn,Q as Qn,Z as $n,a as I,aa as er,d as tr,ea as nr,f as L,fa as rr,g as R,h as ir,l as ar,la as or,na as sr,pa as cr,u as lr,x as ur}from"./chunk-F3UI65ZI.js";import{g as dr}from"./chunk-IZ6MYRYB.js";import"./chunk-WCPJDAYA.js";import"./chunk-IYPY47MC.js";import{a as fr,d as pr}from"./chunk-PWFUOLZK.js";import{a as mr,i as hr,j as gr,p as _r,r as vr,t as yr}from"./chunk-PTFQKLKO.js";import{B as br,I as xr,l as Sr}from"./chunk-QRKFPLA4.js";import{d as Cr,i as wr,k as Tr,l as Er,r as Dr,x as Or}from"./chunk-74AEKRES.js";import"./chunk-C4Z6ZBXV.js";import{a as z,b as kr,c as B,g as V,i as Ar,j as H}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var jr={attach:{title:`Synced triage on report attach`,intro:`have triage from your workspace that disagrees with your local view on`,trailingNote:`Other findings in this report whose chain value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep.`,importedSideLabel:`Apply from chain`,applyButton:`Apply`},chain:{title:`Triage conflict from peer update`,intro:`were changed by a peer (or by another tab) in a way that disagrees with your local triage on`,trailingNote:`Other findings whose remote value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep for each — a "keep current" pick re-publishes your local value to the chain on your next save.`,importedSideLabel:`Apply from chain`,applyButton:`Apply`}};function Mr(){m(async(e,t,n)=>{let r=Ee(e);try{return await gn(e,r,jr[n]??jr.attach)}catch{let t=e.length;return alert(`${n===`attach`?`A report attach`:`A workspace sync`} had ${t} triage disagreement${t===1?``:`s`} with your local view. Kept your local values because another dialog is open. ${n===`attach`?`Detach and re-attach the report to pick again.`:`Your local values will re-publish to the chain on the next change.`}`),null}})}var Nr=class extends Pt{static properties={retry:{type:Boolean},_value:{state:!0}};constructor(){super(),this.retry=!1,this._value=``}_finish(e){this._value=``,super._finish(e)}_onCancel=()=>this._finish(null);_onInput=e=>{this._value=e.target.value};_onSubmit=()=>{let e=this._value??``;e&&this._finish(e)};_onKeydown=e=>{e.key===`Enter`&&(e.preventDefault(),this._onSubmit())};render(){let e=(this._value??``).length>0,t=this.retry?`That password didn't match. Try again, or cancel to leave the workspace unsynced for now.`:`This sync server requires a password before it accepts a new workspace. Enter it to create the workspace on the server.`;return B`<dialog @close="${this._onClose}"><header><h3>Sync server password</h3></header><p class="nwd-intro">${t}</p><input type="password" class="nwd-input" placeholder="Password" autocomplete="off" data-1p-ignore="true" data-lpignore="true" data-bwignore="true" data-form-type="other" name="dv-sync-auth" maxlength="4096" .value="${this._value}" @input="${this._onInput}" @keydown="${this._onKeydown}"><footer class="nwd-actions"><span class="nwd-spacer"></span> <button type="button" @click="${this._onCancel}">Cancel</button> <button type="button" class="primary" ?disabled="${!e}" @click="${this._onSubmit}">${this.retry?`Retry`:`Authenticate`}</button></footer></dialog>`}};customElements.define(`sync-auth-dialog`,Nr);function Pr({retry:e=!1}={}){return Rt(`sync-auth-dialog`,{retry:!!e})}function Fr(){l(async({retry:e})=>{try{return await Pr({retry:e})}catch(e){return console.warn(`Sync auth dialog failed to open:`,e),null}})}var Ir=`https://triage.space/`,Lr=[{hostname:`deepaudit.dev`,pathPrefix:`/`,supportsSync:!0},{hostname:`chalker.github.io`,pathPrefix:`/deepview/`,supportsSync:!1}];function Rr(){for(let e of Lr)if(location.hostname===e.hostname&&location.pathname.startsWith(e.pathPrefix))return e;return null}var zr=[`deepview.triage`,`deepview.triage.pending`],Br=`deepview.repoUrls`;function Vr(){try{for(let e of zr)if(localStorage.getItem(e))return!0}catch{return!0}try{let e=localStorage.getItem(Br);if(e){let t=JSON.parse(e);if(t&&typeof t==`object`&&Object.keys(t).length>0)return!0}}catch{return!0}return!1}async function Hr(){if(Vr())return!0;let e=[];try{e=await Tn()}catch{return!0}if(e.length>0)return!0;try{if(b().length>0)return!0}catch{return!0}try{return await v()}catch{return!0}}var Ur=class extends H{static properties={supportsSync:{attribute:!1}};createRenderRoot(){return this}constructor(){super(),this.supportsSync=!1}firstUpdated(){let e=this.querySelector(`dialog`);e&&e.showModal();let t=this.querySelector(`button.om-stay`);t&&t.focus()}_finish(e){if(this._settled)return;this._settled=!0;let t=this.querySelector(`dialog`);t&&t.close(),this.dispatchEvent(new CustomEvent(`resolve`,{detail:e}))}_onClose=()=>this._finish(!1);_onStay=()=>this._finish(!1);_onMigrate=()=>this._finish(!0);render(){let e=()=>B`<a class="om-link" href="${Ir}" target="_blank" rel="noopener noreferrer">${Ir}</a>`;return B`<dialog class="origin-migration-dialog" @close="${this._onClose}"><header class="om-head"><h3>This deepview build has moved</h3><p><code>${location.host}${location.pathname}</code> has moved to ${e()}.</p></header><section class="om-body"><p>Workspaces and reports don't migrate automatically — they live in this origin's browser storage (OPFS where available, localStorage as a fallback) and have to be re-imported on ${e()}.</p>${this.supportsSync?B`<p>For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}. Workspaces that had sync configured will pick their triage state back up from the sync server once you re-import them with the same key.</p><p>For triage attached to loose reports (or as a top-up after re-importing workspaces), call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces.</p>`:B`<p>This build has no sync layer. For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}.</p><p>For triage attached to loose reports, call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces. Reports themselves need to be re-dropped from their original JSON on the new origin.</p>`}</section><footer class="om-actions"><button type="button" class="om-stay" @click="${this._onStay}">Keep editing on ${location.host}</button> <button type="button" class="primary om-go" @click="${this._onMigrate}">Switch to triage.space</button></footer></dialog>`}};customElements.define(`origin-migration-dialog`,Ur);function Wr(e){return new Promise(t=>{let n=document.createElement(`origin-migration-dialog`);n.supportsSync=e.supportsSync,n.addEventListener(`resolve`,e=>{n.remove(),t(!!e.detail)}),document.body.append(n)})}async function Gr(){let e=Rr();return e?await Hr()?await Wr(e)?(location.assign(Ir),!0):!1:(location.replace(Ir),!0):!1}var U=null,Kr=!1,qr=null;function Jr(e){if(!e)return`Could not unlock. Try again.`;switch(e.name??``){case`NotAllowedError`:case`AbortError`:return``;case`SecurityError`:return`The site identity does not match the one this passkey was registered for. If you opened DeepView through a different URL (different subdomain, different port), reload via the original URL.`;case`InvalidStateError`:return`The passkey state on this device is inconsistent. Try reloading the page or removing and re-creating the passkey.`;case`NotSupportedError`:return`This browser does not support the WebAuthn PRF extension this site needs. Try a recent Chrome, Safari, or Edge with a platform authenticator.`;case`NetworkError`:return`A network error prevented the passkey from completing. Check your connection and try again.`;case`UnknownError`:return`The authenticator returned an unknown error. Try again, or use a different passkey.`;default:{let t=e.message??String(e);return t.length>200?t.slice(0,197)+`…`:t}}}function Yr(){if(U)return U;U=document.createElement(`div`),U.id=`lock-overlay`,U.setAttribute(`role`,`dialog`),U.setAttribute(`aria-modal`,`true`),U.setAttribute(`aria-label`,`Unlock DeepView`),Ar(B`<div class="lock-overlay-card"><div class="lock-overlay-icon" aria-hidden="true"><svg viewBox="0 0 32 32" width="40" height="40" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="15" width="18" height="12" rx="1.5"/><path d="M11 15v-4a5 5 0 0 1 10 0v4"/></svg></div><h2 class="lock-overlay-title">DeepView is locked</h2><p class="lock-overlay-body">Your triage data and reports are encrypted with a passkey on this device. Unlock to continue.</p><p class="lock-overlay-error" hidden></p><button type="button" class="lock-overlay-button primary">Unlock with passkey</button><p class="lock-overlay-footer">Lost your passkey? <a href="#" class="lock-overlay-wipe">Wipe local data and start over</a></p></div>`,U);let e=U.querySelector(`button`),t=U.querySelector(`.lock-overlay-error`);return e.addEventListener(`click`,async()=>{if(!Kr&&Xr()){Kr=!0,t.hidden=!0,t.textContent=``,e.disabled=!0,e.textContent=`Waiting…`,qr=new AbortController;try{await St({signal:qr.signal})}catch(e){let n=Jr(e);t.textContent=n,t.hidden=!n}finally{Kr=!1,qr=null,e.disabled=!1,e.textContent=`Unlock with passkey`}}}),U.querySelector(`.lock-overlay-wipe`).addEventListener(`click`,async e=>{if(e.preventDefault(),!Kr&&Xr()&&confirm(`Wipe ALL local DeepView data and start over?
1
+ import"./chunk-R3NZFXVR.js";import{a as e,b as t,c as n,f as r,g as i,h as a,j as o}from"./chunk-PUXIN26P.js";import{$b as s,$c as c,Ab as l,Ac as u,Ae as d,Af as f,Ba as p,Bb as m,Bc as h,Be as g,Bf as _,C as v,Cc as ee,Ce as te,Cf as ne,D as re,Dc as ie,De as ae,Df as oe,Ec as se,Ef as ce,Fc as le,Fe as ue,G as y,Gd as de,Ge as fe,H as pe,Hd as me,He as he,I as ge,Ib as _e,Id as ve,Jd as ye,K as be,Kb as xe,Kd as Se,L as b,Mb as Ce,N as we,Ob as Te,P as Ee,Pb as De,Pd as Oe,Q as ke,Qb as Ae,Qc as je,Qd as Me,Qe as Ne,R as Pe,Rb as Fe,Rc as Ie,Re as Le,S as Re,Sb as ze,T as x,Tb as Be,Ua as Ve,Ub as He,V as Ue,Va as We,Vb as Ge,Wa as Ke,Wc as qe,Xa as Je,Xb as S,Xc as Ye,Ya as Xe,Yb as Ze,Yc as Qe,Zb as $e,Zc as et,_b as tt,_c as nt,ac as rt,ad as it,bc as at,bd as ot,c as st,cb as ct,cc as C,d as w,db as lt,dc as ut,dd as dt,e as ft,eb as pt,ec as mt,ed as ht,f as gt,fc as _t,fd as vt,gb as yt,gc as T,h as bt,hb as E,hc as xt,i as St,ia as Ct,ib as wt,ic as Tt,ja as Et,jb as Dt,jc as Ot,k as kt,ka as At,kc as jt,l as Mt,la as Nt,lb as Pt,lc as Ft,m as It,ma as Lt,mb as Rt,mc as zt,me as Bt,na as Vt,nc as Ht,ne as Ut,o as Wt,oa as Gt,oc as Kt,oe as qt,p as Jt,pc as Yt,pf as Xt,q as Zt,qc as Qt,qe as $t,qf as en,r as tn,ra as nn,rc as rn,re as an,rf as on,s as sn,sc as D,sd as cn,se as ln,sf as un,t as dn,tc as O,te as k,tf as fn,ue as pn,uf as mn,v as hn,vb as gn,ve as _n,vf as A,w as j,wb as vn,we as yn,wf as bn,x as M,xb as xn,xc as Sn,xe as Cn,xf as wn,y as Tn,yb as En,yc as Dn,ye as N,zb as On,zc as kn,ze as An}from"./chunk-ISF55P7E.js";import"./chunk-JCIIBLKR.js";import"./chunk-E3LFSUDJ.js";import"./chunk-JMG5DXII.js";import{d as jn}from"./chunk-J2FWBXFV.js";import{D as Mn,L as Nn,N as Pn,T as Fn,Y as In,_ as P,b as Ln,ba as Rn,ea as zn,n as Bn,t as Vn,u as Hn,v as Un,x as Wn,y as Gn}from"./chunk-DCBXCBLL.js";import{g as Kn,h as qn}from"./chunk-65PLAG3I.js";import"./chunk-NRPC74AM.js";import"./chunk-7BKKYVWR.js";import{f as F}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import"./chunk-VFWMQ3LG.js";import{F as Jn,G as Yn,N as Xn,O as Zn,Q as Qn,Z as $n,a as I,aa as er,d as tr,ea as nr,f as L,fa as rr,g as R,h as ir,l as ar,la as or,na as sr,pa as cr,u as lr,x as ur}from"./chunk-F3UI65ZI.js";import{g as dr}from"./chunk-IZ6MYRYB.js";import"./chunk-WCPJDAYA.js";import"./chunk-IYPY47MC.js";import{a as fr,d as pr}from"./chunk-PWFUOLZK.js";import{a as mr,i as hr,j as gr,p as _r,r as vr,t as yr}from"./chunk-PTFQKLKO.js";import{B as br,I as xr,l as Sr}from"./chunk-QRKFPLA4.js";import{d as Cr,i as wr,k as Tr,l as Er,r as Dr,x as Or}from"./chunk-74AEKRES.js";import"./chunk-C4Z6ZBXV.js";import{a as z,b as kr,c as B,g as V,i as Ar,j as H}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var jr={attach:{title:`Synced triage on report attach`,intro:`have triage from your workspace that disagrees with your local view on`,trailingNote:`Other findings in this report whose chain value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep.`,importedSideLabel:`Apply from chain`,applyButton:`Apply`},chain:{title:`Triage conflict from peer update`,intro:`were changed by a peer (or by another tab) in a way that disagrees with your local triage on`,trailingNote:`Other findings whose remote value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep for each — a "keep current" pick re-publishes your local value to the chain on your next save.`,importedSideLabel:`Apply from chain`,applyButton:`Apply`}};function Mr(){m(async(e,t,n)=>{let r=Ee(e);try{return await gn(e,r,jr[n]??jr.attach)}catch{let t=e.length;return alert(`${n===`attach`?`A report attach`:`A workspace sync`} had ${t} triage disagreement${t===1?``:`s`} with your local view. Kept your local values because another dialog is open. ${n===`attach`?`Detach and re-attach the report to pick again.`:`Your local values will re-publish to the chain on the next change.`}`),null}})}var Nr=class extends Pt{static properties={retry:{type:Boolean},_value:{state:!0}};constructor(){super(),this.retry=!1,this._value=``}_finish(e){this._value=``,super._finish(e)}_onCancel=()=>this._finish(null);_onInput=e=>{this._value=e.target.value};_onSubmit=()=>{let e=this._value??``;e&&this._finish(e)};_onKeydown=e=>{e.key===`Enter`&&(e.preventDefault(),this._onSubmit())};render(){let e=(this._value??``).length>0,t=this.retry?`That password didn't match. Try again, or cancel to leave the workspace unsynced for now.`:`This sync server requires a password before it accepts a new workspace. Enter it to create the workspace on the server.`;return B`<dialog @close="${this._onClose}"><header><h3>Sync server password</h3></header><p class="nwd-intro">${t}</p><input type="password" class="nwd-input" placeholder="Password" autocomplete="off" data-1p-ignore="true" data-lpignore="true" data-bwignore="true" data-form-type="other" name="dv-sync-auth" maxlength="4096" .value="${this._value}" @input="${this._onInput}" @keydown="${this._onKeydown}"><footer class="nwd-actions"><span class="nwd-spacer"></span> <button type="button" @click="${this._onCancel}">Cancel</button> <button type="button" class="primary" ?disabled="${!e}" @click="${this._onSubmit}">${this.retry?`Retry`:`Authenticate`}</button></footer></dialog>`}};customElements.define(`sync-auth-dialog`,Nr);function Pr({retry:e=!1}={}){return Rt(`sync-auth-dialog`,{retry:!!e})}function Fr(){l(async({retry:e})=>{try{return await Pr({retry:e})}catch(e){return console.warn(`Sync auth dialog failed to open:`,e),null}})}var Ir=`https://triage.space/`,Lr=[{hostname:`deepaudit.dev`,pathPrefix:`/`,supportsSync:!0},{hostname:`chalker.github.io`,pathPrefix:`/deepview/`,supportsSync:!1}];function Rr(){for(let e of Lr)if(location.hostname===e.hostname&&location.pathname.startsWith(e.pathPrefix))return e;return null}var zr=[`deepview.triage`,`deepview.triage.pending`],Br=`deepview.repoUrls`;function Vr(){try{for(let e of zr)if(localStorage.getItem(e))return!0}catch{return!0}try{let e=localStorage.getItem(Br);if(e){let t=JSON.parse(e);if(t&&typeof t==`object`&&Object.keys(t).length>0)return!0}}catch{return!0}return!1}async function Hr(){if(Vr())return!0;let e=[];try{e=await Tn()}catch{return!0}if(e.length>0)return!0;try{if(b().length>0)return!0}catch{return!0}try{return await v()}catch{return!0}}var Ur=class extends H{static properties={supportsSync:{attribute:!1}};createRenderRoot(){return this}constructor(){super(),this.supportsSync=!1}firstUpdated(){let e=this.querySelector(`dialog`);e&&e.showModal();let t=this.querySelector(`button.om-stay`);t&&t.focus()}_finish(e){if(this._settled)return;this._settled=!0;let t=this.querySelector(`dialog`);t&&t.close(),this.dispatchEvent(new CustomEvent(`resolve`,{detail:e}))}_onClose=()=>this._finish(!1);_onStay=()=>this._finish(!1);_onMigrate=()=>this._finish(!0);render(){let e=()=>B`<a class="om-link" href="${Ir}" target="_blank" rel="noopener noreferrer">${Ir}</a>`;return B`<dialog class="origin-migration-dialog" @close="${this._onClose}"><header class="om-head"><h3>This deepview build has moved</h3><p><code>${location.host}${location.pathname}</code> has moved to ${e()}.</p></header><section class="om-body"><p>Workspaces and reports don't migrate automatically — they live in this origin's browser storage (OPFS where available, localStorage as a fallback) and have to be re-imported on ${e()}.</p>${this.supportsSync?B`<p>For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}. Workspaces that had sync configured will pick their triage state back up from the sync server once you re-import them with the same key.</p><p>For triage attached to loose reports (or as a top-up after re-importing workspaces), call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces.</p>`:B`<p>This build has no sync layer. For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}.</p><p>For triage attached to loose reports, call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces. Reports themselves need to be re-dropped from their original JSON on the new origin.</p>`}</section><footer class="om-actions"><button type="button" class="om-stay" @click="${this._onStay}">Keep editing on ${location.host}</button> <button type="button" class="primary om-go" @click="${this._onMigrate}">Switch to triage.space</button></footer></dialog>`}};customElements.define(`origin-migration-dialog`,Ur);function Wr(e){return new Promise(t=>{let n=document.createElement(`origin-migration-dialog`);n.supportsSync=e.supportsSync,n.addEventListener(`resolve`,e=>{n.remove(),t(!!e.detail)}),document.body.append(n)})}async function Gr(){let e=Rr();return e?await Hr()?await Wr(e)?(location.assign(Ir),!0):!1:(location.replace(Ir),!0):!1}var U=null,Kr=!1,qr=null;function Jr(e){if(!e)return`Could not unlock. Try again.`;switch(e.name??``){case`NotAllowedError`:case`AbortError`:return``;case`SecurityError`:return`The site identity does not match the one this passkey was registered for. If you opened DeepView through a different URL (different subdomain, different port), reload via the original URL.`;case`InvalidStateError`:return`The passkey state on this device is inconsistent. Try reloading the page or removing and re-creating the passkey.`;case`NotSupportedError`:return`This browser does not support the WebAuthn PRF extension this site needs. Try a recent Chrome, Safari, or Edge with a platform authenticator.`;case`NetworkError`:return`A network error prevented the passkey from completing. Check your connection and try again.`;case`UnknownError`:return`The authenticator returned an unknown error. Try again, or use a different passkey.`;default:{let t=e.message??String(e);return t.length>200?t.slice(0,197)+`…`:t}}}function Yr(){if(U)return U;U=document.createElement(`div`),U.id=`lock-overlay`,U.setAttribute(`role`,`dialog`),U.setAttribute(`aria-modal`,`true`),U.setAttribute(`aria-label`,`Unlock DeepView`),Ar(B`<div class="lock-overlay-card"><div class="lock-overlay-icon" aria-hidden="true"><svg viewBox="0 0 32 32" width="40" height="40" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="15" width="18" height="12" rx="1.5"/><path d="M11 15v-4a5 5 0 0 1 10 0v4"/></svg></div><h2 class="lock-overlay-title">DeepView is locked</h2><p class="lock-overlay-body">Your triage data and reports are encrypted with a passkey on this device. Unlock to continue.</p><p class="lock-overlay-error" hidden></p><button type="button" class="lock-overlay-button primary">Unlock with passkey</button><p class="lock-overlay-footer">Lost your passkey? <a href="#" class="lock-overlay-wipe">Wipe local data and start over</a></p></div>`,U);let e=U.querySelector(`button`),t=U.querySelector(`.lock-overlay-error`);return e.addEventListener(`click`,async()=>{if(!Kr&&Xr()){Kr=!0,t.hidden=!0,t.textContent=``,e.disabled=!0,e.textContent=`Waiting…`,qr=new AbortController;try{await St({signal:qr.signal})}catch(e){let n=Jr(e);t.textContent=n,t.hidden=!n}finally{Kr=!1,qr=null,e.disabled=!1,e.textContent=`Unlock with passkey`}}}),U.querySelector(`.lock-overlay-wipe`).addEventListener(`click`,async e=>{if(e.preventDefault(),!Kr&&Xr()&&confirm(`Wipe ALL local DeepView data and start over?
2
2
 
3
3
  This deletes your encrypted triage, all reports, and the passkey registration on this device. The data CANNOT be recovered after this — there is no backup.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.63",
3
+ "version": "1.0.0-alpha.64",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -132,7 +132,8 @@
132
132
  // GET /api/npm/rename-diff?name=&version=&otherVersion= → every pair of their JavaScript files the viewer diffs so,
133
133
  // Brotli-encoded ndjson | 400/401/404/413/429/502/503
134
134
  // GET /api/npm/type-only?name=&version=&otherVersion=&runs= → the files that changed between two versions in types alone,
135
- // and with runs=1 those in types alone but for what runs, Brotli-encoded ndjson | 400/401/404/413/429/501/502/503
135
+ // or with otherVersion (empty) of the version against no files, each added, as Review reads one with no base; and
136
+ // with runs=1 those in types alone but for what runs, Brotli-encoded ndjson | 400/401/404/413/429/501/502/503
136
137
  // GET /api/npm/delta?name=&version=&otherVersion= → the lines a version adds and removes against another, or `(empty)`, and
137
138
  // those but for declaration files changed in types alone, where any are, and whether binary files changed
138
139
  // | 400/401/404/413/422/429/502/503/504
@@ -235,7 +236,7 @@ import { type AllHeads, type HistoryCommit, type HistoryPages, MAX_HISTORY_PAGE,
235
236
  repositoryAllHeads, repositoryAllHistory, repositoryHistory, repositoryRefTips } from './repository-history.ts'
236
237
  import { type KnownMerges, type SquashedPull, type Squashes, squashedPulls } from './repository-squashes.ts'
237
238
  import { AGENTS_READ_VERSION, type AuthoredCommit, type BranchTip, type BranchTips, COMMITS_CURSOR, type CommitPulls, repositoryAgents } from './repository-agents.ts'
238
- import { DEPENDENCIES_LABEL, ISSUES_CURSOR, ISSUES_READ_VERSION, repositoryIssues, repositoryItem, repositoryLabel } from './repository-issues.ts'
239
+ import { DEPENDENCIES_LABEL, ISSUES_CURSOR, ISSUES_READ_VERSION, OPEN_PULLS_READ, OPEN_PULLS_SIZES, repositoryIssues, repositoryItem, repositoryLabel, repositoryOpenPulls } from './repository-issues.ts'
239
240
  import { type GithubAsked, type ListedLockfile, type LockfileRead, type LockfileStore, MAX_LOCKED, PULL_DEPENDENCIES_READ, type PullCommits, type PullDependencies,
240
241
  type PullDependencyStore, lockfileFormat, pullDependenciesAt } from './pull-dependencies.ts'
241
242
  import { eachOf } from './queue.ts'
@@ -2443,7 +2444,7 @@ const patchFields = (field: (key: string) => unknown) => requestedPatch({ hash:
2443
2444
  // requests tabs show (repository-issues.ts): `kind`'s open or closed
2444
2445
  // (`state`), a page at a time, on from the cursor `after` names. They are
2445
2446
  // the whole repository's, read as readWholeRepository reads them, kept with
2446
- // open pull requests' commits, which they never tell (teamOpenPulls reads
2447
+ // open pull requests' commits, which they never tell (keptPullCommits reads
2447
2448
  // them).
2448
2449
  async function handleRepositoryIssues(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, query: URLSearchParams): Promise<void> {
2449
2450
  const repoId = askedRepoId(query)
@@ -2462,10 +2463,14 @@ async function handleRepositoryIssues(res: ServerResponse, deps: ManagedHttpDeps
2462
2463
  })
2463
2464
  }
2464
2465
  // What GET issues keeps a page of a repository's `kind` by, `state` ones on
2465
- // from the cursor `after` names; those carrying `label` alone, as a team's
2466
- // Dependencies reads them (teamOpenPulls), apart from the pages of all.
2467
- const issuesKey = (repoId: number, kind: string, state: string, after: string | null, label: string | null = null) =>
2468
- `${repoId}\0issues\0${ISSUES_READ_VERSION}\0${kind}\0${state}\0${after ?? ''}${label === null ? '' : `\0label\0${label}`}`
2466
+ // from the cursor `after` names.
2467
+ const issuesKey = (repoId: number, kind: string, state: string, after: string | null) => `${repoId}\0issues\0${ISSUES_READ_VERSION}\0${kind}\0${state}\0${after ?? ''}`
2468
+ // What a team's Dependencies keeps a page of a repository's open pull
2469
+ // requests by (teamOpenPulls), on from the cursor `after` names, those
2470
+ // carrying `label` alone where it names one: pages of their own, of less
2471
+ // each than GET issues'.
2472
+ const openPullsKey = (repoId: number, after: string | null, label: string | null) =>
2473
+ `${repoId}\0open-pulls\0${OPEN_PULLS_READ}\0${after ?? ''}${label === null ? '' : `\0label\0${label}`}`
2469
2474
 
2470
2475
  // GET /api/admin/repositories/agents: what the code viewer's Agents tab
2471
2476
  // reconstructs agents' sessions from (repository-agents.ts): a page
@@ -2665,8 +2670,10 @@ async function handleRepositoryLockfiles(res: ServerResponse, deps: ManagedHttpD
2665
2670
  // may read only some of, or `{ repoId, error, status }`; then its pull
2666
2671
  // requests' dependencies, of those changing a lockfile or that may,
2667
2672
  // TEAM_PULLS_TOGETHER at a time (`{ repoId, dependencies }`); its open pull
2668
- // requests those carrying its `dependencies` label alone where it has one
2669
- // (`pulls.label`, its name; teamOpenPulls); each line of
2673
+ // requests those carrying its `dependencies` label alone where it has one,
2674
+ // and, where GitHub failed a page of them or their time ran out, those read
2675
+ // till then, with why the rest weren't (`pulls.error`; teamOpenPulls); each
2676
+ // line of
2670
2677
  // dependencies with the lines their versions wanting reviews change, where
2671
2678
  // they are counted already (`deltas`, npm-delta.ts keptNpmDeltas), told
2672
2679
  // before the rows asking for them are drawn. Last, `{ done: true
@@ -2680,6 +2687,10 @@ async function handleRepositoryLockfiles(res: ServerResponse, deps: ManagedHttpD
2680
2687
  const TEAM_REPOSITORIES_AT_ONCE = 4
2681
2688
  const TEAM_DEPENDENCIES_MS = 240_000
2682
2689
  const TEAM_PULL_PAGES = 20
2690
+ // The open pull requests of a repository read, and the pages they are read
2691
+ // in, as many as read them a page's fewest at a time.
2692
+ const TEAM_PULLS = 1000
2693
+ const TEAM_PULL_READS = TEAM_PULLS / OPEN_PULLS_SIZES.at(-1)!
2683
2694
  const TEAM_PULLS_TOGETHER = 20
2684
2695
  const PARTIAL_ACCESS = new Set(['no-directory', 'no-repository'])
2685
2696
  type TeamDependencyLine = Record<string, unknown> & { repoId?: number }
@@ -2741,12 +2752,12 @@ async function handleTeamDependencies(res: ServerResponse, deps: ManagedHttpDeps
2741
2752
  async function teamRepositoryDependencies(deps: ManagedHttpDeps, access: WholeAccess, setting: RepoDependencyReview, deadline: number,
2742
2753
  send: (...lines: TeamDependencyLine[]) => Promise<boolean>, reauthorize: () => Promise<WholeAccess | Refusal>): Promise<boolean> {
2743
2754
  const repoId = access.repo.repoId
2744
- type Read = { branch: object | null; pulls?: { items: TeamPull[]; more: boolean; label?: string }; commits?: Map<number, PullCommits> }
2755
+ type Read = { branch: object | null; pulls?: { items: TeamPull[]; more: boolean; error?: string }; commits?: Map<number, PullCommits> }
2745
2756
  const read = await readWholeRepositoryOf<Read>(deps, access, async (fullName, token, user) => {
2746
2757
  const branch = await branchDependencyAnswer(deps, fullName, token, user, repoId, setting)
2747
2758
  if (!(branch.value as { review?: unknown }).review) return { value: { branch: null }, kept: branch.kept }
2748
- const pulls = await teamOpenPulls(deps, repoId, fullName, token)
2749
- return { value: { branch: branch.value, pulls: { items: pulls.items, more: pulls.more, ...pulls.label === null ? {} : { label: pulls.label } }, commits: pulls.commits },
2759
+ const pulls = await teamOpenPulls(deps, repoId, fullName, token, deadline)
2760
+ return { value: { branch: branch.value, pulls: { items: pulls.items, more: pulls.more, ...pulls.failed === null ? {} : { error: pulls.failed } }, commits: pulls.commits },
2750
2761
  kept: branch.kept && pulls.kept }
2751
2762
  }, reauthorize)
2752
2763
  if ('error' in read) return send({ repoId, ...PARTIAL_ACCESS.has(read.error) ? { branch: null } : { error: read.error, status: read.status } })
@@ -2771,34 +2782,47 @@ const withDeltas = async (deps: ManagedHttpDeps, answers: object[]) => {
2771
2782
  return deltas.length > 0 ? { deltas } : {}
2772
2783
  }
2773
2784
 
2774
- // A repository's open pull requests, as many pages of them as
2775
- // TEAM_PULL_PAGES, each read and kept as GET issues reads it; each's base's
2776
- // and head's commits as its page has them (`commits`, by its number), where
2777
- // it has them; whether it has more, and whether all were kept. Where the
2778
- // repository has a label named DEPENDENCIES_LABEL (kept as a page is), those
2779
- // carrying it alone, by its name as the repository has it (`label`), their
2780
- // pages kept apart from GET issues', which are of all of them: a repository
2781
- // of many open pull requests, few of them its dependencies', read in a page.
2782
- async function teamOpenPulls(deps: ManagedHttpDeps, repoId: number, fullName: string, token: string) {
2785
+ // A repository's open pull requests, the TEAM_PULLS updated latest, a page
2786
+ // at a time (repository-issues.ts repositoryOpenPulls), each kept; each's
2787
+ // base's and head's commits as its page has them (`commits`, by its number),
2788
+ // where it has them; whether it has more, and whether all were kept. Where
2789
+ // the repository has a label named DEPENDENCIES_LABEL (kept as a page is),
2790
+ // those carrying it alone, by its name as the repository has it: a
2791
+ // repository of many open pull requests, few of them its dependencies', read
2792
+ // in a page. A page GitHub was too slow to answer was asked again for fewer,
2793
+ // and the pages after it ask for no more than answered it. Where GitHub
2794
+ // fails a page all the same, but for its refusing the read, or `deadline`
2795
+ // passes, those read till then are told, with more to read and why they
2796
+ // weren't (`failed`), the failure logged: the next to ask reads on from the
2797
+ // pages kept.
2798
+ async function teamOpenPulls(deps: ManagedHttpDeps, repoId: number, fullName: string, token: string, deadline: number) {
2783
2799
  const labelled = await keptAnswer(deps, `${repoId}\0label\0${DEPENDENCIES_LABEL}`, () => repositoryLabel(fullName, token, DEPENDENCIES_LABEL))
2784
2800
  const label = typeof labelled.value.label === 'string' && labelled.value.label !== '' ? labelled.value.label : null
2785
2801
  const items: TeamPull[] = []
2786
2802
  const commits = new Map<number, PullCommits>()
2787
- let after: string | null = null, kept = labelled.kept
2788
- for (let page = 0; page < TEAM_PULL_PAGES; page++) {
2789
- const cursor = after
2790
- const answer = await keptAnswer(deps, issuesKey(repoId, 'pulls', 'open', cursor, label),
2791
- async () => ({ kind: 'pulls', state: 'open', ...await repositoryIssues(fullName, token, 'pulls', 'open', cursor, undefined, label) }))
2803
+ let after: string | null = null, kept = labelled.kept, size = OPEN_PULLS_SIZES[0]!
2804
+ for (let page = 0; page < TEAM_PULL_READS && items.length < TEAM_PULLS; page++) {
2805
+ if (Date.now() > deadline) return { items, commits, more: true, kept: false, failed: 'time-up' }
2806
+ const asked = size, cursor = after
2807
+ let answer
2808
+ try {
2809
+ answer = await keptAnswer(deps, openPullsKey(repoId, cursor, label), () => repositoryOpenPulls(fullName, token, cursor, label, asked))
2810
+ } catch (err) {
2811
+ if (!(err instanceof GithubApiError) || refusedRead(err)) throw err
2812
+ console.warn('managed: open pull requests read failed:', err)
2813
+ return { items, commits, more: true, kept: false, failed: err.message }
2814
+ }
2792
2815
  kept &&= answer.kept
2793
2816
  const value = answer.value as OpenPullsPage
2817
+ if (typeof value.size === 'number' && value.size > 0) size = Math.min(size, value.size)
2794
2818
  items.push(...(Array.isArray(value.items) ? value.items : []).filter(item => Number.isSafeInteger(item?.number) && item.number > 0))
2795
2819
  pageCommits(value, commits)
2796
- if (value.more !== true || typeof value.after !== 'string') return { items, commits, more: false, kept, label }
2820
+ if (value.more !== true || typeof value.after !== 'string') return { items, commits, more: false, kept, failed: null }
2797
2821
  after = value.after
2798
2822
  }
2799
- return { items, commits, more: true, kept, label }
2823
+ return { items, commits, more: true, kept, failed: null }
2800
2824
  }
2801
- type OpenPullsPage = { items?: unknown; more?: unknown; after?: unknown; commits?: unknown }
2825
+ type OpenPullsPage = { items?: unknown; more?: unknown; after?: unknown; commits?: unknown; size?: unknown }
2802
2826
  // Each open pull request's base's and head's commits a page of them names,
2803
2827
  // into `commits` by its number.
2804
2828
  function pageCommits(page: OpenPullsPage, commits: Map<number, PullCommits>) {
@@ -5024,7 +5048,8 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
5024
5048
  const otherSpec = params.get('otherVersion') ?? ''
5025
5049
  // The package a comparison's other side is a version of, another where Review compares a dependency replaced.
5026
5050
  const otherName = path === NPM_COMPARISON_PATH ? params.get('otherName') ?? name : name
5027
- if (!isNpmPackageName(name) || !isNpmPackageName(otherName) || (versioned && !isNpmPackageSpec(spec)) || ((path === NPM_RENAME_DIFF_PATH || path === NPM_TYPE_ONLY_PATH) && !isNpmPackageSpec(otherSpec))
5051
+ if (!isNpmPackageName(name) || !isNpmPackageName(otherName) || (versioned && !isNpmPackageSpec(spec)) || (path === NPM_RENAME_DIFF_PATH && !isNpmPackageSpec(otherSpec))
5052
+ || (path === NPM_TYPE_ONLY_PATH && otherSpec !== '(empty)' && !isNpmPackageSpec(otherSpec))
5028
5053
  || (path === NPM_PRETTY_PATH && otherSpec !== '' && !isNpmPackageSpec(otherSpec))
5029
5054
  || (path === NPM_RISK_PATH && otherSpec !== '' && otherSpec !== '(empty)' && !isNpmPackageSpec(otherSpec))
5030
5055
  || ((path === NPM_COMPARISON_PATH || path === NPM_DELTA_PATH) && otherSpec !== '(empty)' && !isNpmPackageSpec(otherSpec))) {
@@ -5106,7 +5131,7 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
5106
5131
  // The version it is compared with, where its route names one, read
5107
5132
  // beside it, the two read of those kept at once.
5108
5133
  const against: [string, string, boolean] | null = (path === NPM_RISK_PATH && otherSpec !== '' && otherSpec !== '(empty)') || (path === NPM_DELTA_PATH && otherSpec !== '(empty)')
5109
- || ((path === NPM_TYPE_ONLY_PATH || path === NPM_RENAME_DIFF_PATH || (path === NPM_PRETTY_PATH && !params.has('path'))) && otherSpec !== '')
5134
+ || ((path === NPM_TYPE_ONLY_PATH || path === NPM_RENAME_DIFF_PATH || (path === NPM_PRETTY_PATH && !params.has('path'))) && otherSpec !== '' && otherSpec !== '(empty)')
5110
5135
  ? [name, otherSpec, privileged]
5111
5136
  : path === NPM_COMPARISON_PATH && otherSpec !== '(empty)' ? [otherName, otherSpec, canReadPrivateNpm(reader, otherName)] : null
5112
5137
  const keptTogether = against ? readTogether(keptVersions, [{ name, version: spec }, { name: against[0], version: against[1] }]) : keptVersions
@@ -5203,11 +5228,14 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
5203
5228
  // Against another version, the pairs of its files that changed that the
5204
5229
  // viewer diffs with renamed names hidden (rename-diff.ts renamedPairs), a
5205
5230
  // line each as it is worked out, as Compare's pretty-printed files are;
5206
- // and those that changed in types alone (type-only.ts).
5231
+ // and those that changed in types alone (type-only.ts), the version's
5232
+ // against no files where the other is `(empty)`, as Review reads one with
5233
+ // no base.
5207
5234
  if (path === NPM_PRETTY_PATH || path === NPM_TYPE_ONLY_PATH || (path === NPM_RENAME_DIFF_PATH && !diffed)) {
5208
5235
  if (!deps.prettyCache) { sendJson(res, 503, { error: 'unavailable' }); return }
5209
- const other = otherSpec === '' ? null : await otherDoc()
5210
- const sides = other && await deps.prettyCache.npmSides(doc, other)
5236
+ const empty = path === NPM_TYPE_ONLY_PATH && otherSpec === '(empty)'
5237
+ const other = otherSpec === '' || empty ? null : await otherDoc()
5238
+ const sides = empty ? await deps.prettyCache.npmSides(null, doc) : other && await deps.prettyCache.npmSides(doc, other)
5211
5239
  const lines = path === NPM_RENAME_DIFF_PATH ? renamedPairs(sides!, !doc.private && !other!.private)
5212
5240
  : path === NPM_TYPE_ONLY_PATH ? typeOnlyFiles(sides!, runsAsked(params)) : sides ? compared(sides) : await deps.prettyCache.npmAll(doc)
5213
5241
  const isPrivate = doc.private || other?.private === true
@@ -276,6 +276,11 @@ async function bundleSide(details: Parameters<typeof bundlePackageDirs>[0], scop
276
276
  packageDirs: bundlePackageDirs(details) }
277
277
  }
278
278
 
279
+ // A base side of no files, which a version is compared against where it has
280
+ // none: none to print, nor to keep.
281
+ const noFiles = (): ComparedSide => ({ side: 'base', files: [], hashes: new Map(), packageDirs: null, kept: () => Promise.resolve(null),
282
+ made: () => Promise.reject(new PrettyError(404, 'no-file')) })
283
+
279
284
  // A version's files by path, from one load of them.
280
285
  async function npmFiles(doc: NpmVersionDocument): Promise<Array<[string, Uint8Array]>> {
281
286
  const load = loadNpmFiles(doc)
@@ -413,12 +418,14 @@ export function createPrettyCache(bundles: BundleCacheStorage, npm: CacheStorage
413
418
  },
414
419
  // A bundle's details, read in its turn, as Compare pairs them (comparison.ts).
415
420
  bundleDetails,
416
- npmSides(base: NpmVersionDocument, other: NpmVersionDocument): Promise<[ComparedSide, ComparedSide]> {
421
+ // Or a version's against no files, `base` null, each of its files added,
422
+ // as Review reads a version with no base.
423
+ npmSides(base: NpmVersionDocument | null, other: NpmVersionDocument): Promise<[ComparedSide, ComparedSide]> {
417
424
  const sideOf = async (doc: NpmVersionDocument, side: Side): Promise<ComparedSide> => ({ side, ...await sideFiles(await npmFiles(doc), (_, bytes) => npmFileHash(bytes)),
418
425
  packageDirs: null,
419
426
  kept: request => npmKept(doc, request),
420
427
  made: (request, text) => npmCopy(doc, request, () => Promise.resolve(text)) })
421
- return Promise.all([sideOf(base, 'base'), sideOf(other, 'other')])
428
+ return Promise.all([base ? sideOf(base, 'base') : noFiles(), sideOf(other, 'other')])
422
429
  },
423
430
  }
424
431
  }
@@ -8,9 +8,9 @@
8
8
  // packages are told (pull-dependencies.ts touchesLockfile), and its reviews
9
9
  // (pull-reviews.ts), each reviewer's; and an open one's base's and head's
10
10
  // commits, kept with its page but never told, by which what its lockfiles
11
- // add is read (http.ts teamRepositoryDependencies), of those carrying a
12
- // label alone where one is named, as a team's Dependencies names the
13
- // repository's DEPENDENCIES_LABEL where it has one. A nonpublic repository's
11
+ // add is read for its tile (http.ts keptPullCommits). A team's Dependencies
12
+ // reads the open ones in pages of its own, of less each (repositoryOpenPulls).
13
+ // A nonpublic repository's
14
14
  // are read with its GitHub App's installation, which reads pull requests only
15
15
  // with their own permission (doc/code-viewer.md).
16
16
  import { ACTOR, type GraphAccount, actorOf } from './github-accounts.ts'
@@ -50,13 +50,12 @@ const states = { issues: { open: '[OPEN]', closed: '[CLOSED]' }, pulls: { open:
50
50
 
51
51
  // A page of `kind`, those in `state`, after the page `after` ends, and how
52
52
  // many of each state there are; open pull requests with their commits and
53
- // their reviews. `labelled`, of those carrying a label of `$labels` alone,
54
- // the counts still of all.
55
- const pageQuery = (kind: IssuesKind, state: IssuesState, labelled = false) => `query($owner: String!, $name: String!, $after: String${labelled ? ', $labels: [String!]' : ''}) {
53
+ // their reviews.
54
+ const pageQuery = (kind: IssuesKind, state: IssuesState) => `query($owner: String!, $name: String!, $after: String) {
56
55
  repository(owner: $owner, name: $name) {
57
56
  open: ${connection[kind]}(states: ${states[kind].open}) { totalCount }
58
57
  closed: ${connection[kind]}(states: ${states[kind].closed}) { totalCount }
59
- page: ${connection[kind]}(states: ${states[kind][state]}, first: ${ISSUES_PAGE}, after: $after, ${labelled ? 'labels: $labels, ' : ''}orderBy: { field: UPDATED_AT, direction: DESC }) {
58
+ page: ${connection[kind]}(states: ${states[kind][state]}, first: ${ISSUES_PAGE}, after: $after, orderBy: { field: UPDATED_AT, direction: DESC }) {
60
59
  pageInfo { hasNextPage endCursor }
61
60
  nodes { ${fields[kind]}${kind === 'pulls' && state === 'open' ? ` baseRefOid headRefOid ${files} ${reviewFields(TILE_THREADS, false)}` : ''} }
62
61
  }
@@ -102,12 +101,16 @@ function item(kind: IssuesKind, node: Node | null) {
102
101
  closedAt: timeOf(node.closedAt), comments: count(node.comments?.totalCount), labels, moreLabels: Math.max(0, count(node.labels?.totalCount) - labels.length) }
103
102
  if (kind === 'issues') return { ...common, ...issueState(node.state, node.stateReason) }
104
103
  const checks = node.commits?.nodes?.[0]?.commit?.statusCheckRollup?.state
105
- const listed = node.files?.nodes
106
- const paths = Array.isArray(listed) ? listed.flatMap(file => typeof file?.path === 'string' ? [file.path] : []) : null
107
104
  return { ...common, ...pullState(node.state, node.isDraft), mergedAt: timeOf(node.mergedAt),
108
105
  review: REVIEWS[String(node.reviewDecision)] ?? null, checks: CHECKS[String(checks)] ?? null, additions: count(node.additions), deletions: count(node.deletions),
109
- head: nameOf(node.headRefName), base: nameOf(node.baseRefName),
110
- ...paths ? { touchesLockfile: touchesLockfile(paths, count(node.files?.totalCount)) } : {} }
106
+ head: nameOf(node.headRefName), base: nameOf(node.baseRefName), ...lockfileTouched(node) }
107
+ }
108
+ // Whether a pull request changes a lockfile read (touchesLockfile), by the
109
+ // files of it listed; untold where GitHub lists none of them.
110
+ function lockfileTouched(node: Node) {
111
+ const listed = node.files?.nodes
112
+ const paths = Array.isArray(listed) ? listed.flatMap(file => typeof file?.path === 'string' ? [file.path] : []) : null
113
+ return paths ? { touchesLockfile: touchesLockfile(paths, count(node.files?.totalCount)) } : {}
111
114
  }
112
115
 
113
116
  // A pull request's checks, which a GitHub App reads only with the Checks and
@@ -200,12 +203,10 @@ export async function repositoryLabel(fullName: string, token: string, label: st
200
203
  // page `after` ended (null for the first): its `items`, how many are open and
201
204
  // closed (`counts`), and, where more follow, the cursor reading them
202
205
  // (`after`); open pull requests' commits (`commits`, commitsOf) too, which
203
- // the code viewer is never told (http.ts handleRepositoryIssues). With
204
- // `label`, those carrying it alone.
205
- export async function repositoryIssues(fullName: string, token: string, kind: IssuesKind, state: IssuesState, after: string | null, fetchImpl: typeof fetch = globalThis.fetch,
206
- label: string | null = null) {
206
+ // the code viewer is never told (http.ts handleRepositoryIssues).
207
+ export async function repositoryIssues(fullName: string, token: string, kind: IssuesKind, state: IssuesState, after: string | null, fetchImpl: typeof fetch = globalThis.fetch) {
207
208
  const [owner, name] = fullName.split('/') as [string, string]
208
- const data = await githubGraphql(pageQuery(kind, state, label !== null), { owner, name, after, ...label === null ? {} : { labels: [label] } }, token, fetchImpl, partRefused) as Page
209
+ const data = await githubGraphql(pageQuery(kind, state), { owner, name, after }, token, fetchImpl, partRefused) as Page
209
210
  const repository = data?.repository
210
211
  if (!repository) throw new GithubApiError(404, 'github-not-found')
211
212
  const info = repository.page?.pageInfo
@@ -222,3 +223,62 @@ export async function repositoryIssues(fullName: string, token: string, kind: Is
222
223
  ...open ? { commits: tiles.flatMap(({ node, tile }) => commitsOf(tile.number, node)) } : {},
223
224
  }
224
225
  }
226
+
227
+ // A page of the open pull requests a team's Dependencies reads (http.ts
228
+ // teamOpenPulls), those carrying `$labels` alone where it names some: each by
229
+ // what its card there and its popup's heading tell (its number, title and
230
+ // author, when it was opened and last updated, whether it is a draft), the
231
+ // files by which whether it changes a lockfile is told, and its base's and
232
+ // head's commits, by which what its lockfiles add is read. Nothing else a
233
+ // tile shows (its labels, comments, size, branches, checks, reviews, threads
234
+ // and comments), which GitHub is slow enough to gather for fifty of a large
235
+ // repository's to fail the page.
236
+ const openPullsQuery = (labelled: boolean) => `query($owner: String!, $name: String!, $first: Int!, $after: String${labelled ? ', $labels: [String!]' : ''}) {
237
+ repository(owner: $owner, name: $name) {
238
+ page: pullRequests(states: [OPEN], first: $first, after: $after, ${labelled ? 'labels: $labels, ' : ''}orderBy: { field: UPDATED_AT, direction: DESC }) {
239
+ pageInfo { hasNextPage endCursor }
240
+ nodes { number title createdAt updatedAt author { ${ACTOR} } state isDraft baseRefOid headRefOid ${files} }
241
+ }
242
+ }
243
+ }`
244
+ // What a kept page of them was read as: kept ones read before differ.
245
+ export const OPEN_PULLS_READ = 1
246
+ // How many a page asks for: ISSUES_PAGE, then, where GitHub fails to answer
247
+ // that many in its time, fewer, and fewer again.
248
+ export const OPEN_PULLS_SIZES = [ISSUES_PAGE, 20, 5]
249
+ // GitHub not answering a query in its time: its gateway's 502 or 504, the
250
+ // timeout it tells of itself, or ours of it. Fewer asked for may be answered.
251
+ const SLOW = new Set(['github-status-502', 'github-status-504', 'github-timeout', 'github-unreachable'])
252
+ const tooSlow = (err: unknown) => err instanceof GithubApiError && SLOW.has(err.message)
253
+
254
+ // A page of the repository's open pull requests, the latest updated first,
255
+ // after the page `after` ended (null for the first), those carrying `label`
256
+ // alone where it names one: its `items`, their commits (`commits`, commitsOf)
257
+ // and, where more follow, the cursor reading them (`after`). As many as
258
+ // `size` asked for, then, GitHub too slow to answer, as many as each smaller
259
+ // of OPEN_PULLS_SIZES, the last one's failure the read's; how many were
260
+ // asked for (`size`) told, for the pages after it to ask no more.
261
+ export async function repositoryOpenPulls(fullName: string, token: string, after: string | null, label: string | null, size: number = ISSUES_PAGE,
262
+ fetchImpl: typeof fetch = globalThis.fetch) {
263
+ const fitting = OPEN_PULLS_SIZES.filter(one => one <= size)
264
+ const sizes = fitting.length > 0 ? fitting : OPEN_PULLS_SIZES.slice(-1)
265
+ for (const first of sizes.slice(0, -1)) {
266
+ try { return await openPullsPage(fullName, token, after, label, first, fetchImpl) } catch (err) {
267
+ if (!tooSlow(err)) throw err
268
+ }
269
+ }
270
+ return openPullsPage(fullName, token, after, label, sizes.at(-1)!, fetchImpl)
271
+ }
272
+ async function openPullsPage(fullName: string, token: string, after: string | null, label: string | null, first: number, fetchImpl: typeof fetch) {
273
+ const [owner, name] = fullName.split('/') as [string, string]
274
+ const data = await githubGraphql(openPullsQuery(label !== null), { owner, name, first, after, ...label === null ? {} : { labels: [label] } }, token, fetchImpl, checksRefused) as Page
275
+ const repository = data?.repository
276
+ if (!repository) throw new GithubApiError(404, 'github-not-found')
277
+ const info = repository.page?.pageInfo
278
+ const next = info?.hasNextPage === true && typeof info.endCursor === 'string' && ISSUES_CURSOR.test(info.endCursor) ? info.endCursor : null
279
+ const pulls = (repository.page?.nodes ?? []).flatMap(node => {
280
+ const named = itemOf(node)
281
+ return node && named ? [{ node, tile: { ...named, createdAt: timeOf(node.createdAt), updatedAt: timeOf(node.updatedAt), ...pullState(node.state, node.isDraft), ...lockfileTouched(node) } }] : []
282
+ })
283
+ return { items: pulls.map(({ tile }) => tile), commits: pulls.flatMap(({ node, tile }) => commitsOf(tile.number, node)), more: next !== null, after: next, size: first }
284
+ }