@preventive/triage 1.0.0-alpha.75 → 1.0.0-alpha.76

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-NMC7P5AA.js";import{$a as s,$b as c,$c as l,$d as u,$e as d,A as f,Ab as p,Ac as m,Ae as h,Af as g,Ag as ee,B as te,Bb as ne,Bc as re,Bg as _,Cb as ie,Cc as ae,Cg as oe,Db as se,Dc as ce,Dg as le,E as ue,Eb as de,F as fe,Fb as pe,G as me,Gb as he,Gg as ge,Hg as _e,I as ve,Ib as ye,Ig as be,J as xe,Jb as Se,Jg as Ce,Kb as we,Kg as Te,L as Ee,La as De,Lb as Oe,Lf as v,Ma as ke,Mb as Ae,N as je,Na as Me,Nb as Ne,O as Pe,Oa as Fe,Ob as Ie,Oc as Le,P as Re,Pa as ze,Pb as Be,Pc as Ve,Q as He,R as y,Rb as Ue,Sb as We,T as Ge,Tb as Ke,Ub as qe,Uc as Je,Vb as Ye,Vc as Xe,Wb as Ze,Wc as Qe,We as $e,Xa as et,Xb as tt,Xc as nt,Xe as rt,Yb as b,Yc as it,Ye as at,Zb as ot,Zc as st,Zd as ct,_a as lt,_b as ut,_c as dt,_e as ft,a as pt,ab as mt,ac as ht,ad as gt,ae as _t,af as vt,b as x,bb as yt,bc as bt,be as xt,bf as S,c as St,cb as Ct,cc as wt,ce as Tt,cf as Et,d as Dt,db as Ot,dc as kt,df as At,eb as jt,ec as Mt,ed as Nt,ef as Pt,f as Ft,fc as It,fd as Lt,ff as Rt,g as zt,ga as Bt,gc as Vt,gd as Ht,gf as Ut,ha as Wt,hc as Gt,he as Kt,hf as qt,i as Jt,ia as Yt,ic as Xt,if as Zt,j as Qt,ja as $t,jb as en,jc as tn,jf as nn,k as rn,ka as an,kc as on,ke as sn,kf as cn,lb as ln,lc as un,lf as dn,m as fn,mc as C,mf as pn,n as mn,na as hn,nb as gn,o as _n,ob as vn,of as yn,p as bn,pb as xn,pf as Sn,q as Cn,qb as wn,qf as Tn,r as En,rb as Dn,rc as On,sb as kn,sc as An,t as jn,tb as Mn,td as Nn,tg as Pn,u as w,ud as Fn,ug as In,v as T,vc as Ln,vg as Rn,w as zn,wa as Bn,wc as E,wg as Vn,xc as Hn,xg as Un,yc as Wn,yg as Gn,zc as Kn,zf as qn,zg as Jn}from"./chunk-VOJBPNPL.js";import"./chunk-A4BBBHQU.js";import"./chunk-JCIIBLKR.js";import"./chunk-VYYUMYVW.js";import"./chunk-7HP2VYIC.js";import"./chunk-PQPKHAI5.js";import{d as Yn}from"./chunk-T6EXDRB7.js";import{$ as Xn,A as Zn,B as Qn,G as $n,O as er,Q as tr,W as nr,d as rr,ga as D,ja as ir,la as ar,q as or,w as sr,x as cr,y as lr}from"./chunk-O6FA2R5G.js";import{f as ur,g as dr}from"./chunk-62QT2RXR.js";import"./chunk-S5HSDGTP.js";import"./chunk-NRPC74AM.js";import"./chunk-7BKKYVWR.js";import{f as O}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import{$ as fr,G as pr,H as mr,P as hr,Q as gr,S as _r,a as k,ca as vr,e as yr,g as A,ga as br,h as j,ha as xr,i as Sr,n as Cr,na as wr,pa as Tr,ra as Er,w as Dr,z as Or}from"./chunk-SZHJZVBL.js";import{g as kr}from"./chunk-IVDE66N5.js";import"./chunk-74JZTGTO.js";import"./chunk-IYPY47MC.js";import{d as Ar,i as jr,k as Mr,l as Nr,r as Pr,x as Fr}from"./chunk-ITUKKCCK.js";import{a as Ir,d as Lr}from"./chunk-PWFUOLZK.js";import"./chunk-C4Z6ZBXV.js";import{a as Rr,e as zr,f as Br,n as Vr,o as Hr,u as Ur,w as Wr,y as Gr}from"./chunk-WGQ7D5DB.js";import{B as Kr,I as qr,h as Jr,l as Yr}from"./chunk-QRKFPLA4.js";import{a as M,b as Xr,c as N,g as P,i as Zr,j as F}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var Qr={importedSideLabel:`Apply from chain`,applyButton:`Apply`},$r={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.`,...Qr},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.`,...Qr}};function ei(){Mn(async(e,t,n)=>{let r=je(e);try{return await gn(e,r,$r[n]??$r.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 ti=class extends Ot{static properties={_value:{state:!0}};static secrets={_value:``};constructor(){super(),this._value=``}_onInput=e=>{this._value=e.target.value};_onSubmit=()=>{this._value&&this._finish(this._value)};_onKeydown=en(this._onSubmit);render(){return N`<dialog @close="${this._onClose}"><header><h3>Sync server password</h3></header><p class="nwd-intro">${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.`}</p>${ln({name:`dv-sync-auth`,maxlength:4096,placeholder:`Password`,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="${!this._value}" @click="${this._onSubmit}">${this.retry?`Retry`:`Authenticate`}</button></footer></dialog>`}};customElements.define(`sync-auth-dialog`,ti);function ni({retry:e=!1}={}){return jt(`sync-auth-dialog`,{retry:!!e})}function ri(){kn(async({retry:e})=>{try{return await ni({retry:e})}catch(e){return console.warn(`Sync auth dialog failed to open:`,e),null}})}var ii=`https://triage.space/`,ai=[{hostname:`deepaudit.dev`,pathPrefix:`/`,supportsSync:!0},{hostname:`chalker.github.io`,pathPrefix:`/deepview/`,supportsSync:!1}];function oi(){return ai.find(e=>location.hostname===e.hostname&&location.pathname.startsWith(e.pathPrefix))??null}var si=[`deepview.triage`,`deepview.triage.pending`],ci=`deepview.repoUrls`;function li(){try{if(si.some(e=>localStorage.getItem(e)))return!0;let e=localStorage.getItem(ci);if(!e)return!1;let t=JSON.parse(e);return!!(t&&typeof t==`object`&&Object.keys(t).length>0)}catch{return!0}}async function ui(){if(li())return!0;let e=[];try{e=await zn()}catch{return!0}if(e.length>0)return!0;try{if(xe().length>0)return!0}catch{return!0}try{return await f()}catch{return!0}}var di=class extends F{static properties={supportsSync:{attribute:!1}};createRenderRoot(){return this}constructor(){super(),this.supportsSync=!1}firstUpdated(){this.querySelector(`dialog`)?.showModal(),this.querySelector(`button.om-stay`)?.focus()}_finish(e){this._settled||(this._settled=!0,this.querySelector(`dialog`)?.close(),this.dispatchEvent(new CustomEvent(`resolve`,{detail:e})))}_onStay=()=>this._finish(!1);_onMigrate=()=>this._finish(!0);render(){let e=()=>N`<a class="om-link" href="${ii}" target="_blank" rel="noopener noreferrer">${ii}</a>`;return N`<dialog class="origin-migration-dialog" @close="${this._onStay}"><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?N`<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>`:N`<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`,di);function fi(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 pi(){let e=oi();return e?await ui()?await fi(e)?(location.assign(ii),!0):!1:(location.replace(ii),!0):!1}var I=null,mi=!1,hi=null,gi={NotAllowedError:``,AbortError:``,SecurityError:`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.`,InvalidStateError:`The passkey state on this device is inconsistent. Try reloading the page or removing and re-creating the passkey.`,NotSupportedError:`This browser does not support the WebAuthn PRF extension this site needs. Try a recent Chrome, Safari, or Edge with a platform authenticator.`,NetworkError:`A network error prevented the passkey from completing. Check your connection and try again.`,UnknownError:`The authenticator returned an unknown error. Try again, or use a different passkey.`};function _i(e){if(!e)return`Could not unlock. Try again.`;let t=e.name??``;if(Object.hasOwn(gi,t))return gi[t];let n=e.message??String(e);return n.length>200?n.slice(0,197)+`…`:n}function vi(){if(I)return I;I=document.createElement(`div`),I.id=`lock-overlay`,I.setAttribute(`role`,`dialog`),I.setAttribute(`aria-modal`,`true`),I.setAttribute(`aria-label`,`Unlock DeepView`),Zr(N`<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>`,I);let e=I.querySelector(`button`),t=I.querySelector(`.lock-overlay-error`);return e.addEventListener(`click`,async()=>{if(!mi&&yi()){mi=!0,t.hidden=!0,t.textContent=``,e.disabled=!0,e.textContent=`Waiting…`,hi=new AbortController;try{await zt({signal:hi.signal})}catch(e){let n=_i(e);t.textContent=n,t.hidden=!n}finally{mi=!1,hi=null,e.disabled=!1,e.textContent=`Unlock with passkey`}}}),I.querySelector(`.lock-overlay-wipe`).addEventListener(`click`,async e=>{if(e.preventDefault(),!mi&&yi()&&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-MFAB7P3T.js";import{$a as s,$b as c,$c as l,$d as u,$e as d,A as f,Ab as p,Ac as m,Ae as h,Af as g,Ag as ee,B as te,Bb as ne,Bc as re,Bg as _,Cb as ie,Cc as ae,Cg as oe,Db as se,Dc as ce,Dg as le,E as ue,Eb as de,F as fe,Fb as pe,G as me,Gb as he,Gg as ge,Hg as _e,I as ve,Ib as ye,Ig as be,J as xe,Jb as Se,Jg as Ce,Kb as we,Kg as Te,L as Ee,La as De,Lb as Oe,Lf as v,Ma as ke,Mb as Ae,N as je,Na as Me,Nb as Ne,O as Pe,Oa as Fe,Ob as Ie,Oc as Le,P as Re,Pa as ze,Pb as Be,Pc as Ve,Q as He,R as y,Rb as Ue,Sb as We,T as Ge,Tb as Ke,Ub as qe,Uc as Je,Vb as Ye,Vc as Xe,Wb as Ze,Wc as Qe,We as $e,Xa as et,Xb as tt,Xc as nt,Xe as rt,Yb as b,Yc as it,Ye as at,Zb as ot,Zc as st,Zd as ct,_a as lt,_b as ut,_c as dt,_e as ft,a as pt,ab as mt,ac as ht,ad as gt,ae as _t,af as vt,b as x,bb as yt,bc as bt,be as xt,bf as S,c as St,cb as Ct,cc as wt,ce as Tt,cf as Et,d as Dt,db as Ot,dc as kt,df as At,eb as jt,ec as Mt,ed as Nt,ef as Pt,f as Ft,fc as It,fd as Lt,ff as Rt,g as zt,ga as Bt,gc as Vt,gd as Ht,gf as Ut,ha as Wt,hc as Gt,he as Kt,hf as qt,i as Jt,ia as Yt,ic as Xt,if as Zt,j as Qt,ja as $t,jb as en,jc as tn,jf as nn,k as rn,ka as an,kc as on,ke as sn,kf as cn,lb as ln,lc as un,lf as dn,m as fn,mc as C,mf as pn,n as mn,na as hn,nb as gn,o as _n,ob as vn,of as yn,p as bn,pb as xn,pf as Sn,q as Cn,qb as wn,qf as Tn,r as En,rb as Dn,rc as On,sb as kn,sc as An,t as jn,tb as Mn,td as Nn,tg as Pn,u as w,ud as Fn,ug as In,v as T,vc as Ln,vg as Rn,w as zn,wa as Bn,wc as E,wg as Vn,xc as Hn,xg as Un,yc as Wn,yg as Gn,zc as Kn,zf as qn,zg as Jn}from"./chunk-UZC7POI4.js";import"./chunk-A4BBBHQU.js";import"./chunk-JCIIBLKR.js";import"./chunk-VYYUMYVW.js";import"./chunk-7HP2VYIC.js";import"./chunk-PQPKHAI5.js";import{d as Yn}from"./chunk-T6EXDRB7.js";import{$ as Xn,A as Zn,B as Qn,G as $n,O as er,Q as tr,W as nr,d as rr,ga as D,ja as ir,la as ar,q as or,w as sr,x as cr,y as lr}from"./chunk-O6FA2R5G.js";import{f as ur,g as dr}from"./chunk-62QT2RXR.js";import"./chunk-S5HSDGTP.js";import"./chunk-NRPC74AM.js";import"./chunk-7BKKYVWR.js";import{f as O}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import{$ as fr,G as pr,H as mr,P as hr,Q as gr,S as _r,a as k,ca as vr,e as yr,g as A,ga as br,h as j,ha as xr,i as Sr,n as Cr,na as wr,pa as Tr,sa as Er,w as Dr,z as Or}from"./chunk-OCE6KQGJ.js";import{g as kr}from"./chunk-IVDE66N5.js";import"./chunk-74JZTGTO.js";import"./chunk-IYPY47MC.js";import{d as Ar,i as jr,k as Mr,l as Nr,r as Pr,x as Fr}from"./chunk-ITUKKCCK.js";import{a as Ir,d as Lr}from"./chunk-PWFUOLZK.js";import"./chunk-C4Z6ZBXV.js";import{a as Rr,e as zr,f as Br,n as Vr,o as Hr,u as Ur,w as Wr,y as Gr}from"./chunk-WGQ7D5DB.js";import{B as Kr,I as qr,h as Jr,l as Yr}from"./chunk-QRKFPLA4.js";import{a as M,b as Xr,c as N,g as P,i as Zr,j as F}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var Qr={importedSideLabel:`Apply from chain`,applyButton:`Apply`},$r={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.`,...Qr},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.`,...Qr}};function ei(){Mn(async(e,t,n)=>{let r=je(e);try{return await gn(e,r,$r[n]??$r.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 ti=class extends Ot{static properties={_value:{state:!0}};static secrets={_value:``};constructor(){super(),this._value=``}_onInput=e=>{this._value=e.target.value};_onSubmit=()=>{this._value&&this._finish(this._value)};_onKeydown=en(this._onSubmit);render(){return N`<dialog @close="${this._onClose}"><header><h3>Sync server password</h3></header><p class="nwd-intro">${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.`}</p>${ln({name:`dv-sync-auth`,maxlength:4096,placeholder:`Password`,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="${!this._value}" @click="${this._onSubmit}">${this.retry?`Retry`:`Authenticate`}</button></footer></dialog>`}};customElements.define(`sync-auth-dialog`,ti);function ni({retry:e=!1}={}){return jt(`sync-auth-dialog`,{retry:!!e})}function ri(){kn(async({retry:e})=>{try{return await ni({retry:e})}catch(e){return console.warn(`Sync auth dialog failed to open:`,e),null}})}var ii=`https://triage.space/`,ai=[{hostname:`deepaudit.dev`,pathPrefix:`/`,supportsSync:!0},{hostname:`chalker.github.io`,pathPrefix:`/deepview/`,supportsSync:!1}];function oi(){return ai.find(e=>location.hostname===e.hostname&&location.pathname.startsWith(e.pathPrefix))??null}var si=[`deepview.triage`,`deepview.triage.pending`],ci=`deepview.repoUrls`;function li(){try{if(si.some(e=>localStorage.getItem(e)))return!0;let e=localStorage.getItem(ci);if(!e)return!1;let t=JSON.parse(e);return!!(t&&typeof t==`object`&&Object.keys(t).length>0)}catch{return!0}}async function ui(){if(li())return!0;let e=[];try{e=await zn()}catch{return!0}if(e.length>0)return!0;try{if(xe().length>0)return!0}catch{return!0}try{return await f()}catch{return!0}}var di=class extends F{static properties={supportsSync:{attribute:!1}};createRenderRoot(){return this}constructor(){super(),this.supportsSync=!1}firstUpdated(){this.querySelector(`dialog`)?.showModal(),this.querySelector(`button.om-stay`)?.focus()}_finish(e){this._settled||(this._settled=!0,this.querySelector(`dialog`)?.close(),this.dispatchEvent(new CustomEvent(`resolve`,{detail:e})))}_onStay=()=>this._finish(!1);_onMigrate=()=>this._finish(!0);render(){let e=()=>N`<a class="om-link" href="${ii}" target="_blank" rel="noopener noreferrer">${ii}</a>`;return N`<dialog class="origin-migration-dialog" @close="${this._onStay}"><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?N`<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>`:N`<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`,di);function fi(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 pi(){let e=oi();return e?await ui()?await fi(e)?(location.assign(ii),!0):!1:(location.replace(ii),!0):!1}var I=null,mi=!1,hi=null,gi={NotAllowedError:``,AbortError:``,SecurityError:`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.`,InvalidStateError:`The passkey state on this device is inconsistent. Try reloading the page or removing and re-creating the passkey.`,NotSupportedError:`This browser does not support the WebAuthn PRF extension this site needs. Try a recent Chrome, Safari, or Edge with a platform authenticator.`,NetworkError:`A network error prevented the passkey from completing. Check your connection and try again.`,UnknownError:`The authenticator returned an unknown error. Try again, or use a different passkey.`};function _i(e){if(!e)return`Could not unlock. Try again.`;let t=e.name??``;if(Object.hasOwn(gi,t))return gi[t];let n=e.message??String(e);return n.length>200?n.slice(0,197)+`…`:n}function vi(){if(I)return I;I=document.createElement(`div`),I.id=`lock-overlay`,I.setAttribute(`role`,`dialog`),I.setAttribute(`aria-modal`,`true`),I.setAttribute(`aria-label`,`Unlock DeepView`),Zr(N`<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>`,I);let e=I.querySelector(`button`),t=I.querySelector(`.lock-overlay-error`);return e.addEventListener(`click`,async()=>{if(!mi&&yi()){mi=!0,t.hidden=!0,t.textContent=``,e.disabled=!0,e.textContent=`Waiting…`,hi=new AbortController;try{await zt({signal:hi.signal})}catch(e){let n=_i(e);t.textContent=n,t.hidden=!n}finally{mi=!1,hi=null,e.disabled=!1,e.textContent=`Unlock with passkey`}}}),I.querySelector(`.lock-overlay-wipe`).addEventListener(`click`,async e=>{if(e.preventDefault(),!mi&&yi()&&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.75",
3
+ "version": "1.0.0-alpha.76",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -211,8 +211,11 @@
211
211
  "server-managed/repository-actions.ts",
212
212
  "server-managed/repository-risk.ts",
213
213
  "server-managed/repository-risk-assess.ts",
214
+ "server-managed/repository-risk-caches.ts",
214
215
  "server-managed/repository-risk-audit.ts",
215
216
  "server-managed/repository-risk-read.ts",
217
+ "server-managed/repository-risk-stasis.ts",
218
+ "server-managed/repository-risk-turn.ts",
216
219
  "server-managed/scan-downloads.ts",
217
220
  "server-managed/session.ts",
218
221
  "server-managed/slugs.ts",
@@ -449,7 +452,7 @@
449
452
  "@preventive/publishers": "^1.1.0",
450
453
  "@preventive/report": "^1.0.1",
451
454
  "@preventive/sourcemap": "1.0.0-alpha.1",
452
- "@preventive/upstream": "^1.9.1",
455
+ "@preventive/upstream": "^1.10.0",
453
456
  "css-tree": "^3.2.1",
454
457
  "oxc-minify": "^0.158.0",
455
458
  "oxc-parser": "^0.152.0",
@@ -73,6 +73,9 @@ export function withFormatted<T extends DependencyReview>(reviewed: ReviewedDepe
73
73
  // or the base the host names it (`bases`; pull-dependency-reviews.ts reviewsOf,
74
74
  // comparedWith, basesOf), or, `any`, with any version of its package.
75
75
  interface Own { review: PublishedReview; pkgs: LockedPackage[] }
76
+ // The latest of `reviews`, some, the first of those as late, as
77
+ // pull-dependency-reviews.ts stancesOf takes it.
78
+ const latestOf = (reviews: PublishedReview[]) => reviews.reduce((one, other) => other.time > one.time ? other : one)
76
79
  function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string, any: boolean, bases: Map<string, ReviewedBase>): Map<string, Own> {
77
80
  // Theirs by the version they are of, each version probed once.
78
81
  const theirs = reviewsByVersion(reviews.filter(review => review.id !== undefined && review.reviewer === user))
@@ -91,14 +94,17 @@ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: str
91
94
  // request `number` of `repository` adds (`told`), those its review's state
92
95
  // tells of, published to a team counting for it; none where it has none.
93
96
  // A review is left out where every version it is of, as locked, wants no
94
- // comment of it there: the host's `lookup` passes it already, or `user`'s
95
- // own comments there (of `commented`, the reviews its comments make) review
96
- // it with the same verdict, as copying it would but repeat them: by their
97
- // latest of it, which tells where they stand there (pull-dependency-
98
- // reviews.ts stancesOf), an older one of that verdict not counting. A
99
- // version `lookup` fails to answer of keeps its review. Where the host reads
100
- // reviews of comments (`parseComments`), what a review was compared with is
101
- // its to weigh, so one compared with any version is given.
97
+ // comment of it there, as copying it would but repeat what `user` posted
98
+ // there: the host's `lookup` passes it already, or `user`'s own comments
99
+ // there (of `commented`, the reviews its comments make) make one of it with
100
+ // the same verdict, any of them, a later one of another verdict too; or
101
+ // stand on it, by their latest of it (pull-dependency-reviews.ts stancesOf),
102
+ // where `user`'s latest review of it does, their older ones of it then
103
+ // wanting no comment either, as where the host reads one verdict of a
104
+ // version of a comment. A version `lookup` fails to answer of keeps its
105
+ // review. Where the host reads reviews of comments (`parseComments`), what a
106
+ // review was compared with is its to weigh, so one compared with any version
107
+ // is given.
102
108
  export async function formattedPull(reviewed: ReviewedDependencies | null, db: Pick<DependencyReviewStore, 'listOwnDependencyReviewsById'>, user: string,
103
109
  told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = [],
104
110
  bases: Map<string, ReviewedBase> = new Map()): Promise<string | null> {
@@ -107,8 +113,14 @@ export async function formattedPull(reviewed: ReviewedDependencies | null, db: P
107
113
  if (mine.size === 0) return null
108
114
  const { passed } = await askReviewed(reviewed.lookup, new Map([...mine.values()].flatMap(({ pkgs }) => pkgs.map(askedOf))))
109
115
  const there = reviewsByVersion(commented.filter(review => review.reviewer === user))
110
- const stands = (pkg: LockedPackage) => reviewsOf(pkg, there).reduce<PublishedReview | null>((one, other) => one && one.time >= other.time ? one : other, null)?.status
111
- const ids = [...mine].filter(([, { review, pkgs }]) => pkgs.some(pkg => !passed.has(askedOf(pkg)[0]) && stands(pkg) !== review.status)).map(([id]) => id)
116
+ // `user`'s own of each version, as locked.
117
+ const ownOf = new Map<LockedPackage, PublishedReview[]>()
118
+ for (const { review, pkgs } of mine.values()) for (const pkg of pkgs) (ownOf.get(pkg) ?? ownOf.set(pkg, []).get(pkg)!).push(review)
119
+ const posted = (review: PublishedReview, pkg: LockedPackage) => {
120
+ const made = reviewsOf(pkg, there)
121
+ return made.some(one => one.status === review.status) || (made.length > 0 && latestOf(made).status === latestOf(ownOf.get(pkg)!).status)
122
+ }
123
+ const ids = [...mine].filter(([, { review, pkgs }]) => pkgs.some(pkg => !passed.has(askedOf(pkg)[0]) && !posted(review, pkg))).map(([id]) => id)
112
124
  if (ids.length === 0) return null
113
125
  const reviews: DependencyReview[] = []
114
126
  for (let at = 0; at < ids.length; at += REVIEWS_AT_ONCE) reviews.push(...await db.listOwnDependencyReviewsById(user, ids.slice(at, at + REVIEWS_AT_ONCE)))
@@ -3684,8 +3684,9 @@ function scanProgress(deps: ManagedHttpDeps, key: string, scan: string | null) {
3684
3684
  }
3685
3685
 
3686
3686
  // GET /api/admin/repositories/risk: every connected repository's npm
3687
- // packages, or a team's or one repository's (riskRepositories), as its
3688
- // lockfiles lock them at its default branch's head, each assessed by risk
3687
+ // packages, or a team's or one repository's (riskRepositories), but those
3688
+ // GitHub has archived, told so as each is opened and read no further, as
3689
+ // its lockfiles lock them at its default branch's head, each assessed by risk
3689
3690
  // (repository-risk.ts), a line as each is found. A
3690
3691
  // repository is read with the admin's own GitHub access, as browsing it is
3691
3692
  // (repository-browser.ts), and that access checked again once it is read,
@@ -3697,7 +3698,8 @@ function scanProgress(deps: ManagedHttpDeps, key: string, scan: string | null) {
3697
3698
  // GitHub (dependabot-access.ts); and its GitHub Actions, the references they
3698
3699
  // make resolved with the admin's own GitHub token (github-actions.ts); and
3699
3700
  // what Stasis reaches of each of its stasis.config.json files, as its
3700
- // dependency review has them built (riskStasis). Read by an admin, or by a
3701
+ // dependency review has them built (riskStasis), a build still to be made
3702
+ // looked at again as the scan goes on. Read by an admin, or by a
3701
3703
  // manager of the team it names (readRiskSession), each alike, with their
3702
3704
  // own access. The reader leaving, losing what let them read it or the
3703
3705
  // server shutting down stops it.
@@ -3732,6 +3734,8 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3732
3734
  repos: () => Promise.resolve(repos),
3733
3735
  async open(repo) {
3734
3736
  const reader = await browser.reader(repo)
3737
+ // One GitHub has archived is read no further, as nothing installs from it anew.
3738
+ if (reader.archived) return { archived: true as const }
3735
3739
  const commit = await reader.commit('')
3736
3740
  const token = reader.readToken()
3737
3741
  const client = createClient({ token })
@@ -3750,6 +3754,10 @@ async function handleRepositoryRisk(res: ServerResponse, deps: ManagedHttpDeps,
3750
3754
  stasis: config => riskStasis(deps, repo, token, commit, reader.defaultBranch, config),
3751
3755
  }
3752
3756
  },
3757
+ // What Stasis has made of a build still to be made as the scan read its
3758
+ // repository, as its dependency review's reader has it: the page asks
3759
+ // for the build again (handleRepositoryRiskStasis), the scan only looks.
3760
+ stasisBuilt: ({ repoId, commit, config }) => stasisReader(deps).read(repoId, commit, config),
3753
3761
  // References resolved with the admin's token, and each one's advisories
3754
3762
  // asked as a bundle's `github` package's are (bundle-advisories.ts), one
3755
3763
  // `internal` of its repository alone, each bounded on its own.
@@ -1,20 +1,21 @@
1
- // Items in the order they are added, each taken once by whichever reader asks
2
- // first: none once closed and all taken, or once `signal` aborts, but those
3
- // added by then where `drain`, none waited for.
4
- export interface Queue<T> { add(item: T): void; close(): void; take(): Promise<T | undefined> }
1
+ // Items in the order they are added, those added `first` before the rest,
2
+ // each taken once by whichever reader asks first: none once closed and all
3
+ // taken, or once `signal` aborts, but those added by then where `drain`, none
4
+ // waited for.
5
+ export interface Queue<T> { add(item: T, first?: boolean): void; close(): void; take(): Promise<T | undefined> }
5
6
  export function queue<T>(signal: AbortSignal, { drain = false } = {}): Queue<T> {
6
- const items: T[] = []
7
+ const firsts: T[] = [], items: T[] = []
7
8
  const waiting: (() => void)[] = []
8
9
  let closed = false
9
10
  const wake = () => { for (const resolve of waiting.splice(0)) resolve() }
10
11
  signal.addEventListener('abort', wake, { once: true })
11
12
  return {
12
- add(item) { items.push(item); wake() },
13
+ add(item, first = false) { (first ? firsts : items).push(item); wake() },
13
14
  close() { closed = true; wake() },
14
15
  async take() {
15
16
  for (;;) {
16
17
  if (signal.aborted && !drain) return undefined
17
- const item = items.shift()
18
+ const item = firsts.length > 0 ? firsts.shift() : items.shift()
18
19
  if (item !== undefined || closed || signal.aborted) return item
19
20
  await new Promise<void>(resolve => { waiting.push(resolve) })
20
21
  }
@@ -65,7 +65,7 @@ function credentialFailure(err: unknown): err is GithubApiError {
65
65
  // that token (`userToken`, hashed), whichever credential reads it: a private
66
66
  // repository's was granted on who that token told GitHub they are. The next
67
67
  // check asks GitHub, falling back to the installation's or none as it does.
68
- type RepoMetadata = { id?: unknown; full_name?: unknown; private?: unknown; visibility?: unknown; default_branch?: unknown }
68
+ type RepoMetadata = { id?: unknown; full_name?: unknown; private?: unknown; visibility?: unknown; default_branch?: unknown; archived?: unknown }
69
69
  type AccessVerdict = { until: number; data: RepoMetadata; credential: 'user' | 'app' | 'none'; level: string | null; userToken: string | null }
70
70
  type VerdictCache = { get(): AccessVerdict | undefined; set(verdict: Omit<AccessVerdict, 'until' | 'userToken'>): void }
71
71
  const MAX_ACCESS_VERDICTS = 1000
@@ -251,8 +251,8 @@ async function keptAccess(verdicts: VerdictCache | null, userToken: string | nul
251
251
  if (kept.credential === 'none' || credential) return { data: kept.data, token: credential, level: kept.level }
252
252
  }
253
253
  const asked = await ask()
254
- const { id, full_name, private: hidden, visibility, default_branch } = asked.data
255
- const data = { id, full_name, private: hidden, visibility, default_branch }
254
+ const { id, full_name, private: hidden, visibility, default_branch, archived } = asked.data
255
+ const data = { id, full_name, private: hidden, visibility, default_branch, archived }
256
256
  verdicts?.set({ data, credential: asked.token === null ? 'none' : asked.token === userToken ? 'user' : 'app', level: asked.level })
257
257
  return { ...asked, data }
258
258
  }
@@ -299,6 +299,9 @@ async function repositoryReader(repo: SelectedRepo, userToken: string | null, in
299
299
  // Its default branch as GitHub named it when access was first checked,
300
300
  // `''` where it named none: the one whose head `commit('')` reads.
301
301
  defaultBranch,
302
+ // Whether GitHub had it archived then, read-only, as a risk scan leaves
303
+ // one out (http.ts handleRepositoryRisk).
304
+ archived: current.archived === true,
302
305
  async refs() {
303
306
  // Suggestions are bounded; the input also accepts any branch or tag name.
304
307
  const list = async (kind: string) => {
@@ -0,0 +1,37 @@
1
+ // What repository risk scans keep between them (repository-risk.ts), in this
2
+ // instance's memory.
3
+ import { type Lru, lru } from './lru.ts'
4
+ import { type ActionAnswers, type ActionLine, type WorkflowsRead, answerWeight } from './repository-actions.ts'
5
+ import type { Audit } from './repository-risk-audit.ts'
6
+ import type { ListedLockfile, LockfileRead } from './repository-risk-read.ts'
7
+ import type { RiskLine } from './repository-risk.ts'
8
+
9
+ // What scans keep between them, in this instance's memory: a repository's
10
+ // lockfiles as listed at a commit, and a lockfile's packages by its blob,
11
+ // neither of which changes; a lockfile's advisories, asked again after
12
+ // RISK_KEPT_MS, as npm publishes advisories; and a package's risk line,
13
+ // told stale after RISK_KEPT_MS and assessed again, as risk tells again what
14
+ // of a package changes in time (a deprecation, its age, its downloads). A
15
+ // lockfile's, and its packages' lines, are told only once access to its
16
+ // repository is checked as when it was read.
17
+ export interface RiskCaches {
18
+ listings: Lru<ListedLockfile[]>
19
+ lockfiles: Lru<LockfileRead>
20
+ risks: Lru<{ at: number; line: RiskLine }>
21
+ advisories: Lru<{ at: number; audit: Audit }>
22
+ actionFiles: Lru<WorkflowsRead>
23
+ actions: Lru<{ at: number; line: ActionLine }>
24
+ actionAnswers: ActionAnswers
25
+ }
26
+ export const riskCaches = (): RiskCaches => ({
27
+ listings: lru(1000),
28
+ // By the packages they hold, a few hundred bytes each.
29
+ lockfiles: lru(200_000, read => 'packages' in read ? read.packages.length + 1 : 1),
30
+ risks: lru(50_000),
31
+ advisories: lru(50_000, kept => Array.isArray(kept.audit) ? kept.audit.length + 1 : 1),
32
+ // By their text, a kilobyte at a time.
33
+ actionFiles: lru(64 * 1024, read => 'files' in read ? read.files.reduce((sum, file) => sum + ('text' in file ? Math.ceil(file.text.length / 1024) : 1), 1) : 1),
34
+ actions: lru(10_000),
35
+ // What GitHub answered of public repositories' actions, by answerWeight.
36
+ actionAnswers: lru(200_000, answerWeight),
37
+ })
@@ -46,6 +46,9 @@ export type LockfileRead = { packages: LockedPackage[] } | RiskFailure
46
46
  // be had.
47
47
  export type DependabotRead = { alerts: DependabotAlert[]; recheck?(): Promise<void> } | RiskFailure
48
48
  export type RepositoryFailure = Extract<RepositoryRiskLine, { type: 'repo'; error: string }>
49
+ // A repository GitHub has archived, which a scan reads no further: its
50
+ // history alone, nothing that installs anew.
51
+ export type RepositoryArchived = Extract<RepositoryRiskLine, { type: 'repo'; archived: true }>
49
52
  // What Stasis reaches of a stasis.config.json, as a dependency review's
50
53
  // build of it tells (stasis-dependencies.ts): the versions it installs
51
54
  // (`dependencies`), that its build is still to be made (`pending`), or why it
@@ -57,6 +60,16 @@ export type StasisConfigRow = { path: string; lockfiles?: string[] } & ({ depend
57
60
  // what Stasis reaches of it, or why they couldn't be listed.
58
61
  export type StasisConfigsRead = { configs: StasisConfigRow[] } | RiskFailure
59
62
 
63
+ // A version, as Stasis tells those it installs, whatever its integrity.
64
+ export const versionKey = ({ name, version }: { name: string; version: string }) => `${name}@${version}`
65
+ // The versions a repository's Stasis builds made install (versionKey); none
66
+ // of those still to be made, which aren't waited for.
67
+ export const stasisVersions = (read: StasisConfigsRead | null): string[] => [...new Set(read && 'configs' in read
68
+ ? read.configs.flatMap(config => 'dependencies' in config ? config.dependencies.map(versionKey) : []) : [])]
69
+ // The paths of a repository's stasis.config.json files whose builds are still
70
+ // to be made.
71
+ export const stasisBuilding = (read: StasisConfigsRead | null): string[] => read && 'configs' in read ? read.configs.flatMap(config => 'pending' in config ? [config.path] : []) : []
72
+
60
73
  // A config's row of its read: a failed build told by its code (`detail`).
61
74
  export function stasisConfigRow(path: string, read: StasisRead): StasisConfigRow {
62
75
  if (read.status === 'ready') return { path, dependencies: read.dependencies }
@@ -87,7 +100,8 @@ export interface OpenedRepository {
87
100
  // What a repository is read with: the scan's source and caches, and its
88
101
  // signal.
89
102
  interface RepositoryReading<R extends RepositoryRiskRepo> {
90
- source: { open(repo: R): Promise<OpenedRepository>; listings?: KeptStore<ListedLockfile[]>; lockfiles?: KeptStore<LockfileRead>; actionFiles?: KeptStore<WorkflowsRead> }
103
+ source: { open(repo: R): Promise<OpenedRepository | { archived: true }>; listings?: KeptStore<ListedLockfile[]>; lockfiles?: KeptStore<LockfileRead>;
104
+ actionFiles?: KeptStore<WorkflowsRead> }
91
105
  caches: { listings: Lru<ListedLockfile[]>; lockfiles: Lru<LockfileRead>; actionFiles: Lru<WorkflowsRead> }
92
106
  signal: AbortSignal
93
107
  }
@@ -150,12 +164,15 @@ async function readLockfile({ source, caches }: RepositoryReading<RepositoryRisk
150
164
 
151
165
  // A repository opened and its lockfiles of npm's ecosystem listed, as kept
152
166
  // for its commit or else from GitHub, those of its `paths` alone; its line
153
- // telling why where either failed; null where the scan stopped.
154
- async function listLockfiles<R extends RepositoryRiskRepo>(reading: RepositoryReading<R>, repo: R) {
167
+ // telling why where either failed, or that GitHub has it archived, read no
168
+ // further; null where the scan stopped.
169
+ async function listLockfiles<R extends RepositoryRiskRepo>(reading: RepositoryReading<R>, repo: R):
170
+ Promise<{ opened: OpenedRepository; lockfiles: ListedLockfile[] } | RepositoryFailure | RepositoryArchived | null> {
155
171
  let doing = 'opening it'
156
172
  try {
157
173
  const opened = await reading.source.open(repo)
158
174
  if (reading.signal.aborted) return null
175
+ if ('archived' in opened) return { type: 'repo', id: repo.repoId, archived: true } as const
159
176
  doing = 'listing its lockfiles'
160
177
  const listed = await keptRead(reading.caches.listings, reading.source.listings, `${repo.repoId}@${opened.commit}`, () => opened.lockfiles())
161
178
  const lockfiles = listed.filter(({ path, format }) => NPM_LOCKFILE_FORMATS.has(format) && lockfileOf(path, repo.paths))
@@ -216,10 +233,10 @@ export const namedLockfiles = (path: string) => (text: string): string[] | null
216
233
  // A repository read: its lockfiles listed and read, a few at once, its
217
234
  // Dependabot alerts asked, its Actions read and its stasis.config.json files
218
235
  // asked meanwhile; its line telling why where listing
219
- // failed; null where the scan stopped. A test's
236
+ // failed, or that it is archived; null where the scan stopped. A test's
220
237
  // fixture or example its reader refuses (isTestFixture) is left out, as a
221
238
  // test may keep one so on purpose.
222
- export async function readRepository<R extends RepositoryRiskRepo>(reading: RepositoryReading<R>, repo: R): Promise<RepositoryRead | RepositoryFailure | null> {
239
+ export async function readRepository<R extends RepositoryRiskRepo>(reading: RepositoryReading<R>, repo: R): Promise<RepositoryRead | RepositoryFailure | RepositoryArchived | null> {
223
240
  const listed = await listLockfiles(reading, repo)
224
241
  if (!listed || 'type' in listed) return listed
225
242
  const { opened } = listed
@@ -0,0 +1,61 @@
1
+ // What a repository risk scan knows of Stasis's builds (repository-risk.ts):
2
+ // the versions those made install (versionKey), Stasis's wherever they are
3
+ // locked, as the page tells them apart (repository-risk.js stasisReach),
4
+ // assessed before the rest; the packages seen of each version, to move up
5
+ // once it is told Stasis's; and the builds still to be made as their
6
+ // repositories were read, watched: asked again every STASIS_AGAIN_MS what
7
+ // Stasis has made of them, as their page asks, none ever waited for.
8
+ import { setTimeout as delay } from 'node:timers/promises'
9
+ import type { AssessedPackage } from './repository-risk-assess.ts'
10
+ import { versionKey } from './repository-risk-read.ts'
11
+ import type { StasisRead } from './stasis-dependencies.ts'
12
+
13
+ // As often as a page asks again of the builds it shows still to be made
14
+ // (repository-risk.js STASIS_POLL_MS).
15
+ export const STASIS_AGAIN_MS = 30_000
16
+
17
+ // A build still to be made: of the stasis.config.json at `config` of
18
+ // repository `repoId` at `commit`.
19
+ export interface StasisBuild { repoId: number; commit: string; config: string }
20
+
21
+ export interface StasisReach {
22
+ // Whether a Stasis build made installs its version.
23
+ has(pkg: AssessedPackage): boolean
24
+ // A package the scan sees, the first time.
25
+ seen(pkg: AssessedPackage): void
26
+ // `versions` told Stasis's: the packages seen of those new to it.
27
+ add(versions: readonly string[]): AssessedPackage[]
28
+ // Builds still to be made, to watch.
29
+ building(builds: StasisBuild[]): void
30
+ // Those watched asked of `built` every `everyMs`, till `signal` aborts:
31
+ // each made since given to `made` with the versions it installs, once; one
32
+ // failed let go, one still to be made asked again.
33
+ watch(built: (build: StasisBuild) => Promise<StasisRead>, made: (build: StasisBuild, versions: string[]) => void, signal: AbortSignal, everyMs: number): Promise<void>
34
+ }
35
+
36
+ export function stasisReach(): StasisReach {
37
+ const builds = new Map<string, StasisBuild>(), reached = new Set<string>(), seen = new Map<string, AssessedPackage[]>()
38
+ return {
39
+ has: pkg => reached.has(versionKey(pkg)),
40
+ seen(pkg) { seen.set(versionKey(pkg), [...seen.get(versionKey(pkg)) ?? [], pkg]) },
41
+ add(versions) {
42
+ const fresh = [...new Set(versions)].filter(version => !reached.has(version))
43
+ for (const version of fresh) reached.add(version)
44
+ return fresh.flatMap(version => seen.get(version) ?? [])
45
+ },
46
+ building(told) { for (const build of told) builds.set(`${build.repoId}\0${build.commit}\0${build.config}`, build) },
47
+ async watch(built, made, signal, everyMs) {
48
+ for (;;) {
49
+ try { await delay(everyMs, undefined, { signal }) } catch { return }
50
+ for (const [key, build] of builds) {
51
+ let read: StasisRead
52
+ try { read = await built(build) } catch { continue }
53
+ if (signal.aborted) return
54
+ if (read.status === 'pending') continue
55
+ builds.delete(key)
56
+ if (read.status === 'ready') made(build, [...new Set(read.dependencies.map(versionKey))])
57
+ }
58
+ }
59
+ },
60
+ }
61
+ }
@@ -0,0 +1,97 @@
1
+ // A turn of a repository risk scan's assessments (repository-risk.ts): the
2
+ // packages given it, each assessed once, as many at a time as npm-risk.ts
3
+ // makes spare assessments, those `first` (the scan's Stasis's) before the
4
+ // rest, each given to the assessors once its downloads are readied, where
5
+ // the scan readies them (scan-downloads.ts); once all it is given are
6
+ // assessed, or the scan stops, those given once its feed is over too. One
7
+ // given that is `first` only since, as a Stasis build made since installs
8
+ // it, is hurried where it is still waiting: its downloads readied before the
9
+ // rest, or put before the rest waiting for an assessor.
10
+ import { MAX_SPARE_ASSESSMENTS } from './npm-risk.ts'
11
+ import { type Queue, queue } from './queue.ts'
12
+ import { type AssessedPackage, BUSY_RETRIES, BUSY_WAIT_MS, isBusy } from './repository-risk-assess.ts'
13
+ import { type DownloadsSource, readyingDownloads } from './scan-downloads.ts'
14
+
15
+ export interface Turn {
16
+ // Packages to assess: those given it before not again. False, none taken,
17
+ // once the turn is over.
18
+ give(packages: AssessedPackage[]): boolean
19
+ // Those of `packages` given it that are `first` now, hurried.
20
+ hurry(packages: AssessedPackage[]): void
21
+ }
22
+
23
+ export interface TurnOptions {
24
+ signal: AbortSignal
25
+ downloads: DownloadsSource | undefined
26
+ // A package as the scan tells it apart (repository-risk.ts seenKey).
27
+ key(pkg: AssessedPackage): string
28
+ first(pkg: AssessedPackage): boolean
29
+ assess(pkg: AssessedPackage): Promise<void>
30
+ }
31
+
32
+ // Where a package given is: its downloads being readied, waiting for an
33
+ // assessor, or taken by one.
34
+ type Given = 'readying' | 'pending' | 'taken'
35
+
36
+ async function assessor({ key, assess }: TurnOptions, pending: Queue<AssessedPackage>, given: Map<string, Given>, done: () => void) {
37
+ for (let next = await pending.take(); next !== undefined; next = await pending.take()) {
38
+ // One hurried is in line twice: assessed once.
39
+ if (given.get(key(next)) === 'taken') continue
40
+ given.set(key(next), 'taken')
41
+ try { await assess(next) } finally { done() }
42
+ }
43
+ }
44
+
45
+ // The packages `feed` gives the turn assessed, once `feed` ends and all
46
+ // given it are: those given it since too, it being over only then.
47
+ export async function assessingTurn(options: TurnOptions, feed: (turn: Turn) => Promise<void>): Promise<void> {
48
+ const { signal, downloads, key, first } = options
49
+ const pending = queue<AssessedPackage>(signal)
50
+ const given = new Map<string, Given>()
51
+ // Whether an assessor failed; what waits for the last of those given once
52
+ // `feed` is over; whether it is; how many given are still to be assessed;
53
+ // and whether the turn is over.
54
+ let broken = false, drained = () => {}, fed = false, left = 0, over = false
55
+ const done = () => { left--; if (fed && left === 0) drained() }
56
+ const toAssessors = (pkg: AssessedPackage) => { given.set(key(pkg), 'pending'); pending.add(pkg, first(pkg)) }
57
+ const readying = downloads ? readyingDownloads<AssessedPackage>(downloads, signal, toAssessors, { busy: isBusy, retries: BUSY_RETRIES, waitMs: BUSY_WAIT_MS }) : null
58
+ // One failing ends the wait for the rest, its failure thrown as the turn ends.
59
+ const assessors = Array.from({ length: MAX_SPARE_ASSESSMENTS }, () => assessor(options, pending, given, done).catch((error: unknown) => { broken = true; drained(); throw error }))
60
+ const turn: Turn = {
61
+ give(packages) {
62
+ if (over) return false
63
+ const fresh = packages.filter(pkg => !given.has(key(pkg)))
64
+ left += fresh.length
65
+ if (!readying) { for (const pkg of fresh) toAssessors(pkg); return true }
66
+ for (const pkg of fresh) given.set(key(pkg), 'readying')
67
+ const firsts = fresh.filter(first)
68
+ if (firsts.length > 0) readying.add(firsts, true)
69
+ if (firsts.length < fresh.length) readying.add(fresh.filter(pkg => !first(pkg)))
70
+ return true
71
+ },
72
+ hurry(packages) {
73
+ if (over) return
74
+ const names: string[] = []
75
+ for (const pkg of packages) {
76
+ if (!first(pkg)) continue
77
+ const at = given.get(key(pkg))
78
+ if (at === 'readying') names.push(pkg.name)
79
+ else if (at === 'pending') pending.add(pkg, true)
80
+ }
81
+ if (names.length > 0) readying?.hurry(names)
82
+ },
83
+ }
84
+ try { await feed(turn) } finally {
85
+ fed = true
86
+ if (left > 0 && !signal.aborted && !broken) {
87
+ await new Promise<void>(resolve => {
88
+ drained = resolve
89
+ signal.addEventListener('abort', () => { resolve() }, { once: true })
90
+ })
91
+ }
92
+ over = true
93
+ await readying?.close()
94
+ pending.close()
95
+ }
96
+ await Promise.all(assessors)
97
+ }