@preventive/triage 1.0.0-alpha.77 → 1.0.0-alpha.79

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.
Files changed (63) hide show
  1. package/common/line-diff.d.ts +2 -0
  2. package/common/line-diff.js +54 -0
  3. package/common/managed/dependency-routes.js +25 -0
  4. package/common/managed/finding-values.d.ts +2 -2
  5. package/common/managed/finding-values.js +128 -34
  6. package/common/managed/routes.js +9 -12
  7. package/common/pretty-json.js +95 -0
  8. package/common/pretty-print.d.ts +1 -0
  9. package/common/pretty-print.js +6 -0
  10. package/common/whitespace-insensitive.js +19 -0
  11. package/out/activity.js +2 -2
  12. package/out/{chunk-OCE6KQGJ.js → chunk-26W3E5JE.js} +1 -1
  13. package/out/chunk-3S4YWYOM.js +1 -0
  14. package/out/{chunk-OQS2USZM.js → chunk-55YIWY3H.js} +1 -1
  15. package/out/{chunk-IVDE66N5.js → chunk-6VXEPL32.js} +1 -1
  16. package/out/{chunk-XVKDPU4D.js → chunk-6Y6PZ2BU.js} +1 -1
  17. package/out/{chunk-S5PPXPAT.js → chunk-ATT2QA77.js} +1 -1
  18. package/out/{chunk-2V6Q4ZOZ.js → chunk-B64CTMVU.js} +1 -1
  19. package/out/{chunk-EXQQ5VQJ.js → chunk-BEKYZCPX.js} +1 -1
  20. package/out/{chunk-S2ZIKK45.js → chunk-EEJA7JBI.js} +1 -1
  21. package/out/{chunk-4IW3VD3H.js → chunk-FSU2PLJL.js} +1 -1
  22. package/out/{chunk-N7TD27UJ.js → chunk-IIJK4F4U.js} +1 -1
  23. package/out/{chunk-I6UQQKAH.js → chunk-LVSLM7HB.js} +1 -1
  24. package/out/{chunk-T6EXDRB7.js → chunk-MKX6JODK.js} +1 -1
  25. package/out/chunk-NTJJIEHS.js +259 -0
  26. package/out/{chunk-NEFCZAIY.js → chunk-PKLVXUEI.js} +1 -1
  27. package/out/chunk-QBIUW5EF.js +2 -0
  28. package/out/{chunk-ADMVRLNP.js → chunk-QD3IBSF4.js} +1 -1
  29. package/out/{chunk-GSNSP3EF.js → chunk-RPNO56H2.js} +1 -1
  30. package/out/{chunk-QBFT2DDR.js → chunk-UR4WYMIP.js} +1 -1
  31. package/out/{chunk-5DWOFBKS.js → chunk-V43XH2JQ.js} +1 -1
  32. package/out/{chunk-UH6NZBSU.js → chunk-VHEXSGGP.js} +1 -1
  33. package/out/chunk-XLX6XXJF.js +1 -0
  34. package/out/{chunk-BXQCCW7F.js → chunk-XM4RLC4A.js} +1 -1
  35. package/out/chunk-Z54AXVCK.js +3 -0
  36. package/out/client-managed-import.js +1 -1
  37. package/out/client-managed.js +4 -4
  38. package/out/compare.js +14 -14
  39. package/out/dialogs.js +37 -37
  40. package/out/graph.js +1 -1
  41. package/out/index.html +9 -7
  42. package/out/scan.js +2 -2
  43. package/out/terminal.js +7 -7
  44. package/out/view.css +1 -1
  45. package/out/view.js +8 -8
  46. package/package.json +8 -2
  47. package/server-managed/dependency-review-comments.ts +17 -10
  48. package/server-managed/http.ts +83 -19
  49. package/server-managed/npm-delta-worker.js +58 -12
  50. package/server-managed/npm-delta.ts +52 -28
  51. package/server-managed/npm-kept.ts +11 -1
  52. package/server-managed/pretty-copies.ts +22 -0
  53. package/server-managed/pretty-format.d.ts +3 -0
  54. package/server-managed/pretty-format.js +13 -0
  55. package/server-managed/pretty-print.ts +34 -24
  56. package/server-managed/public-workspace.ts +1 -1
  57. package/server-managed/team-reports.ts +25 -15
  58. package/out/chunk-G6YPDPW7.js +0 -2
  59. package/out/chunk-JCIIBLKR.js +0 -1
  60. package/out/chunk-SDLETN3Z.js +0 -3
  61. package/out/chunk-WGQ7D5DB.js +0 -1
  62. package/out/chunk-Z6DL5PPO.js +0 -255
  63. /package/out/{chunk-Z667U2UJ.js → chunk-SZWPYLPC.js} +0 -0
@@ -1,4 +1,4 @@
1
- import{a as e}from"./chunk-6VOB5WXX.js";import{g as t,n,r,s as i,t as a,u as o,v as s,w as c,x as l}from"./chunk-T6EXDRB7.js";import{a as u}from"./chunk-NRPC74AM.js";import{e as d,i as f}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import"./chunk-IVDE66N5.js";import"./chunk-WGQ7D5DB.js";import{D as p}from"./chunk-QRKFPLA4.js";import{a as m,c as h,g}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var _=`h1{font-size:1.35rem;margin-bottom:.5rem}h2{font-size:1.1rem;margin-bottom:.5rem}.triage-import{display:flex;gap:1rem;align-items:center;margin:1.5rem 0 2rem}.triage-import .btn{flex-shrink:0}.triage-import p{margin:0}.workspace-drop{display:grid;gap:.8rem;padding:2rem;margin:1.5rem 0;border:1px dashed var(--border);border-radius:var(--ui-radius, 8px)}.workspace-drop.dragging{border-color:var(--accent);background:rgb(from var(--accent) r g b / .08)}.workspace-drop span,p,li span{color:var(--muted);line-height:1.5}.actions,.local-choice{display:flex;gap:.8rem;flex-wrap:wrap;align-items:center}.local-choice{margin-bottom:1.5rem}.import-preview{display:grid;gap:.8rem}input:not([type=radio]),select{padding:.55rem;border:1px solid var(--border);border-radius:var(--ui-radius, 5px);color:var(--text);background:var(--bg);font:inherit}.import-preview input:not([type=radio]),.import-preview select{width:100%;box-sizing:border-box}fieldset{display:grid;gap:.8rem;padding:1rem;border:1px solid var(--border);border-radius:var(--ui-radius, 5px)}fieldset label{display:flex;gap:.5rem;align-items:center}li{padding:.4rem 0;overflow-wrap:anywhere}li span{display:block;font-size:.8rem}ul{padding-left:1.2rem}.primary{justify-self:start;color:var(--accent)}.error{color:var(--critical)}button:disabled{opacity:.5}input:focus-visible,select:focus-visible,button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
1
+ import{a as e}from"./chunk-6VOB5WXX.js";import{g as t,n,r,s as i,t as a,u as o,v as s,w as c,x as l}from"./chunk-MKX6JODK.js";import{a as u}from"./chunk-NRPC74AM.js";import{e as d,i as f}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import"./chunk-6VXEPL32.js";import"./chunk-XLX6XXJF.js";import{D as p}from"./chunk-QRKFPLA4.js";import{a as m,c as h,g}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var _=`h1{font-size:1.35rem;margin-bottom:.5rem}h2{font-size:1.1rem;margin-bottom:.5rem}.triage-import{display:flex;gap:1rem;align-items:center;margin:1.5rem 0 2rem}.triage-import .btn{flex-shrink:0}.triage-import p{margin:0}.workspace-drop{display:grid;gap:.8rem;padding:2rem;margin:1.5rem 0;border:1px dashed var(--border);border-radius:var(--ui-radius, 8px)}.workspace-drop.dragging{border-color:var(--accent);background:rgb(from var(--accent) r g b / .08)}.workspace-drop span,p,li span{color:var(--muted);line-height:1.5}.actions,.local-choice{display:flex;gap:.8rem;flex-wrap:wrap;align-items:center}.local-choice{margin-bottom:1.5rem}.import-preview{display:grid;gap:.8rem}input:not([type=radio]),select{padding:.55rem;border:1px solid var(--border);border-radius:var(--ui-radius, 5px);color:var(--text);background:var(--bg);font:inherit}.import-preview input:not([type=radio]),.import-preview select{width:100%;box-sizing:border-box}fieldset{display:grid;gap:.8rem;padding:1rem;border:1px solid var(--border);border-radius:var(--ui-radius, 5px)}fieldset label{display:flex;gap:.5rem;align-items:center}li{padding:.4rem 0;overflow-wrap:anywhere}li span{display:block;font-size:.8rem}ul{padding-left:1.2rem}.primary{justify-self:start;color:var(--accent)}.error{color:var(--critical)}button:disabled{opacity:.5}input:focus-visible,select:focus-visible,button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
2
2
  `;async function v(e,{session:t,confirmImport:n,...r}){if(t?.role!==`admin`||!t.csrfToken)throw Error(`An administrator session is required.`);if(e!=null&&(typeof e!=`object`||Array.isArray(e)))throw Error(`Invalid local triage.`);let i=Object.create(null);for(let[t,n]of Object.entries(e??{})){let{ignoredReports:e,scopedIgnoredReports:r,...a}=d(n)??{};Object.keys(a).length!==0&&(i[t]=a)}let a=Object.keys(i).length,o=new Set,s=[],c;if(a>0)do{r.signal?.throwIfAborted();let e=`/api/admin/reports/finding-ids`+(c?`?after=${encodeURIComponent(c)}`:``),{reports:t,nextCursor:n}=await r.api.send(e);r.signal?.throwIfAborted();for(let e of t){let t=e.findingIds.filter(e=>Object.hasOwn(i,e)&&!o.has(e));t.length>0&&s.push({id:e.id,ids:t});for(let e of t)o.add(e)}c=n}while(c);for(let e of o){if(!e||e.length>100)throw Error(`Triage finding IDs must be between 1 and 100 characters.`);if(l(i[e])===`invalid`)throw Error(`Triage for ${e} exceeds the managed server limits.`)}if(r.signal?.throwIfAborted(),n){let e=await n({matched:o.size,available:a});if(r.signal?.throwIfAborted(),!e)return null}let u=r.importedIds??new Set;for(let e of s)await S(i,{...r,importedIds:u,ids:e.ids,path:`/api/admin/reports/${encodeURIComponent(e.id)}/import-triage`});return o.size}function y(e,t){let n=[],r=Object.create(null);for(let[i,a]of Object.entries(e)){let e=t[i];if(!e)throw Error(`The server did not return the requested triage snapshot.`);let o=e.entry??{},s=r[i]={...o};delete s.comment;for(let[t,r]of Object.entries(a))if(t===`comment`){if(e.comments.some(e=>e.body===r))continue;e.comments.length>0?n.push({id:i,property:t,local:e.comments.map(e=>e.body).join(`
3
3
 
4
4
  `),imported:r}):s.comment=r}else if(o[t]!==void 0&&o[t]!==r){let e=e=>t===`flagged`?e?`flagged`:`not flagged`:e;n.push({id:i,property:t,local:e(o[t]),imported:e(r)})}else s[t]=r}return{entries:r,conflicts:n}}async function b(e,t,n,r,i){i?.throwIfAborted();let{entries:a,conflicts:o}=y(e,t);if(o.length===0)return a;let s=await r(o,n,{title:`Triage conflicts on import`,intro:`disagree with stored triage on`,trailingNote:`Imported comments are added alongside existing comments. Other choices apply to these finding IDs across all teams.`,importedSideLabel:`Apply imported`});if(i?.throwIfAborted(),!s)throw Object.assign(Error(`Triage conflict resolution was cancelled.`),{cancelled:!0});for(let t of o){let n=s[`${t.id}:${t.property}`];if(![`local`,`imported`].includes(n))throw Error(`Resolve every triage conflict before importing.`);n===`imported`&&(a[t.id][t.property]=e[t.id][t.property])}return a}function x(e,t){let n=[],r={entries:{},expected:{}};for(let[i,a]of Object.entries(e)){let e={entries:{...r.entries,[i]:a},expected:{...r.expected,[i]:t[i].version}};if(new TextEncoder().encode(JSON.stringify(e)).length<=262144)r=e;else{if(Object.keys(r.entries).length===0)throw Error(`This triage entry is too large to import.`);n.push(r),r={entries:{[i]:a},expected:{[i]:t[i].version}}}}return Object.keys(r.entries).length>0&&n.push(r),n}async function S(e,{api:t,path:n,ids:r=Object.keys(e),importedIds:i=new Set,lookup:a=new Map,resolveConflicts:o,signal:s}){r=r.filter(t=>Object.hasOwn(e,t)&&!i.has(t));for(let c=0;c<r.length;c+=200){let l=r.slice(c,c+200);for(let r=0;r<5&&l.length>0;r++){s?.throwIfAborted();let{snapshots:r}=await t.send(n,{findingIds:l}),c=await b(Object.fromEntries(l.map(t=>[t,e[t]])),r,a,o,s);for(let e of x(c,r)){if(s?.throwIfAborted(),(await t.send(n,e)).conflict)break;Object.keys(e.entries).forEach(e=>i.add(e))}l=l.filter(e=>!i.has(e))}if(l.length>0)throw Error(`Stored triage keeps changing. Retry to resolve it against the latest values.`)}}var C=`You can retry the remaining steps.`;function w(e){return String(e?.detail??e?.message??e).replace(/\.$/u,``)}function T(e,t){return t?.aborted===!0||e?.name===`AbortError`||e?.cancelled===!0}function E(e){if(typeof e!=`string`)return{ok:!0,path:null};if(/\p{Cc}/u.test(e)||e.includes(`\\`)||e!==e.trim())return{ok:!1};let t=[];for(let n of e.split(`/`))if(n!==``&&n!==`.`){if(n===`..`||n!==n.trim())return{ok:!1};t.push(n)}let n=t.join(`/`);return n.length>500?{ok:!1}:{ok:!0,path:n===``?null:n}}async function D(e,t){let a=new Uint8Array(await e.arrayBuffer());return n(a)?t({tryPassword:e=>r(a,e)}):a[0]===31&&a[1]===139?r(a):i(new TextDecoder(`utf-8`,{fatal:!0}).decode(a))}function O(e,t,n,r,i=``){let a=e?u(e,t,r,i):null,o=n.find(t=>a?t.repoId===a.repoId:t.fullName.toLowerCase()===e?.toLowerCase());return{repoId:o?.repoId??null,directory:a?.directory??t,github:o?.fullName??e}}async function k(e,n,r=[]){let i=new Map,l=[];for(let t of e.reports){if(typeof t?.name!=`string`||!t.name||typeof t.content!=`string`)throw Error(`Every report must have a name and content.`);let u=a(t.content,t.name);if(!u.data)throw Error(`${t.name}: ${u.reason??`Unsupported report`}`);let d=p(u.data),f=d??p(t)??p({repo:{github:e.repoUrls?.[t.name]}})??s(u.data),m=d?``:c(u.data),h=E(u.data.repo?.directory);if(!h.ok)throw Error(`${t.name}: invalid repository directory`);let g=u.format===`links`?[]:(await o(t.content,t.name))?.findings??[];for(let e of g)e.id&&i.set(e.id,e);let _=h.path??``;l.push({...t,links:u.format===`links`,...O(f,_,n,r,m),declaredGithub:f,declaredDirectory:_,filePrefix:m,embedded:d,ids:[...new Set(g.map(e=>e.id).filter(Boolean))],uploaded:null})}let u=Object.create(null);if(e.triage!=null&&(typeof e.triage!=`object`||Array.isArray(e.triage)))throw Error(`Invalid workspace triage.`);let f=await t(e.triage,t=>e.reports.find(e=>e.name===t)?.content);for(let[e,t]of Object.entries(f.entries)){if(!i.has(e))continue;let n=d(t);if(!n)continue;let{ignoredReports:r,scopedIgnoredReports:a,...o}=n;Object.keys(o).length!==0&&(u[e]=o)}let m=[];for(let t of e.bundleBlobs??[]){let e=Uint8Array.fromBase64(t.data),n=`sha512-${new Uint8Array(await crypto.subtle.digest(`SHA-512`,e)).toBase64()}`;if(n!==t.integrity)throw Error(`${t.name}: bundle integrity mismatch`);m.push({name:t.name,integrity:n,bytes:e,uploaded:null})}return{name:e.workspace.name.slice(0,100),reports:l,bundles:m,triage:u,lookup:i,references:e.bundles??[],team:null,completed:new Set,importedIds:new Set}}function A(e,t,n){async function r(r,i,a={}){n?.throwIfAborted();let o=await e(r,{credentials:`same-origin`,signal:n,...i===void 0?{}:{method:`POST`,body:i instanceof File?i:JSON.stringify(i)},headers:{...i instanceof File?{}:{"content-type":`application/json`},"x-csrf-token":t.csrfToken,...a}});if(n?.throwIfAborted(),o.status===409)return{conflict:!0};if(!o.ok){let e=await o.json().then(e=>typeof e?.error==`string`?e.error:``,()=>``);n?.throwIfAborted();let t=`Import request failed (HTTP ${o.status}${e?`: ${e}`:``}).`;throw Object.assign(Error(`${t} ${C}`),{detail:t})}let s=await o.json();return n?.throwIfAborted(),s}return{send:r}}async function j(e,t,n,r,i,a){if(e.bundles.length===0&&e.references.length===0)return;let o=i??(await n.send(`/api/admin/bundles`)).bundles,s=new Set(e.bundles.map(e=>e.uploaded.id));if([...s].some(e=>!o.some(t=>t.id===e)))throw Error(`Could not verify the uploaded source bundles. Retry the import.`);let c=new Set(e.references);for(let i of o){if(!s.has(i.id)&&!c.has(i.integrity))continue;let o=!a.has(i.repoId),l=o?t:i.repoId;o&&await r(`bundle-repo:${i.id}:${l}`,()=>n.send(`/api/admin/bundles/set-repo`,{bundleId:i.id,repoId:l}));let u=o?``:i.repoDirectory??``;await r(`repo:${l}:${u}`,()=>n.send(`/api/admin/teams/set-repo`,{teamId:e.team.id,repoId:l,path:u}))}}async function M(e,t){e.uploaded||=await t.send(`/api/admin/deduplication`,new File([e.content],e.name),{"x-report-filename":encodeURIComponent(e.name)})}async function N(e,t){let n=(await t.send(`/api/admin/repositories/browsable`)).repos,r=e.reports.filter(e=>!e.links&&e.declaredGithub&&!e.uploaded);if(r.length>0){let{aliases:e=[]}=await t.send(`/api/admin/repositories/aliases`);for(let t of r)Object.assign(t,O(t.declaredGithub,t.declaredDirectory,n,e,t.filePrefix))}return new Set(n.map(e=>e.repoId))}async function P(e,{plan:t,api:n,step:r,activeRepos:i,defaultRepo:a,includeTriage:o,resolveConflicts:s,signal:c}){if(e.links){await M(e,n);return}let l=i.has(e.repoId)?e.repoId:a;if(!e.uploaded){let t=await n.send(`/api/admin/reports`,new File([e.content],e.name),{"x-report-filename":encodeURIComponent(e.name),"x-repo-id":String(l),"x-repo-directory":encodeURIComponent(e.directory)});if(t.conflict)throw Error(`Could not reuse the stored report ${e.name}. Retry the import.`);e.uploaded=t}let u=e.uploaded;i.has(u.repoId)||await r(`report-repo:${u.id}:${l}:${e.directory}`,async()=>{if((await n.send(`/api/admin/reports/set-repo`,{reportId:u.id,repoId:l,directory:e.directory})).conflict)throw Error(`Could not assign the stored report ${e.name} to its repository.`);u.repoId=l,u.repoDirectory=e.directory});let d=u.repoDirectory??``;await r(`repo:${u.repoId}:${d}`,()=>n.send(`/api/admin/teams/set-repo`,{teamId:t.team.id,repoId:u.repoId,path:d})),o&&await S(t.triage,{api:n,resolveConflicts:s,signal:c,ids:e.ids,importedIds:t.importedIds,lookup:t.lookup,path:`/api/admin/reports/${encodeURIComponent(e.uploaded.id)}/import-triage`}),await r(`publish:${e.uploaded.id}`,()=>n.send(`/api/admin/reports/set-visible`,{reportId:e.uploaded.id,visible:!0}))}async function F(e,{api:t,session:n,defaultRepo:r,includeTriage:i,resolveConflicts:a,signal:o,progress:s=()=>{}}){if(n?.role!==`admin`||!n.csrfToken)throw Error(`An administrator session is required.`);if(!e.name.trim()||e.name.trim().length>100)throw Error(`Enter a team name of up to 100 characters.`);if(i)for(let[t,n]of Object.entries(e.triage)){if(!t||t.length>100)throw Error(`Triage finding IDs must be between 1 and 100 characters. Choose Skip triage to import the files without it.`);if(l(n)===`invalid`)throw Error(`Triage for ${t} exceeds the managed server limits. Choose Skip triage to import the files without it.`)}o?.throwIfAborted();let c=null;if(e.bundles.length===0){let n=new Set(e.references);c=n.size>0?(await t.send(`/api/admin/bundles`)).bundles.filter(e=>n.has(e.integrity)):[]}if(e.reports.length===0&&e.bundles.length===0&&c.length===0)throw Error(e.references.length>0?`None of the referenced source bundles are available on the server. Export with bundle bytes included and try again.`:`This workspace contains no report or bundle files.`);let u=await N(e,t);for(let t of e.reports.filter(e=>!e.links)){if(t.embedded&&!u.has(t.repoId))throw Error(`Connect ${t.embedded} in Repositories before importing ${t.name}.`);if(!u.has(t.repoId)&&!u.has(r))throw Error(`Choose an active repository for ${t.name}.`)}if((e.bundles.length>0||c.some(e=>!u.has(e.repoId)))&&!u.has(r))throw Error(`Choose an active repository for the source bundles.`);let d=()=>o?.throwIfAborted(),f=async(t,n)=>{d(),e.completed.has(t)||(await n(),e.completed.add(t))};if(d(),!e.team){let n=await t.send(`/api/admin/teams`,{name:e.name.trim()});if(n.conflict)throw Error(`A team already has this name. Choose another name.`);e.team=n}await f(`member`,()=>t.send(`/api/admin/teams/set-member`,{teamId:e.team.id,userId:n.id,security:!0,dependencies:!0}));for(let n of e.bundles)d(),s(`Importing ${n.name}\u2026`),n.uploaded||=await t.send(`/api/admin/bundles`,new File([n.bytes],n.name),{"x-bundle-filename":encodeURIComponent(n.name)});await j(e,r,t,f,c,u);let p=[];for(let n of e.reports){d(),s(`Importing ${n.name}\u2026`);try{await P(n,{plan:e,api:t,step:f,activeRepos:u,defaultRepo:r,includeTriage:i,resolveConflicts:a,signal:o})}catch(e){if(T(e,o))throw e;p.push(`${n.name}: ${w(e)}`)}}if(p.length>0)throw Error(`Could not import ${p.length} of ${e.reports.length} files: ${p.join(`; `)}. ${C}`);return e.team}function I(e){let t=()=>e.isEncryptionEnabled()&&!e.isUnlocked();return{get locked(){return t()},unlock:t=>e.unlockEncryption(t),async read({signal:n}={}){let r=!1,i=e.onVaultStateChange(()=>{r=!0}),a=()=>{if(n?.throwIfAborted(),t()||r)throw Error(`Local data was locked or changed. Unlock it and import triage again.`)};try{a();let t=await e.readTriageBlob();return a(),t}finally{i()}}}}function L(e){let t=()=>e.isEncryptionEnabled()&&!e.isUnlocked();async function n(){let t=JSON.parse(await e.hydrateKey(`deepview.workspaces`)||`[]`);return(Array.isArray(t)?t:t.workspaces??[]).filter(e=>typeof e.id==`string`&&typeof e.name==`string`)}async function r(n,r){let i=!1,a=[e.onVaultStateChange,e.onFileMutated,e.onBundleMutated].map(e=>e(()=>{i=!0})),o=()=>{if(r?.throwIfAborted(),t()||i)throw Error(`Local data was locked or changed. Unlock it and select the workspace again.`)};try{o();let e=await n(o);return o(),e}finally{a.forEach(e=>e())}}return{get locked(){return t()},unlock:t=>e.unlockEncryption(t),list:({signal:e}={})=>r(async()=>(await n()).map(e=>({id:e.id,name:e.name})),e),read:(t,{signal:i}={})=>r(async r=>{let i=(await n()).find(e=>e.id===t);if(!i)throw Error(`This local workspace no longer exists.`);let a=JSON.stringify(i),o=JSON.parse(await e.hydrateKey(`deepview.repoUrls`)||`{}`),s=[];for(let t of i.reports??[]){r();let n=await e.withStoredItem(`report`,t,()=>e.readFile(t));r(),s.push({name:t,content:n,...o[t]?{repo:{github:o[t]}}:{}})}let c=await e.listBundles(),l=[];for(let t of i.bundles??[]){r();let n=c.find(e=>e.integrity===t);if(!n)continue;let i=await e.withStoredItem(`bundle`,t,()=>e.readBundle(t));r(),l.push({integrity:t,name:n.name,data:i.toBase64()})}let u=await e.readTriageBlob()??{};if(JSON.stringify((await n()).find(e=>e.id===t))!==a)throw Error(`The local workspace changed. Select it again.`);return{version:1,workspace:{id:t,name:i.name,privateKey:``},reports:s,bundles:i.bundles??[],bundleBlobs:l,triage:u,repoUrls:o}},i)}}var R=e=>e===`bundle`?`bundles`:`reports`,z=(e,t)=>JSON.stringify([e,t||``]),B=(e,t)=>new Set(t.map(t=>e===`bundle`?t.integrity:z(t.sha256,t.analyzer)));async function V(e){let t=new Uint8Array(await e.arrayBuffer()),n=a(new TextDecoder().decode(t),e.name);if(!n.data)throw Error(n.reason??`Not a recognized report`);let r=new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)).toBase64({alphabet:`base64url`,omitPadding:!0});return{hash:r,key:z(r,typeof n.data.source==`string`?n.data.source:null)}}async function H(e,{source:t,deps:n,api:r,signal:i}){let a=JSON.parse(await n.hydrateKey(`deepview.workspaces`)||`[]`),o=(Array.isArray(a)?a:a.workspaces??[]).filter(e=>typeof e.id==`string`&&typeof e.name==`string`);i.throwIfAborted();let s=await t.list(e),c=B(e,(await r.send(`/api/admin/${R(e)}`))[R(e)]),l=o.map(e=>({id:e.id,name:e.name,items:[]})),u={id:null,name:`Not in a workspace`,items:[]},d=[];for(let r of s){i.throwIfAborted();let a={value:r.value,name:r.label,key:r.value,synced:!1,present:!1,error:``};if(e===`report`)try{Object.assign(a,await t.importItem(e,a.value,V,{signal:i})),a.syncHash=await n.reportSyncHash(a.value)}catch(e){i.throwIfAborted(),a.error=String(e?.message??e)}i.throwIfAborted(),a.present=c.has(a.key);let s=!1;o.forEach((t,r)=>{if(!t[R(e)]?.includes(a.value))return;let i=n.localContentSyncStatus(t.id,e,a.value,a.syncHash);a.synced||=i.synced,l[r].items.push({item:a,...i}),s=!0}),s||u.items.push({item:a,synced:!1,cached:!1}),d.push(a)}return{kind:e,items:d,groups:[...l,u].filter(e=>e.items.length>0)}}async function U(e,t,{source:n,api:r,signal:i,progress:a=()=>{},imported:o=new Set}){let{kind:s}=e,c=B(s,(await r.send(`/api/admin/${R(s)}`))[R(s)]),l=new Set(t),u=[],d=0;for(let t of e.items)if(i.throwIfAborted(),!(!l.has(t.value)||t.error||t.present)){if(c.has(t.key)){t.present=!0;continue}a(`Importing ${t.name}\u2026`),d++;try{await n.importItem(s,t.value,async e=>{let n=s===`report`?(await V(e)).key:await f(new Uint8Array(await e.arrayBuffer()));if(i.throwIfAborted(),n!==t.key)throw Error(`${t.name} changed. Choose files again before importing.`);if((await r.send(`/api/admin/${R(s)}`,e,{[`x-${s}-filename`]:encodeURIComponent(e.name)})).conflict)throw Error(`Could not import ${t.name}. Try again.`)},{signal:i})}catch(e){if(T(e,i))throw e;u.push(`${t.name}: ${w(e)}`);continue}c.add(t.key),t.present=!0,o.add(t.value)}if(u.length>0)throw Error(`Imported ${d-u.length} of ${d} ${s}s. Could not import ${u.join(`; `)}. Import again to retry them.`);return o.size}var W=(e,t)=>e===void 0?`managed-only`:t===void 0?`local-only`:`mismatch`;function G(e,t){let n=t.slice(),r=e.map(e=>{let t=n.indexOf(e);return t!==-1&&n.splice(t,1),{text:e,different:t===-1}}),i=e.slice(),a=t.map(e=>{let t=i.indexOf(e);return t!==-1&&i.splice(t,1),{text:e,different:t===-1}});return!r.some(e=>e.different)&&!a.some(e=>e.different)?null:{property:`comment`,local:r,managed:a,kind:r.some(e=>e.different)?a.some(e=>e.different)?`mismatch`:`local-only`:`managed-only`}}function K(e,t){let n=d(e)??{},r=d(t.entry)??{},i=[];for(let e of[`triage`,`color`,`fix`,`flagged`])n[e]!==r[e]&&i.push({property:e,local:n[e],managed:r[e],kind:W(n[e],r[e])});let a=G(n.comment?[n.comment]:[],t.comments.map(e=>e.body));return a&&i.push(a),n.ignoredReports?.length&&i.push({property:`ignoredReports`,local:[...new Set(n.ignoredReports)],managed:void 0,kind:`local-only`}),i}async function q(e,{lookup:t,triage:n,matched:r,findings:i,api:a,signal:o}){let s=[...new Set(e.findingIds)].filter(e=>t.has(e)&&!r.has(e));for(let c=0;c<s.length;c+=200){let l=s.slice(c,c+200);if(l.some(e=>e.length>100))throw Error(`A shared finding ID exceeds the managed triage limit.`);o.throwIfAborted();let{snapshots:u}=await a.send(`/api/admin/reports/${encodeURIComponent(e.id)}/import-triage`,{findingIds:l});o.throwIfAborted();for(let e of l){if(!u?.[e])throw Error(`The server did not return the requested triage snapshot.`);let a=K(n[e],u[e]);a.length>0&&i.push({id:e,finding:t.get(e),differences:a}),r.add(e)}}}async function J({source:e,readTriage:t,api:n,signal:r,progress:i=()=>{}}){let s=new Map,c=[];for(let t of await e.list(`report`)){r.throwIfAborted(),i(`Reading ${t.label}\u2026`);try{let n=await e.importItem(`report`,t.value,async e=>{let t=await e.text(),n=a(t,e.name);if(!n.data)throw Error(n.reason??`Not a recognized report`);return n.format===`links`?[]:(await o(t,e.name))?.findings??[]},{signal:r});r.throwIfAborted();for(let e of n)typeof e.id!=`string`||!e.id||(s.has(e.id)||s.set(e.id,{...e,reports:[]}),s.get(e.id).reports.push(t.label))}catch(e){r.throwIfAborted(),c.push({name:t.label,reason:String(e?.message??e)})}}let l=await t()??{};if(r.throwIfAborted(),typeof l!=`object`||Array.isArray(l))throw TypeError(`Invalid local triage.`);let u=[],d=new Set;if(s.size===0)return{matched:0,localFindings:0,findings:u,skipped:c};let f;do{r.throwIfAborted(),i(`Comparing local and managed triage…`);let e=await n.send(`/api/admin/reports/finding-ids`+(f?`?after=${encodeURIComponent(f)}`:``));r.throwIfAborted();for(let t of e.reports)await q(t,{lookup:s,triage:l,matched:d,findings:u,api:n,signal:r});f=e.nextCursor}while(f);return r.throwIfAborted(),{matched:d.size,localFindings:s.size,findings:u,skipped:c}}function Y(t,n){if(customElements.get(`managed-admin-import`))return;class r extends t{static view=`manage-import`;static styles=[m(e),m(_)];static properties={localDeps:{attribute:!1},_busy:{state:!0},_error:{state:!0},_message:{state:!0},_plan:{state:!0},_catalog:{state:!0},_localOpen:{state:!0},_workspaces:{state:!0},_localId:{state:!0},_triage:{state:!0},_repo:{state:!0},_drag:{state:!0}};constructor(){super(),this._busy=!1,this._error=``,this._message=``,this._plan=null,this._catalog=null,this._workspaces=[],this._localOpen=!1,this._localId=``,this._triage=``,this._repo=null,this._files=[],this._drag=!1,this._local=!1,this._over=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),this._drag=!0)},this._drop=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),e.stopPropagation(),this._drag=!1,this._busy||(this._files.push(...e.dataTransfer.files),this._nextFile()))},this._localChanged=()=>{this._workspaces=[],this._localId=``,!this._unlocking&&(this._local&&(this._plan=null),(this._local||this._importingTriage||this._importingContent||this._comparingTriage)&&(this._operation?.abort(),this._message=``,this._error=this._comparingTriage?`Local data changed or was locked. Compare triage again to continue.`:this._importingContent?`Local data changed or was locked. Choose files again to continue.`:this._importingTriage?`Local data changed or was locked. Import triage again to continue.`:`Local data changed or was locked. Choose the workspace again.`))},this._blur=()=>{this._readingLocal&&this._localChanged()}}connectedCallback(){super.connectedCallback(),this.addEventListener(`dragover`,this._over),this.addEventListener(`drop`,this._drop),globalThis.addEventListener(`blur`,this._blur),globalThis.addEventListener(`storage`,this._localChanged),this._offVault=this.localDeps?.onVaultStateChange(this._localChanged),this._loadCatalog()}disconnectedCallback(){this._operation?.abort(),this._offVault?.(),this._plan=null,this._files=[],this.removeEventListener(`dragover`,this._over),this.removeEventListener(`drop`,this._drop),globalThis.removeEventListener(`blur`,this._blur),globalThis.removeEventListener(`storage`,this._localChanged),super.disconnectedCallback()}updated(e){e.has(`session`)&&(this._role!==`admin`||e.get(`session`)?.id!==this.session?.id)&&(this._operation?.abort(),this._plan=null,this._files=[])}async _action(e){if(this._busy||this._role!==`admin`)return;let t=this._operation=new AbortController,n=AbortSignal.any([t.signal,this.appState.sessionController.signal]);this._busy=!0,this._error=``;try{await e(n),n.throwIfAborted()}catch(e){n.aborted||(this._error=String(e?.message??e))}finally{this._operation===t&&(this._busy=!1)}}async _loadCatalog(){if(this._role===`admin`)try{await this._loadCollection(`workspace-import:catalog`,`import options`,async e=>{let t=A(n,this.session,e),[r,i,a,o]=await Promise.all([t.send(`/api/admin/reports`),t.send(`/api/admin/teams`),t.send(`/api/admin/bundles`),t.send(`/api/admin/repositories/aliases`)]);return{repos:r.repos,teams:i.teams,bundles:a.bundles,aliases:o.aliases}},e=>{this._catalog=e})}catch(e){this._error=String(e?.message??e)}}_browse(){let e=document.createElement(`input`);e.type=`file`,e.multiple=!0,e.accept=`.enc,.gz,.json`,e.addEventListener(`change`,()=>{this._files.push(...e.files),this._nextFile()},{once:!0}),e.click()}async _prepare(e,t){if(!e)return;if(this._catalog||await this._loadCatalog(),t.throwIfAborted(),!this._catalog)throw Error(`Could not load repositories. Try again.`);let n=await k(e,this._catalog.repos,this._catalog.aliases);t.throwIfAborted();let r=new Set(this._catalog.teams.map(e=>e.name)),i=n.name||`Imported workspace`,a=2;for(;r.has(n.name);){let e=` (${a++})`;n.name=i.slice(0,100-e.length)+e}let o=new Set(n.reports.map(e=>e.repoId).filter(e=>e!=null));this._repo=o.size===1?[...o][0]:null,this._triage=Object.keys(n.triage).length>0?``:`skip`,this._plan=n,this._message=``}async _nextFile(){if(this._files.length===0||this._busy)return;let e=this._files.shift();this._local=!1,this._plan=null,await this._action(async t=>{let n=await D(e,this.promptPassword);t.throwIfAborted(),await this._prepare(n,t)})}async _unlock(e,t){this._unlocking=!0;try{return!e.locked||await e.unlock({signal:t})}finally{this._unlocking=!1}}async _chooseLocal(){this._localOpen=!0,await this._action(async e=>{let t=L(this.localDeps);await this._unlock(t,e)&&(e.throwIfAborted(),this._workspaces=await t.list({signal:e}))})}async _readLocal(){if(!this._localId)return;let e=this._localId;this._local=!0,this._plan=null,await this._action(async t=>{let n=L(this.localDeps);if(await this._unlock(n,t)){this._readingLocal=!0;try{await this._prepare(await n.read(e,{signal:t}),t)}finally{this._readingLocal=!1}}})}async _import(){this._plan&&this._triage&&this._csrf&&(await this._action(async e=>{if(this._local&&L(this.localDeps).locked)throw Error(`Unlock local data and choose the workspace again.`);let t=this._plan,r=[`teams`,`reports`,`bundles`,`history`,`workspace-import`,`scan-sources`,`repo-impact`];try{let i=await this.appState.mutate(()=>F(t,{api:A(n,this.session,e),session:this.session,defaultRepo:this._repo,includeTriage:this._triage===`include`,resolveConflicts:this.resolveConflicts,signal:e,progress:e=>{this._message=e}}),r);this._catalog.teams.push(i),this._message=`Imported into ${i.name}.`,this._plan=null}finally{this.appState.invalidate(r),t.team&&this._emit(`managed-import-complete`)}}),!this._plan&&!this._error&&await this._nextFile())}async _importLocalTriage(){this._csrf&&await this._action(async e=>{this._importingTriage=!0,this._message=``;let t=new Set,r=[`reports`,`history`];try{let r=I(this.localDeps);if(!await this._unlock(r,e))return;this._readingLocal=!0;let i;try{i=await r.read({signal:e})}finally{this._readingLocal=!1}let a=await v(i,{api:A(n,this.session,e),session:this.session,resolveConflicts:this.resolveConflicts,signal:e,importedIds:t,confirmImport:async t=>(await this.confirmTriageImport({...t,signal:e}))?.confirmed===!0});if(e.throwIfAborted(),a===null)return;this._message=a?`Imported triage for ${a} finding${a===1?``:`s`}.`:`No local triage matches findings in managed reports.`}finally{this._importingTriage=!1,this.appState.invalidate(r),t.size>0&&this._emit(`managed-import-complete`)}})}async _compareLocalTriage(){this._csrf&&await this._action(async e=>{this._comparingTriage=!0,this._message=``;let t=this.localImportSource,r=t.subscribe(this._localChanged);try{if(!await this._unlock(t,e))return;e.throwIfAborted(),this._readingLocal=!0;let r=I(this.localDeps),i=await J({source:t,signal:e,readTriage:()=>r.read({signal:e}),api:A(n,this.session,e),progress:e=>{this._message=e}});e.throwIfAborted(),this._message=``,await this.showTriageComparison({comparison:i,signal:e})}finally{r(),this._readingLocal=!1,this._comparingTriage=!1,this._message=``}})}async _importLocalContent(e){this._csrf&&await this._action(async t=>{this._importingContent=!0,this._message=``;let r=this.localImportSource,i=[`reports`,`bundles`,`bundle-metadata`,`history`,`workspace-import`,`scan-sources`,`repo-impact`],a=new Set,o=r.subscribe(this._localChanged);try{if(!await this._unlock(r,t))return;t.throwIfAborted(),this._readingLocal=!0;let i=A(n,this.session,t),o=await H(e,{source:r,deps:this.localDeps,api:i,signal:t}),s=await this.confirmContentImport({plan:o,signal:t});if(t.throwIfAborted(),!s?.confirmed)return;let c=await U(o,s.selected,{source:r,api:i,signal:t,imported:a,progress:e=>{this._message=e}});this._message=`Imported ${c} ${e}${c===1?``:`s`}.`}finally{o(),this._readingLocal=!1,this._importingContent=!1,this.appState.invalidate(i),a.size>0&&this._emit(`managed-import-complete`)}})}render(){if(this._role!==`admin`)return g;let e=this._plan,t=e?Object.keys(e.triage).length:0,n=new Set([...e?.references??[],...e?.bundles.map(e=>e.integrity)??[]]),r=(this._catalog?.bundles??[]).filter(e=>n.has(e.integrity)),i=e?.references.filter(t=>!e.bundles.some(e=>e.integrity===t)).length??0;return h`<div class="wrap" @dragleave="${()=>{this._drag=!1}}">${this._nav()}<h1>Import</h1><section class="triage-import" aria-label="Import local files"><div class="actions"><button type="button" class="btn" ?disabled="${this._busy||!this._csrf}" @click="${()=>this._importLocalContent(`bundle`)}">Import bundles</button> <button type="button" class="btn" ?disabled="${this._busy||!this._csrf}" @click="${()=>this._importLocalContent(`report`)}">Import reports</button></div><p>Choose files from this browser, grouped by workspace. Import files without teams or triage.</p></section><section class="triage-import" aria-label="Local triage"><div class="actions"><button type="button" class="btn" ?disabled="${this._busy||!this._csrf}" @click="${()=>this._importLocalTriage()}">Import triage</button> <button type="button" class="btn" ?disabled="${this._busy||!this._csrf}" @click="${()=>this._compareLocalTriage()}">Compare triage</button></div><p>Import saved triage and comments for findings already in managed reports.<br>Unmatched data stays in this browser.<br>Conflicting values prompt for resolution; per-report ignores are skipped.</p></section><h2>Import workspace</h2><p class="intro ui-hint">Create a new team from a workspace export or a workspace stored in this browser.</p><section class="${`workspace-drop ${this._drag?`dragging`:``}`}" aria-label="Workspace files"><strong>Drop workspace files here</strong><span>Encrypted exports, JSON, or compressed JSON. Encrypted files prompt for a password.</span><div class="actions"><button type="button" class="btn" ?disabled="${this._busy||!this._catalog}" @click="${()=>this._browse()}">Choose files</button> <button type="button" class="btn" ?disabled="${this._busy}" @click="${()=>this._chooseLocal()}">Choose local workspace</button></div></section>${this._localOpen?h`<section class="local-choice"><label for="local-workspace">Local workspace</label> <select id="local-workspace" .value="${this._localId}" ?disabled="${this._busy}" @change="${e=>{this._localId=e.target.value}}"><option value="">Choose a workspace…</option>${this._workspaces.map(e=>h`<option value="${e.id}">${e.name}</option>`)}</select> <button type="button" class="btn" ?disabled="${this._busy||!this._localId}" @click="${()=>this._readLocal()}">Select workspace</button> ${!this._busy&&this._workspaces.length===0?h`<p class="ui-hint">No unlocked local workspaces. Choose local workspace to unlock or refresh.</p>`:g}</section>`:g} ${e?h`<section class="import-preview" aria-label="Import options">${e.team?h`<p>Team ${e.team.name} has been created. Retry continues its remaining import steps.</p>`:g} <label for="import-team">New team name</label><input id="import-team" maxlength="100" .value="${e.name}" ?disabled="${this._busy||!!e.team}" @input="${t=>{e.name=t.target.value,this.requestUpdate()}}"><p>${e.reports.length} reports / links · ${n.size} source bundles · ${t} triaged findings</p><label for="import-repo">Repository for files and source bundles without an active repository</label> <select id="import-repo" .value="${String(this._repo??``)}" ?disabled="${this._busy||!!e.team}" @change="${e=>{this._repo=e.target.value?Number(e.target.value):null}}"><option value="" ?selected="${this._repo==null}">Choose a repository…</option>${(this._catalog?.repos??[]).map(e=>h`<option value="${String(e.repoId)}" ?selected="${this._repo===e.repoId}">${e.fullName}</option>`)}</select><p>Declared report repositories and directories are preserved. Stored reports without an active repository use the selected repository. The new team receives those repository paths; other published reports in the same paths are also visible to that team.</p><ul>${e.reports.map(e=>h`<li>${e.name}<span>${e.links?`Global deduplication — enabled for all teams`:e.github??`Uses selected repository`}${e.links||e.github==null||e.repoId!=null?``:e.embedded?` — connect this repository first`:` — not connected; uses selected repository`}</span></li>`)}</ul>${r.length>0?h`<p>Existing source bundles in active repositories keep their locations. The new team also receives access to those directories. Unassigned bundles and bundles in inactive repositories use the selected repository.</p><ul>${r.map(e=>h`<li>${e.filename}<span>${e.repoFullName?`${e.repoFullName}${e.repoDirectory?`/${e.repoDirectory}`:``}`:`Uses selected repository`}</span></li>`)}</ul>`:g} ${i?h`<p>${i} referenced source bundles have no bytes in this export. Reports can use matching bundles already on the server.</p>`:g} ${t?h`<fieldset ?disabled="${this._busy||!!e.team}"><legend>Import triage?</legend><label><input type="radio" name="import-triage" value="include" ?checked="${this._triage===`include`}" @change="${()=>{this._triage=`include`}}"> Include triage and comments</label> <label><input type="radio" name="import-triage" value="skip" ?checked="${this._triage===`skip`}" @change="${()=>{this._triage=`skip`}}"> Skip triage</label><p>Conflicting values prompt for resolution. Triage stays shared by finding ID across teams. Per-report local ignores are not imported.</p></fieldset>`:g} <button type="button" class="btn primary" ?disabled="${this._busy||!this._triage||!this._csrf}" @click="${()=>this._import()}">${this._busy?`Importing…`:e.team?`Retry remaining import`:`Import workspace`}</button></section>`:g} ${this._message?h`<p role="status">${this._message}</p>`:g} ${this._error?h`<p class="error" role="alert">${this._error}${this._catalog?g:h`<button class="btn" @click="${()=>this._loadCatalog()}">Retry</button>`}</p>`:g} ${this._files.length>0&&!this._busy?h`<button class="btn" @click="${()=>this._nextFile()}">Next workspace file (${this._files.length} waiting)</button>`:g}</div>`}}customElements.define(`managed-admin-import`,r)}export{Y as registerWorkspaceImport};
@@ -1,4 +1,4 @@
1
- import{b as e,d as t,i as n}from"./chunk-WB3NRZL7.js";import{a as r}from"./chunk-6VOB5WXX.js";import{A as i,B as a,a as o,b as s,c,d as l,e as u,f as d,g as ee,h as te,i as ne,j as re,k as ie,l as ae,m as oe,n as se,o as ce,p as le,q as ue,r as de,s as fe,t as pe,u as me,v as he,w as ge,x as _e,y as ve,z as ye}from"./chunk-SDLETN3Z.js";import"./chunk-6CCSTJWB.js";import{$a as be,H as xe,I as Se,Ka as Ce,Sa as we,Ta as Te,X as Ee,Ya as De,Za as Oe,a as ke,ab as Ae,bb as je,cb as Me,db as Ne,eb as f,fb as Pe,g as Fe,gb as p,hb as Ie,i as Le,ja as Re,ka as ze,m as Be,ma as Ve,n as m,z as He}from"./chunk-EMNIV37E.js";import{y as Ue}from"./chunk-OWIBDEJJ.js";import"./chunk-S5HSDGTP.js";import{b as We}from"./chunk-NRPC74AM.js";import"./chunk-PNHBZGDD.js";import{a as h,e as Ge}from"./chunk-74JZTGTO.js";import"./chunk-IYPY47MC.js";import{C as Ke,D as qe,d as g,h as Je,i as Ye,j as Xe,x as _,y as Ze}from"./chunk-ITUKKCCK.js";import{a as Qe,d as $e}from"./chunk-PWFUOLZK.js";import"./chunk-C4Z6ZBXV.js";import{m as et,r as tt}from"./chunk-WGQ7D5DB.js";import{B as nt,D as rt,J as it}from"./chunk-QRKFPLA4.js";import{a as v,b as at,c as y,d as ot,g as b,j as st}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";function ct(e){let t=document.createElement(`input`);t.type=`file`,t.multiple=!0,t.addEventListener(`change`,()=>{e([...t.files])},{once:!0}),t.click()}function lt(e,t,n){let r=0,i=e=>Array.from(e.dataTransfer?.types??[]).includes(`Files`),a=e=>{i(e)&&(e.preventDefault(),r+=1,n(!0))},o=e=>{i(e)&&e.preventDefault()},s=e=>{i(e)&&(r=Math.max(0,r-1),r===0&&n(!1))},c=e=>{i(e)&&(e.preventDefault(),e.stopPropagation(),r=0,n(!1),t([...e.dataTransfer.files]))};return e.addEventListener(`dragenter`,a),e.addEventListener(`dragover`,o),e.addEventListener(`dragleave`,s),e.addEventListener(`drop`,c),()=>{e.removeEventListener(`dragenter`,a),e.removeEventListener(`dragover`,o),e.removeEventListener(`dragleave`,s),e.removeEventListener(`drop`,c)}}async function ut(e,t,n,r){let i=e.appState.generation;try{return await e.appState.mutate(()=>n(t),r)}catch(t){throw i===e.appState.generation&&e.appState.invalidate(r),t}}async function dt(e,t,n,r){if(e._busy||!e._csrf)throw Error(`Wait for the current operation to finish, then try again.`);e._busy=!0;try{await ut(e,t,n,r)}finally{await e._load(),e._busy=!1;let t=e._queue.splice(0);t.length>0&&e._upload(t)}}async function ft(e,t,n,r){if(t.length===0||(e._queue.push(...t),e._busy))return;e._busy=!0,e._error=null;let i=e.appState.generation,a=[],o=0;try{for(;e._queue.length>0;){if(e.appState.generation!==i){e._queue=[];break}let t=e._queue.shift();try{await ut(e,t,n,r)}catch(n){if(n?.name===`AbortError`||e.appState.generation!==i){e._queue=[];break}a.push(`${t.name}: ${String(n?.message??n)}`)}o++}}finally{a.length>0&&(e._error=o===1?`Upload failed: ${a[0]}`:`Upload failed for ${a.length} of ${o} files: ${a.join(`; `)}`),e._busy=!1,await e._load({preserveError:!0})}}var x=class extends st{static properties={session:{attribute:!1},allowShare:{attribute:!1},_loading:{state:!0},_data:{state:!0},_error:{state:!0}};constructor(){super(),this.session=null,this.allowShare=!1,this.appState=u,this._loading=!1,this._loadRequest=null,this._data=null,this._error=null}get _role(){return this.session?.role??null}get _csrf(){return this.session?.csrfToken??null}get _me(){return this.session?.id??null}connectedCallback(){super.connectedCallback(),this._load()}disconnectedCallback(){this._loadRequest?.abort(),super.disconnectedCallback()}async _load({preserveError:e=!1}={}){let{collection:t}=this.constructor;if(!t)return;e||(this._error=null);let[n,r,i]=t;await this._loadCollection(n,r,i,e=>this._show(e))}_show(e){this._data=e}async _loadCollection(e,t,n,r){this._loading=!0,await this._read(`_loadRequest`,e,t,n,{apply:r,settled:()=>{this._loading=!1},failed:t=>{this.appState.read(e)===void 0&&(this._error=String(t?.message??t))}})}async _read(e,t,n,r,{apply:i,answered:a,failed:o,settled:s}){this[e]?.abort();let c=this[e]=new AbortController;try{await this.appState.load(t,n,r,{signal:c.signal,apply:i}),c.signal.aborted||a?.()}catch(e){!c.signal.aborted&&e?.name!==`AbortError`&&o(e)}finally{this[e]===c&&s()}}_nav(){return Pe(this.constructor.view,this._role,this.allowShare)}_emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}_list(e,t,n){return y`<div class="manage-list" aria-busy="${this._loading}">${e==null?this._error?b:S(t):n()}</div>`}},pt=class{constructor(e,t=()=>!0){this.host=e,this.accepts=t,this.active=!1,e.addController(this)}hostConnected(){this.teardown=lt(this.host,e=>{this.accepts()&&this.host._upload(e)},e=>{this.active=this.accepts()&&e,this.host.requestUpdate()})}hostDisconnected(){this.teardown?.()}overlay(e){return this.active?y`<div class="dropzone">${e}</div>`:b}card(e,t,n,r=`Uploading…`){return y`<span class="drop-icon" aria-hidden="true">${p(`upload`)}</span><span class="drop-copy"><strong>${e}</strong><span>${t}</span></span><button type="button" class="drop-browse" ?disabled="${n}" @click="${()=>ct(e=>{this.host._upload(e)})}">${this.host._busy?r:`Browse files`}</button>`}};function S(e){return y`<div class="loading-rows" role="status"><span class="sr-only">${e}</span><div aria-hidden="true">${[0,1,2,3].map(()=>y`<div class="loading-row"><span></span><span></span></div>`)}</div></div>`}var C=e=>e?y`<p class="msg error" role="alert">${e}</p>`:b,w=(e,t)=>y`<div class="empty"><strong>${e}</strong><p>${t}</p></div>`;function mt(e){let t=e.split(`/`);return t.at(-1)===`stasis.config.json`&&!t.includes(`node_modules`)}var ht=class extends Te{get changeEvent(){return`local-item-change`}get searchLabel(){return`Search local files`}get optionsLabel(){return`Local files`}get noMatchesLabel(){return`No matching files.`}get emptyLabel(){return`No local files available.`}choices(){let e=this._query.trim().toLocaleLowerCase(),t=this.options.filter(t=>`${t.label} ${t.secondary??``}`.toLocaleLowerCase().includes(e));return{pinned:[],sections:[{options:t}],count:t.length,total:this.options.length,showFacets:!1}}};customElements.define(`managed-local-item-selector`,ht);var gt=class{constructor(e,t,n){this.host=e,this.kind=t,this.upload=n,this.source=null,this.hasData=!1,this.open=!1,this.options=[],this.value=null,this.busy=!1,this.loading=!1,this.error=``,this.success=``,this.generation=0,this.readAbort=null,this.onChange=e=>{if(e?.kind){if(e.kind!==this.kind)return;if(e.value!==this.value){this.refresh();return}}this.readAbort&&!this.readAbort.signal.aborted&&(this.readAbort.abort(),this.error=`The local ${this.kind} changed or the list was refreshed. Select it again before importing.`),this.options=[],this.value=null,this.success=``,this.refresh()},this.onBlur=()=>{this.readAbort&&!this.readAbort.signal.aborted&&this.onChange()},this.onVisibilityChange=()=>{globalThis.document?.visibilityState===`hidden`&&this.onBlur()},e.addController(this)}listeners(){return[[globalThis,`focus`,this.onChange],[globalThis,`blur`,this.onBlur],[globalThis,`storage`,this.onChange],[globalThis.document,`visibilitychange`,this.onVisibilityChange]]}hostConnected(){for(let[e,t,n]of this.listeners())e?.addEventListener(t,n);this.connectSource()}hostUpdated(){this.connectSource()}connectSource(){this.source!==this.host.localImportSource&&(this.unsubscribe?.(),this.abort?.abort(),this.source=this.host.localImportSource,this.unsubscribe=this.source?.subscribe(this.onChange),this.onChange())}hostDisconnected(){++this.generation,this.abort?.abort(),this.unsubscribe?.(),this.source=null;for(let[e,t,n]of this.listeners())e?.removeEventListener(t,n)}async refresh(){let e=++this.generation,t=this.source;this.loading=!0,this.host.requestUpdate();try{let n=t?await t.hasData(this.kind):!1;if(e!==this.generation)return;this.hasData=n;let r=this.open&&!t?.locked?await t?.list(this.kind)??[]:[];if(e!==this.generation)return;this.options=r,r.some(e=>e.value===this.value)||(this.value=null)}catch(t){e===this.generation&&(this.error=String(t?.message??t))}finally{e===this.generation&&(this.loading=!1,this.host.requestUpdate())}}toggle(){this.busy||(this.open=!this.open,this.error=``,this.success=``,this.options=[],this.value=null,this.refresh())}async busyWith(e){let t=this.abort=new AbortController;this.busy=!0,this.error=``,this.host.requestUpdate();try{await e(t)}catch(e){t.signal.aborted||(this.error=String(e?.message??e))}finally{this.readAbort===t&&(this.readAbort=null),this.busy=!1,this.host.requestUpdate()}}async unlock(){this.busy||await this.busyWith(async e=>{await this.source.unlock({signal:e.signal})&&!e.signal.aborted&&await this.refresh()})}async importSelected(){if(this.busy||this.loading||!this.value||this.source?.locked)return;this.success=``;let e=this.options.find(e=>e.value===this.value)?.label;await this.busyWith(async t=>{this.readAbort=t,await this.source.importItem(this.kind,this.value,e=>(this.readAbort=null,this.upload(e)),{signal:t.signal}),!t.signal.aborted&&!this.source?.locked&&(this.success=`Imported ${e}.`,this.value=null)})}renderAction(){return this.hasData||this.open?y`<button type="button" class="local-import-toggle" aria-expanded="${this.open}" aria-controls="local-import-panel" ?disabled="${this.busy}" @click="${()=>this.toggle()}">Import</button>`:b}renderPanel(e){if(!this.open)return b;let t=this.source?.locked;return y`<section class="local-import-panel" id="local-import-panel" aria-label="${`Import local ${this.kind}`}"><div class="local-import-copy"><strong>Import local ${this.kind}</strong><p>${t?`Unlock local data with your passkey to choose a file.`:`Copy a file from this browser to the managed workspace. The local copy stays on this device.`}</p></div><div class="local-import-controls">${t?y`<button type="button" class="local-import-submit" ?disabled="${this.busy}" @click="${()=>this.unlock()}">${this.busy?`Waiting for passkey…`:`Unlock with passkey`}</button>`:y`<managed-local-item-selector label="${`Choose local ${this.kind}`}" placeholder="${this.loading?`Loading local files…`:`Choose local ${this.kind}\u2026`}" .options="${this.options}" .value="${this.value}" ?disabled="${this.busy||this.loading}" @local-item-change="${e=>{this.value=e.detail.value,this.success=``,this.host.requestUpdate()}}"></managed-local-item-selector><button type="button" class="local-import-submit" ?disabled="${e||this.busy||this.loading||!this.value}" @click="${()=>this.importSelected()}">${this.busy?`Importing…`:`Import ${this.kind}`}</button>`} <button type="button" class="local-import-close" ?disabled="${this.busy}" @click="${()=>this.toggle()}">Close</button></div>${!t&&!this.loading&&this.options.length===0?y`<p class="local-import-message">No local ${this.kind}s available.</p>`:b} ${this.error?y`<p class="local-import-message error" role="alert">${this.error} <button type="button" ?disabled="${this.busy}" @click="${()=>{this.error=``,this.refresh()}}">Retry</button></p>`:b} ${this.success?y`<p class="local-import-message" role="status">${this.success}</p>`:b}</section>`}},T=e=>e?AbortSignal.any([e,u.sessionController.signal]):u.sessionController.signal,_t=()=>new DOMException(`Managed session changed`,`AbortError`),E=e=>e.json();async function vt({signal:e}={}){e=T(e),e.throwIfAborted();let t=await l(`/api/admin/bundles`,{credentials:`same-origin`,signal:e});if(e.throwIfAborted(),!t.ok)throw Object.assign(Error(`Bundle catalogue request failed (${t.status})`),{status:t.status});let n=await t.json();return e.throwIfAborted(),n.bundles??[]}async function D(e,t,n){let r=u.generation,i=await l(`/api/bundles/${encodeURIComponent(e)}/${t}`,{credentials:`same-origin`,signal:n});if(n?.throwIfAborted(),!i.ok)throw Object.assign(Error(`Bundle ${t} request failed (${i.status})`),{status:i.status});let a=t===`contents`?await i.text():await i.json();if(n?.throwIfAborted(),r!==u.generation)throw _t();return a}function yt(e,{signal:t}={}){return u.load(`bundle-metadata:${e}`,`bundle metadata`,t=>D(e,`metadata`,t),{signal:t,retryInvalidated:!0})}async function bt(e,{signal:t}={}){t=T(t);let n=await D(e,`metadata`,t),r=n?.bundle?.repo??null,i=rt({repo:r});if(!i)return r;let a=new URLSearchParams({repo:i,directory:r.directory??``}),o=new Set(n.unsized??[]),s=We((n.files??[]).filter(([e,t])=>t!=null||o.has(e)).map(([e])=>e));s&&a.set(`filePrefix`,s);let c=await l(`/api/admin/repositories/resolve?${a}`,{credentials:`same-origin`,cache:`no-store`,signal:t});if(t.throwIfAborted(),!c.ok)throw Error(`Repository suggestion request failed (${c.status})`);let{location:u}=await c.json();return t.throwIfAborted(),u?{...r,github:u.github,...u.mapped?{directory:u.directory}:{},repoId:u.repoId}:r}async function xt(e,{signal:t}={}){t=T(t);try{return await D(e,`contents`,t)}catch(e){throw e.name!==`AbortError`&&u.notify(`Couldn't load bundle contents: ${e.message}`),e}}function St(e,t,n=``,r=!1,i=!1){let a=n?`${n.startsWith(`entry:`)?`entry`:`reason`}=${encodeURIComponent(n.slice(n.indexOf(`:`)+1))}`:``,o=[t?`team=${encodeURIComponent(t)}`:``,a,r?`repoAdvisories=true`:``,i?`details=true`:``].filter(Boolean).join(`&`);return D(e,`advisories${o?`?${o}`:``}`,u.sessionController.signal)}var Ct={"patch-not-found":`The patch isn’t at the commit it was looked for at.`,"patch-mismatch":`The file at the commit the patch was read at isn’t the patch its lockfile names.`,"patch-unreadable":`The patch isn’t written as git writes one, so pnpm versions may apply it differently.`,"patch-unsupported":`The patch changes a file’s bytes, or gives it a mode other than 644 or 755, which isn’t reviewed here.`,"patch-does-not-apply":`The patch doesn’t apply to this version, though pnpm may still install part of it.`,"patch-too-large":`The patch is too large to read here.`,"no-repository":`The repository the patch is in isn’t available to you.`,"no-directory":`Only some of the repository the patch is in is available to you.`,"github-token-required":`Reading the patch needs your GitHub sign-in.`,"patch-not-kept":`The patch isn’t kept here: a review of a version it patches keeps it, as does a team’s Dependencies tab of its repository’s default branch.`},wt=e=>e?{patchHash:e.hash,...e.repoId==null?{}:{patchRepoId:String(e.repoId),patchCommit:e.commit},...e.path==null?{}:{patchPath:e.path}}:{},O={...Ct,"bad-tarball":`This package's tarball couldn't be read.`,"tarball-conflict":`This package's tarball isn't shown, as it doesn't install as one set of files: it holds two different files at one path, or at paths that are one on macOS or Windows, or a file within another, which installers each install their own way.`,"upstream-invalid":`The npm registry's answer for this package couldn't be read.`,"upstream-too-large":`The npm registry's answer for this package is too large to read here.`,400:`Not an npm package name and version.`,404:`No such package version, or it is not available to you.`,413:`This package is too large to open here.`,429:`Too many packages are loading. Try again shortly.`,502:`The npm registry couldn't be reached.`},Tt=15e3,k=new Map;function Et(e){if(k.has(e))return;let t=new AbortController,n=l(e,{credentials:`same-origin`,signal:AbortSignal.any([t.signal,u.sessionController.signal])});n.catch(()=>{});let r={reading:n,until:Date.now()+Tt,generation:u.generation};k.set(e,r),setTimeout(()=>{k.get(e)===r&&(k.delete(e),t.abort())},Tt)}function Dt(e,t){let n=k.get(e);return n?(k.delete(e),n.until>Date.now()&&n.generation===t?n.reading:null):null}var Ot=(e,t)=>new Promise((n,r)=>{let i=()=>r(t.reason);t.aborted?i():(t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener(`abort`,i)))});async function A(e,t,n,r,i={}){r=T(r);let a=u.generation,o=()=>l(e,{credentials:`same-origin`,...i,signal:r}),s=i.method?null:Dt(e,a),c=s&&await Ot(s,r).then(e=>e.ok?e:null,e=>{if(r.aborted)throw e;return null})||await o();if(r.throwIfAborted(),!c.ok){let e=await c.json().catch(()=>null),n=e?.error??null;throw Object.assign(Error(t[n]??t[c.status]??`Request failed (${c.status})`),{status:c.status,code:n,...typeof e?.commit==`string`?{commit:e.commit}:{}})}let d=await n(c);if(r.throwIfAborted(),a!==u.generation)throw _t();return d}var j=(e,t,n)=>A(`/api/npm/${e}?${new URLSearchParams(t)}`,O,E,n),kt={"no-repository":`This repository is not available to you.`,"no-directory":`This directory is not at that commit, or not available to you.`,"directory-too-large":`This directory is too large to open here. Open one of its directories instead.`,"directory-unreadable":`GitHub’s archive of this directory couldn’t be read here, as when a symlink in it points outside the repository.`,"repository-busy":`Too many directories and packages are loading. Try again shortly.`,"repository-changed":`The repository changed while it was read. Try again.`,"github-rate-limited":`GitHub’s API rate limit has been reached. Try again later.`,"github-unauthorized":`GitHub authentication has expired or was revoked. Sign in again.`,"github-status-403":`GitHub denied this request. Check repository access and the GitHub App’s read permissions.`,"github-malformed":`GitHub’s archive of this directory could not be verified against its commit.`,"github-unreachable":`Could not connect to GitHub. Try again shortly.`,"github-moved":`GitHub moved this repository, as when it is renamed. Try again shortly.`,"github-timeout":`GitHub took too long to answer. Try again shortly.`,400:`Not a repository directory and commit.`,403:`Repository access is required to read its files.`,404:`This repository, commit or directory is unavailable.`,413:`This directory is too large to open here.`,429:`Too many directories and packages are loading. Try again shortly.`,502:`GitHub couldn’t be reached.`},M=(e,t,n,r=kt)=>A(`/api/admin/repositories/${e}?${new URLSearchParams(t)}`,r,E,n);function At(e,t,n,{signal:r}={}){return M(`code`,{repoId:e,ref:t,path:n},r)}async function jt({signal:e}={}){return(await M(`browsable`,{},e)).repos??[]}function Mt(e,{signal:t}={}){return M(`refs`,{repoId:e},t)}function Nt(e,t,n,{signal:r,commitOnly:i=!1}={}){return M(`contents`,{repoId:e,ref:t,path:n,...i?{listing:`none`}:{}},r)}var Pt={...kt,"no-directory":`This directory’s history is not available to you.`,"github-malformed":`GitHub answered with a history that couldn’t be read.`,"github-token-required":`Reading every branch needs your GitHub sign-in.`,400:`Not a repository’s history.`};function Ft(e,t,n,{page:r=1,all:i=!1,fresh:a=!1,from:o=null,signal:s}={}){return M(`history`,{repoId:e,ref:t,path:n,page:r,...i?{all:`true`}:{},...a?{fresh:`true`}:{},...o?{from:o.join(`,`)}:{}},s,Pt)}var It={...Pt,"no-directory":`This directory’s changes are not available to you.`,"github-malformed":`GitHub answered with a commit’s files that couldn’t be read.`,400:`Not a repository’s commits.`};function Lt(e,t,n,{signal:r}={}){return M(`changes`,{repoId:e,path:t,shas:n.join(`,`)},r,It)}function Rt(e,t,n,{signal:r}={}){return M(`tree`,{repoId:e,path:t,commit:n},r,It)}var N={...kt,"no-directory":`Issues and pull requests show only with access to the whole repository.`,"github-malformed":`GitHub answered with a list that couldn’t be read.`,"github-token-required":`Reading issues and pull requests needs your GitHub sign-in.`,"github-status-403":`GitHub refused to list these. The GitHub App reading this repository needs Issues: read and Pull requests: read, which an owner of its installation approves.`,400:`Not a repository’s issues or pull requests.`},zt=(e,t,n,r)=>`/api/admin/repositories/issues?${new URLSearchParams({repoId:e,kind:t,state:n,...r?{after:r}:{}})}`;function Bt(e,t,{state:n=`open`,after:r=null,signal:i}={}){return A(zt(e,t,n,r),N,E,i)}var Vt={...N,"no-directory":`Agents show only with access to the whole repository.`,"github-token-required":`Reading what the agents did needs your GitHub sign-in.`,400:`Not a repository’s agents.`},Ht=(e,t,n)=>`/api/admin/repositories/agents?${new URLSearchParams({repoId:e,...t?{pulls:t}:{},...n?{commits:n}:{}})}`;function Ut(e,{pulls:t=null,commits:n=null,signal:r}={}){return A(Ht(e,t,n),Vt,E,r)}var Wt={...N,"github-not-found":`GitHub has no issue or pull request of that number here.`,400:`Not an issue or pull request of a repository.`};function Gt(e,t,{signal:n}={}){return M(`item`,{repoId:e,number:t},n,Wt)}var Kt={...Wt,"github-not-found":`GitHub has no pull request of that number here.`,"github-malformed":`GitHub answered with a pull request or lockfile that couldn’t be read.`,"github-status-403":`GitHub refused to read its lockfiles. The GitHub App reading this repository needs Contents: read and Pull requests: read, which an owner of its installation approves.`,400:`Not a pull request of a repository.`},qt=({review:e,listed:t})=>({...e?{review:`1`}:{},...t?{listed:`1`}:{}});function Jt(e,t,{review:n=!1,listed:r=!1,signal:i}={}){return M(`pull-dependencies`,{repoId:e,number:t,...qt({review:n,listed:r})},i,Kt)}async function Yt(e,t,{review:n=!1,listed:r=!1,signal:i}={}){let{pulls:a,users:o,deltas:s}=await M(`pull-dependencies`,{repoId:e,numbers:t.join(`,`),...qt({review:n,listed:r})},i,Kt);return Xt(a,o,s)}var Xt=(e,t,n)=>new Map((Array.isArray(e)?e:[]).filter(e=>Number.isSafeInteger(e?.number)).map(e=>[e.number,typeof e.error==`string`?Object.assign(Error(Kt[e.error]??`It couldn\u2019t be read (${e.error}).`),{code:e.error}):{...e,...t?{users:t}:{},...Array.isArray(n)&&n.length>0?{deltas:n}:{}}])),Zt={...Wt,"github-not-found":`GitHub has none of a lockfile it lists on the default branch.`,"github-malformed":`GitHub answered with a lockfile that couldn’t be read.`,"github-status-403":`GitHub refused to read its lockfiles. The GitHub App reading this repository needs Contents: read, which an owner of its installation approves.`,400:`Not a repository.`},Qt={...Zt,"no-bundle":`This bundle is not available to you.`,"bundle-unavailable":`This bundle’s packages couldn’t be read.`,"directory-package-malformed":`This bundle records a package installed from a directory with an integrity, or naming no directory.`,"payload-too-large":`This bundle holds too many packages to check here.`,"repository-changed":`The bundle or its repository changed while it was read. Try again.`,"github-not-found":`GitHub has none of the commit this bundle was built from, or of a lockfile it lists there.`,400:`Not a bundle.`};function $t(e,{signal:t}={}){return A(`/api/bundles/${encodeURIComponent(e)}/dependency-review`,Qt,E,t)}var en={...Qt,"unsupported-bundle":`Only Stasis bundles are validated.`,"validation-busy":`Other bundles are being validated. Try again shortly.`,"validation-failed":`The validation failed. Try again.`,"csrf-missing":`Your session is missing its request token. Reload the page.`,"csrf-mismatch":`Your session changed. Reload the page.`,429:`Other bundles are being validated. Try again shortly.`},tn=e=>`/api/bundles/${encodeURIComponent(e)}/validation`;function nn(e,{signal:t}={}){return A(tn(e),en,E,t)}function rn(e,t,{signal:n}={}){return A(tn(e),en,e=>e.json().catch(()=>null),n,{method:`POST`,headers:{"x-csrf-token":t}})}var an={"no-team":`This team is not available to you.`,400:`Not a team’s repositories.`},on=`GitHub failed to answer. Try again shortly.`,sn={...N,"github-status-502":on,"github-status-504":on,"time-up":`Reading them took too long.`},cn=e=>`Not all its open pull requests were read. ${sn[e]??`(${e})`}`;function ln(e,t,{repoIds:n=null,signal:r}={}){let i=n?`?${new URLSearchParams({repoIds:n.join(`,`)})}`:``;return A(`/api/teams/${encodeURIComponent(e)}/dependencies${i}`,an,async e=>{for await(let n of On(e))t(typeof n.error==`string`?{...n,error:Zt[n.error]??Zt[n.status]??`It couldn\u2019t be read (${n.error}).`,code:n.error}:Array.isArray(n.dependencies)?{...n,dependencies:Xt(n.dependencies,n.users)}:typeof n.pulls?.error==`string`?{...n,pulls:{...n.pulls,error:cn(n.pulls.error)}}:n)},r)}function un(e,t,n,r,{signal:i}={}){let a=JSON.stringify({since:t,versions:n.map(({name:e,version:t})=>[e,t])});return A(`/api/teams/${encodeURIComponent(e)}/dependency-reviews/changed`,an,e=>e.json().then(e=>({now:Number.isSafeInteger(e?.now)?e.now:null,versions:Array.isArray(e?.versions)?e.versions.flatMap(e=>Array.isArray(e)&&typeof e[0]==`string`&&typeof e[1]==`string`?[{name:e[0],version:e[1]}]:[]):[]})),i,{method:`POST`,headers:{"content-type":`application/json`,"x-csrf-token":r},body:a})}var dn={...N,"no-directory":`Pulse shows only with access to the whole repository.`,"github-malformed":`GitHub answered with statistics that couldn’t be read.`,"github-token-required":`Reading a repository’s pulse needs your GitHub sign-in.`,"github-status-403":`GitHub refused to read these. The GitHub App reading this repository needs Contents, Issues and Pull requests: read, which an owner of its installation approves.`,400:`Not a repository’s pulse.`},fn=(e,t)=>`/api/admin/repositories/pulse?${new URLSearchParams({repoId:e,weeks:t})}`;function pn(e,t,{signal:n}={}){return A(fn(e,t),dn,E,n)}function mn(e,t,{state:n=`open`,weeks:r=4}={}){t===`issues`||t===`pulls`?Et(zt(e,t,n,null)):t===`agents`?Et(Ht(e,null,null)):t===`pulse`&&Et(fn(e,r))}function hn(e,t,{from:n,to:r=null,authors:i=[]},{signal:a}={}){return M(`pulse/items`,{repoId:e,weeks:t,from:n,...r===null?{}:{to:r},...i.length>0?{authors:i.join(`,`)}:{}},a,dn)}function gn(e,t,{signal:n,patch:r=null}={}){return j(`package`,{name:e,version:t,...wt(r)},n)}function _n(e,{signal:t}={}){return j(`versions`,{name:e},t)}function vn(e,{signal:t}={}){return j(`stats`,{name:e},t)}function yn(e,{signal:t}={}){return j(`advisories`,{name:e},t)}function bn(e,t,{signal:n}={}){return j(`tags`,{name:e,version:t},n)}function xn(e,t,{signal:n}={}){return j(`socket`,{name:e,version:t},n)}function Sn(e,t,n=null,{signal:r}={}){return j(`risk`,{name:e,version:t,...n===null?{}:{otherVersion:n}},r)}function Cn(e,t,{signal:n}={}){return j(`provenance`,{name:e,version:t},n)}var P={404:`This file is no longer available.`,409:`This file has changed since it was opened.`,413:`This file is too large to pretty-print.`,422:`This file couldn't be read as code.`,"pretty-mismatch":`Pretty-printing would change more than its layout, so it is shown as published.`,unsupported:`This kind of file can't be checked once pretty-printed, so it is shown as published.`,429:`Too many files are being pretty-printed. Try again shortly.`,502:`The npm registry couldn't be reached.`};function wn(e,t,n,{signal:r}={}){return A(`/api/bundles/${encodeURIComponent(e)}/pretty?${new URLSearchParams({path:t,hash:n})}`,P,En,r)}function Tn(e,t,n,r,{signal:i}={}){return A(`/api/npm/pretty?${new URLSearchParams({name:e,version:t,path:n,hash:r})}`,{...O,...P},En,i)}var En=async e=>({text:await e.text(),source:e.headers.get(`x-source-hash`)});async function*Dn(e){let t=e.body.pipeThrough(new TextDecoderStream).getReader(),n=[];for(;;){let{done:e,value:r}=await t.read();if(e)return;let i=0;for(let e=r.indexOf(`
1
+ import{b as e,d as t,i as n}from"./chunk-WB3NRZL7.js";import{a as r}from"./chunk-6VOB5WXX.js";import{A as i,B as a,a as o,b as s,c,d as l,e as u,f as d,g as ee,h as te,i as ne,j as re,k as ie,l as ae,m as oe,n as se,o as ce,p as le,q as ue,r as de,s as fe,t as pe,u as me,v as he,w as ge,x as _e,y as ve,z as ye}from"./chunk-Z54AXVCK.js";import"./chunk-6CCSTJWB.js";import{$a as be,H as xe,I as Se,Ka as Ce,Sa as we,Ta as Te,X as Ee,Ya as De,Za as Oe,a as ke,ab as Ae,bb as je,cb as Me,db as Ne,eb as f,fb as Pe,g as Fe,gb as p,hb as Ie,i as Le,ja as Re,ka as ze,m as Be,ma as Ve,n as m,z as He}from"./chunk-EMNIV37E.js";import{y as Ue}from"./chunk-OWIBDEJJ.js";import"./chunk-S5HSDGTP.js";import{b as We}from"./chunk-NRPC74AM.js";import"./chunk-PNHBZGDD.js";import{a as h,e as Ge}from"./chunk-74JZTGTO.js";import"./chunk-IYPY47MC.js";import{C as Ke,D as qe,d as g,h as Je,i as Ye,j as Xe,x as _,y as Ze}from"./chunk-ITUKKCCK.js";import{a as Qe,d as $e}from"./chunk-PWFUOLZK.js";import"./chunk-C4Z6ZBXV.js";import{m as et,r as tt}from"./chunk-XLX6XXJF.js";import{B as nt,D as rt,J as it}from"./chunk-QRKFPLA4.js";import{a as v,b as at,c as y,d as ot,g as b,j as st}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";function ct(e){let t=document.createElement(`input`);t.type=`file`,t.multiple=!0,t.addEventListener(`change`,()=>{e([...t.files])},{once:!0}),t.click()}function lt(e,t,n){let r=0,i=e=>Array.from(e.dataTransfer?.types??[]).includes(`Files`),a=e=>{i(e)&&(e.preventDefault(),r+=1,n(!0))},o=e=>{i(e)&&e.preventDefault()},s=e=>{i(e)&&(r=Math.max(0,r-1),r===0&&n(!1))},c=e=>{i(e)&&(e.preventDefault(),e.stopPropagation(),r=0,n(!1),t([...e.dataTransfer.files]))};return e.addEventListener(`dragenter`,a),e.addEventListener(`dragover`,o),e.addEventListener(`dragleave`,s),e.addEventListener(`drop`,c),()=>{e.removeEventListener(`dragenter`,a),e.removeEventListener(`dragover`,o),e.removeEventListener(`dragleave`,s),e.removeEventListener(`drop`,c)}}async function ut(e,t,n,r){let i=e.appState.generation;try{return await e.appState.mutate(()=>n(t),r)}catch(t){throw i===e.appState.generation&&e.appState.invalidate(r),t}}async function dt(e,t,n,r){if(e._busy||!e._csrf)throw Error(`Wait for the current operation to finish, then try again.`);e._busy=!0;try{await ut(e,t,n,r)}finally{await e._load(),e._busy=!1;let t=e._queue.splice(0);t.length>0&&e._upload(t)}}async function ft(e,t,n,r){if(t.length===0||(e._queue.push(...t),e._busy))return;e._busy=!0,e._error=null;let i=e.appState.generation,a=[],o=0;try{for(;e._queue.length>0;){if(e.appState.generation!==i){e._queue=[];break}let t=e._queue.shift();try{await ut(e,t,n,r)}catch(n){if(n?.name===`AbortError`||e.appState.generation!==i){e._queue=[];break}a.push(`${t.name}: ${String(n?.message??n)}`)}o++}}finally{a.length>0&&(e._error=o===1?`Upload failed: ${a[0]}`:`Upload failed for ${a.length} of ${o} files: ${a.join(`; `)}`),e._busy=!1,await e._load({preserveError:!0})}}var x=class extends st{static properties={session:{attribute:!1},allowShare:{attribute:!1},_loading:{state:!0},_data:{state:!0},_error:{state:!0}};constructor(){super(),this.session=null,this.allowShare=!1,this.appState=u,this._loading=!1,this._loadRequest=null,this._data=null,this._error=null}get _role(){return this.session?.role??null}get _csrf(){return this.session?.csrfToken??null}get _me(){return this.session?.id??null}connectedCallback(){super.connectedCallback(),this._load()}disconnectedCallback(){this._loadRequest?.abort(),super.disconnectedCallback()}async _load({preserveError:e=!1}={}){let{collection:t}=this.constructor;if(!t)return;e||(this._error=null);let[n,r,i]=t;await this._loadCollection(n,r,i,e=>this._show(e))}_show(e){this._data=e}async _loadCollection(e,t,n,r){this._loading=!0,await this._read(`_loadRequest`,e,t,n,{apply:r,settled:()=>{this._loading=!1},failed:t=>{this.appState.read(e)===void 0&&(this._error=String(t?.message??t))}})}async _read(e,t,n,r,{apply:i,answered:a,failed:o,settled:s}){this[e]?.abort();let c=this[e]=new AbortController;try{await this.appState.load(t,n,r,{signal:c.signal,apply:i}),c.signal.aborted||a?.()}catch(e){!c.signal.aborted&&e?.name!==`AbortError`&&o(e)}finally{this[e]===c&&s()}}_nav(){return Pe(this.constructor.view,this._role,this.allowShare)}_emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}_list(e,t,n){return y`<div class="manage-list" aria-busy="${this._loading}">${e==null?this._error?b:S(t):n()}</div>`}},pt=class{constructor(e,t=()=>!0){this.host=e,this.accepts=t,this.active=!1,e.addController(this)}hostConnected(){this.teardown=lt(this.host,e=>{this.accepts()&&this.host._upload(e)},e=>{this.active=this.accepts()&&e,this.host.requestUpdate()})}hostDisconnected(){this.teardown?.()}overlay(e){return this.active?y`<div class="dropzone">${e}</div>`:b}card(e,t,n,r=`Uploading…`){return y`<span class="drop-icon" aria-hidden="true">${p(`upload`)}</span><span class="drop-copy"><strong>${e}</strong><span>${t}</span></span><button type="button" class="drop-browse" ?disabled="${n}" @click="${()=>ct(e=>{this.host._upload(e)})}">${this.host._busy?r:`Browse files`}</button>`}};function S(e){return y`<div class="loading-rows" role="status"><span class="sr-only">${e}</span><div aria-hidden="true">${[0,1,2,3].map(()=>y`<div class="loading-row"><span></span><span></span></div>`)}</div></div>`}var C=e=>e?y`<p class="msg error" role="alert">${e}</p>`:b,w=(e,t)=>y`<div class="empty"><strong>${e}</strong><p>${t}</p></div>`;function mt(e){let t=e.split(`/`);return t.at(-1)===`stasis.config.json`&&!t.includes(`node_modules`)}var ht=class extends Te{get changeEvent(){return`local-item-change`}get searchLabel(){return`Search local files`}get optionsLabel(){return`Local files`}get noMatchesLabel(){return`No matching files.`}get emptyLabel(){return`No local files available.`}choices(){let e=this._query.trim().toLocaleLowerCase(),t=this.options.filter(t=>`${t.label} ${t.secondary??``}`.toLocaleLowerCase().includes(e));return{pinned:[],sections:[{options:t}],count:t.length,total:this.options.length,showFacets:!1}}};customElements.define(`managed-local-item-selector`,ht);var gt=class{constructor(e,t,n){this.host=e,this.kind=t,this.upload=n,this.source=null,this.hasData=!1,this.open=!1,this.options=[],this.value=null,this.busy=!1,this.loading=!1,this.error=``,this.success=``,this.generation=0,this.readAbort=null,this.onChange=e=>{if(e?.kind){if(e.kind!==this.kind)return;if(e.value!==this.value){this.refresh();return}}this.readAbort&&!this.readAbort.signal.aborted&&(this.readAbort.abort(),this.error=`The local ${this.kind} changed or the list was refreshed. Select it again before importing.`),this.options=[],this.value=null,this.success=``,this.refresh()},this.onBlur=()=>{this.readAbort&&!this.readAbort.signal.aborted&&this.onChange()},this.onVisibilityChange=()=>{globalThis.document?.visibilityState===`hidden`&&this.onBlur()},e.addController(this)}listeners(){return[[globalThis,`focus`,this.onChange],[globalThis,`blur`,this.onBlur],[globalThis,`storage`,this.onChange],[globalThis.document,`visibilitychange`,this.onVisibilityChange]]}hostConnected(){for(let[e,t,n]of this.listeners())e?.addEventListener(t,n);this.connectSource()}hostUpdated(){this.connectSource()}connectSource(){this.source!==this.host.localImportSource&&(this.unsubscribe?.(),this.abort?.abort(),this.source=this.host.localImportSource,this.unsubscribe=this.source?.subscribe(this.onChange),this.onChange())}hostDisconnected(){++this.generation,this.abort?.abort(),this.unsubscribe?.(),this.source=null;for(let[e,t,n]of this.listeners())e?.removeEventListener(t,n)}async refresh(){let e=++this.generation,t=this.source;this.loading=!0,this.host.requestUpdate();try{let n=t?await t.hasData(this.kind):!1;if(e!==this.generation)return;this.hasData=n;let r=this.open&&!t?.locked?await t?.list(this.kind)??[]:[];if(e!==this.generation)return;this.options=r,r.some(e=>e.value===this.value)||(this.value=null)}catch(t){e===this.generation&&(this.error=String(t?.message??t))}finally{e===this.generation&&(this.loading=!1,this.host.requestUpdate())}}toggle(){this.busy||(this.open=!this.open,this.error=``,this.success=``,this.options=[],this.value=null,this.refresh())}async busyWith(e){let t=this.abort=new AbortController;this.busy=!0,this.error=``,this.host.requestUpdate();try{await e(t)}catch(e){t.signal.aborted||(this.error=String(e?.message??e))}finally{this.readAbort===t&&(this.readAbort=null),this.busy=!1,this.host.requestUpdate()}}async unlock(){this.busy||await this.busyWith(async e=>{await this.source.unlock({signal:e.signal})&&!e.signal.aborted&&await this.refresh()})}async importSelected(){if(this.busy||this.loading||!this.value||this.source?.locked)return;this.success=``;let e=this.options.find(e=>e.value===this.value)?.label;await this.busyWith(async t=>{this.readAbort=t,await this.source.importItem(this.kind,this.value,e=>(this.readAbort=null,this.upload(e)),{signal:t.signal}),!t.signal.aborted&&!this.source?.locked&&(this.success=`Imported ${e}.`,this.value=null)})}renderAction(){return this.hasData||this.open?y`<button type="button" class="local-import-toggle" aria-expanded="${this.open}" aria-controls="local-import-panel" ?disabled="${this.busy}" @click="${()=>this.toggle()}">Import</button>`:b}renderPanel(e){if(!this.open)return b;let t=this.source?.locked;return y`<section class="local-import-panel" id="local-import-panel" aria-label="${`Import local ${this.kind}`}"><div class="local-import-copy"><strong>Import local ${this.kind}</strong><p>${t?`Unlock local data with your passkey to choose a file.`:`Copy a file from this browser to the managed workspace. The local copy stays on this device.`}</p></div><div class="local-import-controls">${t?y`<button type="button" class="local-import-submit" ?disabled="${this.busy}" @click="${()=>this.unlock()}">${this.busy?`Waiting for passkey…`:`Unlock with passkey`}</button>`:y`<managed-local-item-selector label="${`Choose local ${this.kind}`}" placeholder="${this.loading?`Loading local files…`:`Choose local ${this.kind}\u2026`}" .options="${this.options}" .value="${this.value}" ?disabled="${this.busy||this.loading}" @local-item-change="${e=>{this.value=e.detail.value,this.success=``,this.host.requestUpdate()}}"></managed-local-item-selector><button type="button" class="local-import-submit" ?disabled="${e||this.busy||this.loading||!this.value}" @click="${()=>this.importSelected()}">${this.busy?`Importing…`:`Import ${this.kind}`}</button>`} <button type="button" class="local-import-close" ?disabled="${this.busy}" @click="${()=>this.toggle()}">Close</button></div>${!t&&!this.loading&&this.options.length===0?y`<p class="local-import-message">No local ${this.kind}s available.</p>`:b} ${this.error?y`<p class="local-import-message error" role="alert">${this.error} <button type="button" ?disabled="${this.busy}" @click="${()=>{this.error=``,this.refresh()}}">Retry</button></p>`:b} ${this.success?y`<p class="local-import-message" role="status">${this.success}</p>`:b}</section>`}},T=e=>e?AbortSignal.any([e,u.sessionController.signal]):u.sessionController.signal,_t=()=>new DOMException(`Managed session changed`,`AbortError`),E=e=>e.json();async function vt({signal:e}={}){e=T(e),e.throwIfAborted();let t=await l(`/api/admin/bundles`,{credentials:`same-origin`,signal:e});if(e.throwIfAborted(),!t.ok)throw Object.assign(Error(`Bundle catalogue request failed (${t.status})`),{status:t.status});let n=await t.json();return e.throwIfAborted(),n.bundles??[]}async function D(e,t,n){let r=u.generation,i=await l(`/api/bundles/${encodeURIComponent(e)}/${t}`,{credentials:`same-origin`,signal:n});if(n?.throwIfAborted(),!i.ok)throw Object.assign(Error(`Bundle ${t} request failed (${i.status})`),{status:i.status});let a=t===`contents`?await i.text():await i.json();if(n?.throwIfAborted(),r!==u.generation)throw _t();return a}function yt(e,{signal:t}={}){return u.load(`bundle-metadata:${e}`,`bundle metadata`,t=>D(e,`metadata`,t),{signal:t,retryInvalidated:!0})}async function bt(e,{signal:t}={}){t=T(t);let n=await D(e,`metadata`,t),r=n?.bundle?.repo??null,i=rt({repo:r});if(!i)return r;let a=new URLSearchParams({repo:i,directory:r.directory??``}),o=new Set(n.unsized??[]),s=We((n.files??[]).filter(([e,t])=>t!=null||o.has(e)).map(([e])=>e));s&&a.set(`filePrefix`,s);let c=await l(`/api/admin/repositories/resolve?${a}`,{credentials:`same-origin`,cache:`no-store`,signal:t});if(t.throwIfAborted(),!c.ok)throw Error(`Repository suggestion request failed (${c.status})`);let{location:u}=await c.json();return t.throwIfAborted(),u?{...r,github:u.github,...u.mapped?{directory:u.directory}:{},repoId:u.repoId}:r}async function xt(e,{signal:t}={}){t=T(t);try{return await D(e,`contents`,t)}catch(e){throw e.name!==`AbortError`&&u.notify(`Couldn't load bundle contents: ${e.message}`),e}}function St(e,t,n=``,r=!1,i=!1){let a=n?`${n.startsWith(`entry:`)?`entry`:`reason`}=${encodeURIComponent(n.slice(n.indexOf(`:`)+1))}`:``,o=[t?`team=${encodeURIComponent(t)}`:``,a,r?`repoAdvisories=true`:``,i?`details=true`:``].filter(Boolean).join(`&`);return D(e,`advisories${o?`?${o}`:``}`,u.sessionController.signal)}var Ct={"patch-not-found":`The patch isn’t at the commit it was looked for at.`,"patch-mismatch":`The file at the commit the patch was read at isn’t the patch its lockfile names.`,"patch-unreadable":`The patch isn’t written as git writes one, so pnpm versions may apply it differently.`,"patch-unsupported":`The patch changes a file’s bytes, or gives it a mode other than 644 or 755, which isn’t reviewed here.`,"patch-does-not-apply":`The patch doesn’t apply to this version, though pnpm may still install part of it.`,"patch-too-large":`The patch is too large to read here.`,"no-repository":`The repository the patch is in isn’t available to you.`,"no-directory":`Only some of the repository the patch is in is available to you.`,"github-token-required":`Reading the patch needs your GitHub sign-in.`,"patch-not-kept":`The patch isn’t kept here: a review of a version it patches keeps it, as does a team’s Dependencies tab of its repository’s default branch.`},wt=e=>e?{patchHash:e.hash,...e.repoId==null?{}:{patchRepoId:String(e.repoId),patchCommit:e.commit},...e.path==null?{}:{patchPath:e.path}}:{},O={...Ct,"bad-tarball":`This package's tarball couldn't be read.`,"tarball-conflict":`This package's tarball isn't shown, as it doesn't install as one set of files: it holds two different files at one path, or at paths that are one on macOS or Windows, or a file within another, which installers each install their own way.`,"upstream-invalid":`The npm registry's answer for this package couldn't be read.`,"upstream-too-large":`The npm registry's answer for this package is too large to read here.`,400:`Not an npm package name and version.`,404:`No such package version, or it is not available to you.`,413:`This package is too large to open here.`,429:`Too many packages are loading. Try again shortly.`,502:`The npm registry couldn't be reached.`},Tt=15e3,k=new Map;function Et(e){if(k.has(e))return;let t=new AbortController,n=l(e,{credentials:`same-origin`,signal:AbortSignal.any([t.signal,u.sessionController.signal])});n.catch(()=>{});let r={reading:n,until:Date.now()+Tt,generation:u.generation};k.set(e,r),setTimeout(()=>{k.get(e)===r&&(k.delete(e),t.abort())},Tt)}function Dt(e,t){let n=k.get(e);return n?(k.delete(e),n.until>Date.now()&&n.generation===t?n.reading:null):null}var Ot=(e,t)=>new Promise((n,r)=>{let i=()=>r(t.reason);t.aborted?i():(t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener(`abort`,i)))});async function A(e,t,n,r,i={}){r=T(r);let a=u.generation,o=()=>l(e,{credentials:`same-origin`,...i,signal:r}),s=i.method?null:Dt(e,a),c=s&&await Ot(s,r).then(e=>e.ok?e:null,e=>{if(r.aborted)throw e;return null})||await o();if(r.throwIfAborted(),!c.ok){let e=await c.json().catch(()=>null),n=e?.error??null;throw Object.assign(Error(t[n]??t[c.status]??`Request failed (${c.status})`),{status:c.status,code:n,...typeof e?.commit==`string`?{commit:e.commit}:{}})}let d=await n(c);if(r.throwIfAborted(),a!==u.generation)throw _t();return d}var j=(e,t,n)=>A(`/api/npm/${e}?${new URLSearchParams(t)}`,O,E,n),kt={"no-repository":`This repository is not available to you.`,"no-directory":`This directory is not at that commit, or not available to you.`,"directory-too-large":`This directory is too large to open here. Open one of its directories instead.`,"directory-unreadable":`GitHub’s archive of this directory couldn’t be read here, as when a symlink in it points outside the repository.`,"repository-busy":`Too many directories and packages are loading. Try again shortly.`,"repository-changed":`The repository changed while it was read. Try again.`,"github-rate-limited":`GitHub’s API rate limit has been reached. Try again later.`,"github-unauthorized":`GitHub authentication has expired or was revoked. Sign in again.`,"github-status-403":`GitHub denied this request. Check repository access and the GitHub App’s read permissions.`,"github-malformed":`GitHub’s archive of this directory could not be verified against its commit.`,"github-unreachable":`Could not connect to GitHub. Try again shortly.`,"github-moved":`GitHub moved this repository, as when it is renamed. Try again shortly.`,"github-timeout":`GitHub took too long to answer. Try again shortly.`,400:`Not a repository directory and commit.`,403:`Repository access is required to read its files.`,404:`This repository, commit or directory is unavailable.`,413:`This directory is too large to open here.`,429:`Too many directories and packages are loading. Try again shortly.`,502:`GitHub couldn’t be reached.`},M=(e,t,n,r=kt)=>A(`/api/admin/repositories/${e}?${new URLSearchParams(t)}`,r,E,n);function At(e,t,n,{signal:r}={}){return M(`code`,{repoId:e,ref:t,path:n},r)}async function jt({signal:e}={}){return(await M(`browsable`,{},e)).repos??[]}function Mt(e,{signal:t}={}){return M(`refs`,{repoId:e},t)}function Nt(e,t,n,{signal:r,commitOnly:i=!1}={}){return M(`contents`,{repoId:e,ref:t,path:n,...i?{listing:`none`}:{}},r)}var Pt={...kt,"no-directory":`This directory’s history is not available to you.`,"github-malformed":`GitHub answered with a history that couldn’t be read.`,"github-token-required":`Reading every branch needs your GitHub sign-in.`,400:`Not a repository’s history.`};function Ft(e,t,n,{page:r=1,all:i=!1,fresh:a=!1,from:o=null,signal:s}={}){return M(`history`,{repoId:e,ref:t,path:n,page:r,...i?{all:`true`}:{},...a?{fresh:`true`}:{},...o?{from:o.join(`,`)}:{}},s,Pt)}var It={...Pt,"no-directory":`This directory’s changes are not available to you.`,"github-malformed":`GitHub answered with a commit’s files that couldn’t be read.`,400:`Not a repository’s commits.`};function Lt(e,t,n,{signal:r}={}){return M(`changes`,{repoId:e,path:t,shas:n.join(`,`)},r,It)}function Rt(e,t,n,{signal:r}={}){return M(`tree`,{repoId:e,path:t,commit:n},r,It)}var N={...kt,"no-directory":`Issues and pull requests show only with access to the whole repository.`,"github-malformed":`GitHub answered with a list that couldn’t be read.`,"github-token-required":`Reading issues and pull requests needs your GitHub sign-in.`,"github-status-403":`GitHub refused to list these. The GitHub App reading this repository needs Issues: read and Pull requests: read, which an owner of its installation approves.`,400:`Not a repository’s issues or pull requests.`},zt=(e,t,n,r)=>`/api/admin/repositories/issues?${new URLSearchParams({repoId:e,kind:t,state:n,...r?{after:r}:{}})}`;function Bt(e,t,{state:n=`open`,after:r=null,signal:i}={}){return A(zt(e,t,n,r),N,E,i)}var Vt={...N,"no-directory":`Agents show only with access to the whole repository.`,"github-token-required":`Reading what the agents did needs your GitHub sign-in.`,400:`Not a repository’s agents.`},Ht=(e,t,n)=>`/api/admin/repositories/agents?${new URLSearchParams({repoId:e,...t?{pulls:t}:{},...n?{commits:n}:{}})}`;function Ut(e,{pulls:t=null,commits:n=null,signal:r}={}){return A(Ht(e,t,n),Vt,E,r)}var Wt={...N,"github-not-found":`GitHub has no issue or pull request of that number here.`,400:`Not an issue or pull request of a repository.`};function Gt(e,t,{signal:n}={}){return M(`item`,{repoId:e,number:t},n,Wt)}var Kt={...Wt,"github-not-found":`GitHub has no pull request of that number here.`,"github-malformed":`GitHub answered with a pull request or lockfile that couldn’t be read.`,"github-status-403":`GitHub refused to read its lockfiles. The GitHub App reading this repository needs Contents: read and Pull requests: read, which an owner of its installation approves.`,400:`Not a pull request of a repository.`},qt=({review:e,listed:t})=>({...e?{review:`1`}:{},...t?{listed:`1`}:{}});function Jt(e,t,{review:n=!1,listed:r=!1,signal:i}={}){return M(`pull-dependencies`,{repoId:e,number:t,...qt({review:n,listed:r})},i,Kt)}async function Yt(e,t,{review:n=!1,listed:r=!1,signal:i}={}){let{pulls:a,users:o,deltas:s}=await M(`pull-dependencies`,{repoId:e,numbers:t.join(`,`),...qt({review:n,listed:r})},i,Kt);return Xt(a,o,s)}var Xt=(e,t,n)=>new Map((Array.isArray(e)?e:[]).filter(e=>Number.isSafeInteger(e?.number)).map(e=>[e.number,typeof e.error==`string`?Object.assign(Error(Kt[e.error]??`It couldn\u2019t be read (${e.error}).`),{code:e.error}):{...e,...t?{users:t}:{},...Array.isArray(n)&&n.length>0?{deltas:n}:{}}])),Zt={...Wt,"github-not-found":`GitHub has none of a lockfile it lists on the default branch.`,"github-malformed":`GitHub answered with a lockfile that couldn’t be read.`,"github-status-403":`GitHub refused to read its lockfiles. The GitHub App reading this repository needs Contents: read, which an owner of its installation approves.`,400:`Not a repository.`},Qt={...Zt,"no-bundle":`This bundle is not available to you.`,"bundle-unavailable":`This bundle’s packages couldn’t be read.`,"directory-package-malformed":`This bundle records a package installed from a directory with an integrity, or naming no directory.`,"payload-too-large":`This bundle holds too many packages to check here.`,"repository-changed":`The bundle or its repository changed while it was read. Try again.`,"github-not-found":`GitHub has none of the commit this bundle was built from, or of a lockfile it lists there.`,400:`Not a bundle.`};function $t(e,{signal:t}={}){return A(`/api/bundles/${encodeURIComponent(e)}/dependency-review`,Qt,E,t)}var en={...Qt,"unsupported-bundle":`Only Stasis bundles are validated.`,"validation-busy":`Other bundles are being validated. Try again shortly.`,"validation-failed":`The validation failed. Try again.`,"csrf-missing":`Your session is missing its request token. Reload the page.`,"csrf-mismatch":`Your session changed. Reload the page.`,429:`Other bundles are being validated. Try again shortly.`},tn=e=>`/api/bundles/${encodeURIComponent(e)}/validation`;function nn(e,{signal:t}={}){return A(tn(e),en,E,t)}function rn(e,t,{signal:n}={}){return A(tn(e),en,e=>e.json().catch(()=>null),n,{method:`POST`,headers:{"x-csrf-token":t}})}var an={"no-team":`This team is not available to you.`,400:`Not a team’s repositories.`},on=`GitHub failed to answer. Try again shortly.`,sn={...N,"github-status-502":on,"github-status-504":on,"time-up":`Reading them took too long.`},cn=e=>`Not all its open pull requests were read. ${sn[e]??`(${e})`}`;function ln(e,t,{repoIds:n=null,kept:r=!1,signal:i}={}){let a=new URLSearchParams({...n?{repoIds:n.join(`,`)}:{},...r?{kept:`1`}:{}}),o=a.size>0?`?${a}`:``;return A(`/api/teams/${encodeURIComponent(e)}/dependencies${o}`,an,async e=>{for await(let n of On(e))typeof n.error==`string`?t({...n,error:Zt[n.error]??Zt[n.status]??`It couldn\u2019t be read (${n.error}).`,code:n.error}):t({...n,...Array.isArray(n.dependencies)?{dependencies:Xt(n.dependencies,n.users)}:{},...typeof n.pulls?.error==`string`?{pulls:{...n.pulls,error:cn(n.pulls.error)}}:{}})},i)}function un(e,t,n,r,{signal:i}={}){let a=JSON.stringify({since:t,versions:n.map(({name:e,version:t})=>[e,t])});return A(`/api/teams/${encodeURIComponent(e)}/dependency-reviews/changed`,an,e=>e.json().then(e=>({now:Number.isSafeInteger(e?.now)?e.now:null,versions:Array.isArray(e?.versions)?e.versions.flatMap(e=>Array.isArray(e)&&typeof e[0]==`string`&&typeof e[1]==`string`?[{name:e[0],version:e[1]}]:[]):[]})),i,{method:`POST`,headers:{"content-type":`application/json`,"x-csrf-token":r},body:a})}var dn={...N,"no-directory":`Pulse shows only with access to the whole repository.`,"github-malformed":`GitHub answered with statistics that couldn’t be read.`,"github-token-required":`Reading a repository’s pulse needs your GitHub sign-in.`,"github-status-403":`GitHub refused to read these. The GitHub App reading this repository needs Contents, Issues and Pull requests: read, which an owner of its installation approves.`,400:`Not a repository’s pulse.`},fn=(e,t)=>`/api/admin/repositories/pulse?${new URLSearchParams({repoId:e,weeks:t})}`;function pn(e,t,{signal:n}={}){return A(fn(e,t),dn,E,n)}function mn(e,t,{state:n=`open`,weeks:r=4}={}){t===`issues`||t===`pulls`?Et(zt(e,t,n,null)):t===`agents`?Et(Ht(e,null,null)):t===`pulse`&&Et(fn(e,r))}function hn(e,t,{from:n,to:r=null,authors:i=[]},{signal:a}={}){return M(`pulse/items`,{repoId:e,weeks:t,from:n,...r===null?{}:{to:r},...i.length>0?{authors:i.join(`,`)}:{}},a,dn)}function gn(e,t,{signal:n,patch:r=null}={}){return j(`package`,{name:e,version:t,...wt(r)},n)}function _n(e,{signal:t}={}){return j(`versions`,{name:e},t)}function vn(e,{signal:t}={}){return j(`stats`,{name:e},t)}function yn(e,{signal:t}={}){return j(`advisories`,{name:e},t)}function bn(e,t,{signal:n}={}){return j(`tags`,{name:e,version:t},n)}function xn(e,t,{signal:n}={}){return j(`socket`,{name:e,version:t},n)}function Sn(e,t,n=null,{signal:r}={}){return j(`risk`,{name:e,version:t,...n===null?{}:{otherVersion:n}},r)}function Cn(e,t,{signal:n}={}){return j(`provenance`,{name:e,version:t},n)}var P={404:`This file is no longer available.`,409:`This file has changed since it was opened.`,413:`This file is too large to pretty-print.`,422:`This file couldn't be read as code.`,"pretty-mismatch":`Pretty-printing would change more than its layout, so it is shown as published.`,unsupported:`This kind of file can't be checked once pretty-printed, so it is shown as published.`,429:`Too many files are being pretty-printed. Try again shortly.`,502:`The npm registry couldn't be reached.`};function wn(e,t,n,{signal:r}={}){return A(`/api/bundles/${encodeURIComponent(e)}/pretty?${new URLSearchParams({path:t,hash:n})}`,P,En,r)}function Tn(e,t,n,r,{signal:i}={}){return A(`/api/npm/pretty?${new URLSearchParams({name:e,version:t,path:n,hash:r})}`,{...O,...P},En,i)}var En=async e=>({...await e.json(),source:e.headers.get(`x-source-hash`)});async function*Dn(e){let t=e.body.pipeThrough(new TextDecoderStream).getReader(),n=[];for(;;){let{done:e,value:r}=await t.read();if(e)return;let i=0;for(let e=r.indexOf(`
2
2
  `);e!==-1;i=e+1,e=r.indexOf(`
3
3
  `,i))n.push(r.slice(i,e)),yield JSON.parse(n.join(``)),n=[];n.push(r.slice(i))}}async function*On(e){let t=u.generation;for await(let n of Dn(e)){if(t!==u.generation)throw _t();yield n}}function kn(e,t,n,{signal:r}={}){return F(`/api/npm/pretty?${new URLSearchParams({name:e,version:t})}`,O,n,r)}function An(e,t,n,{signal:r}={}){return F(`/api/bundles/${encodeURIComponent(e)}/pretty?${new URLSearchParams({other:t})}`,P,n,r)}function jn(e,t,n,r,{signal:i}={}){return F(`/api/npm/pretty?${new URLSearchParams({name:e,version:t,otherVersion:n})}`,O,r,i)}function F(e,t,n,r,i=P){return A(e,t,async e=>{for await(let{error:t,status:r,...a}of On(e))await n(t?{...a,status:r,message:i[t]??i[r]??`Request failed (${r})`}:a)},r)}var Mn={...P,413:`This file is too large to compare with renamed names hidden.`,422:`This file couldn't be compared as code.`,"diff-busy":`Too many files are being compared. Try again shortly.`,504:`Comparing this file took too long.`},Nn=(e,t)=>A(e,Mn,E,t);function Pn(e,t,{path:n,hash:r,otherPath:i,otherHash:a},{signal:o}={}){return Nn(`/api/bundles/${encodeURIComponent(e)}/rename-diff?${new URLSearchParams({path:n,hash:r,other:t,otherPath:i,otherHash:a})}`,o)}function Fn(e,t,n,{path:r,hash:i,otherPath:a,otherHash:o},{signal:s}={}){return Nn(`/api/npm/rename-diff?${new URLSearchParams({name:e,version:t,path:r,hash:i,otherVersion:n,otherPath:a,otherHash:o})}`,s)}var In=(e,t)=>new URLSearchParams({other:e,...t?{scope:t}:{}});function Ln(e,t,n,{signal:r,scope:i=``}={}){return F(`/api/bundles/${encodeURIComponent(e)}/rename-diff?${In(t,i)}`,P,n,r,Mn)}function Rn(e,t,n,r,{signal:i}={}){return F(`/api/npm/rename-diff?${new URLSearchParams({name:e,version:t,otherVersion:n})}`,O,r,i,Mn)}function zn(e,t,n,{signal:r,scope:i=``}={}){return F(`/api/bundles/${encodeURIComponent(e)}/type-only?${In(t,i)}&runs=1`,P,n,r)}function Bn(e,t,n,r,{signal:i}={}){return F(`/api/npm/type-only?${new URLSearchParams({name:e,version:t,otherVersion:n,runs:`1`})}`,O,r,i)}var Vn={...O,"delta-busy":`Too many packages are being counted. Try again shortly.`,"delta-timeout":`Counting its lines took too long.`,"delta-failed":`Its lines couldn’t be counted.`};function Hn(e,t,{signal:n}={}){return A(`/api/npm/deltas?${new URLSearchParams({versions:JSON.stringify(e)})}`,Vn,async e=>{for await(let{error:n,status:r,...i}of On(e))t(n?{...i,error:Vn[n]??Vn[r]??`Request failed (${r})`}:i)},n)}var Un={404:`This bundle is no longer available.`,422:`This bundle couldn't be read.`,429:`Too many bundles are being compared. Try again shortly.`},Wn=async e=>{let t=await e.json();return t.files.basePaths=new Map(t.files.basePaths),t};function Gn(e,t,{signal:n,scope:r=``}={}){return A(`/api/bundles/${encodeURIComponent(e)}/comparison?${In(t,r)}`,Un,Wn,n)}function Kn(e,t,n,{signal:r,otherName:i=e,patch:a=null,otherPatch:o=null}={}){return A(`/api/npm/comparison?${new URLSearchParams({name:e,version:t,otherVersion:n,...i===e?{}:{otherName:i},...wt(a),...o?{otherPatchHash:o.hash}:{}})}`,O,Wn,r)}async function I(e,t){let n=await l(e,{signal:t,credentials:`same-origin`,headers:{accept:`application/json`}});if(!n.ok)throw Error(`HTTP ${n.status}`);return n.json()}function L(e,t,n,{signal:r,token:i=!!t}={}){let a={"content-type":`application/json`};return i&&(a[`x-csrf-token`]=t),l(e,{method:`POST`,credentials:`same-origin`,...r?{signal:r}:{},headers:a,body:JSON.stringify(n)})}async function R(e,t,n){let r=await L(e,t,n);if(!r.ok)throw Error(`HTTP ${r.status}`);return r}function qn(e,t){return async(n=``,r={})=>{let i=await l(`${e}${n}`,{credentials:`same-origin`,...r}),a=await i.json();if(!i.ok)throw Error(t[a?.error]??`HTTP ${i.status}`);return a}}async function Jn(e){let t=await e.json().then(e=>typeof e?.error==`string`?e.error:``,()=>``);return[`repo-forbidden`,`forbidden`].includes(t)?`choose a repository and directory within your team access`:`HTTP 403${t?`: ${t}`:``}`}async function Yn(e,t,n){let r=n?{"x-csrf-token":n}:{},i=await l(`/api/admin/${e}/${encodeURIComponent(t)}`,{method:`DELETE`,credentials:`same-origin`,headers:r});if(!i.ok)throw Error(`HTTP ${i.status}`)}function Xn(e,t,n,r){let i={"content-type":r,[`x-${e}-filename`]:encodeURIComponent(t.name)};return n&&(i[`x-csrf-token`]=n),l(`/api/admin/${e}s`,{method:`POST`,credentials:`same-origin`,headers:i,body:t})}async function Zn(e,t,n,r,i,a){let o=new URLSearchParams({page:String(t),limit:`100`,kind:n,q:r.trim()});i&&o.set(`repo`,i),a&&o.set(`actor`,a);let s=await I(`/api/admin/history?${o}`,e);if(!Array.isArray(s?.history)||!Number.isSafeInteger(s.total)||s.total<0||!Number.isSafeInteger(s.page)||s.page<1)throw Error(`No history returned`);return s}async function Qn(e){let t=await I(`/api/admin/users`,e);return Array.isArray(t?.users)?t.users:[]}async function $n(e,t,n){await R(`/api/admin/set-role`,n,{userId:e,role:t})}function er(e,t,n,r){let i=new URLSearchParams({scope:e});return e===`installed`&&i.set(`showAll`,String(t)),n&&i.set(`refresh`,`true`),I(`/api/admin/repositories?${i}`,r)}async function tr(e,t,n){await R(`/api/admin/repositories/select`,n,{repoId:e,selected:t})}async function nr(e,{enabled:t,required:n,since:r,lockfiles:i},a){let o=await L(`/api/admin/repositories/dependency-review`,a,{repoId:e,enabled:t,required:n,since:r,...i?{lockfiles:i}:{}});if(!o.ok)throw Error(o.status===400?`Enter 1 to 10 required reviews, the commit as its full 40-character id, and at most 100 lockfiles by their paths in the repository; a stasis.config.json only among those reviewed alone.`:`HTTP ${o.status}`);return(await o.json()).dependencyReview}async function rr(e,t){let n=await I(`/api/admin/repositories/lockfiles?repoId=${encodeURIComponent(e)}`,t);return{paths:Array.isArray(n?.lockfiles)?n.lockfiles.flatMap(e=>typeof e?.path==`string`?[e.path]:[]):[],configs:Array.isArray(n?.configs)?n.configs.filter(e=>typeof e==`string`):[]}}var ir={400:`Enter a repository as owner/repo or a GitHub repository URL.`,403:`You do not have permission to add arbitrary public repositories.`,404:`No public repository was found at that address.`,409:`Choose a public, non-archived repository.`};async function ar(e,t){let n=await L(`/api/admin/repositories/add-public`,t,{repository:e},{token:!0});if(!n.ok)throw Error(ir[n.status]??`GitHub lookup failed (HTTP ${n.status}). Try again.`)}async function or(e,t){let n=await I(`/api/admin/repositories/impact?repoId=${encodeURIComponent(e)}`,t);if(n?.repoId!==e||!Array.isArray(n.reports)||!Array.isArray(n.bundles)||!Number.isSafeInteger(n.triageCount)||n.triageCount<0)throw Error(`Invalid repository data`);return n}var sr={"github-app-not-configured":`The GitHub App is not configured on this server.`,"repo-identity-changed":`The repository has changed on GitHub. Refresh and check its connection.`,"repo-connection-changed":`The connection or your permissions changed. Refresh and try again.`,"repo-not-connected":`This repository is no longer connected.`,forbidden:`Administrator access is required to connect the GitHub App.`};async function cr(e,t){let n=await L(`/api/admin/repositories/connect-app`,t,{repoId:e},{token:!0}),r=await n.json();if(!n.ok)throw Error(sr[r.error]??`Could not connect the GitHub App (HTTP ${n.status}). Try again.`);if(r.connected===!0)return r;if(r.connected!==!1||typeof r.installUrl!=`string`||!/^https:\/\/github\.com\/apps\/[^/?#]+\/installations\/new$/u.test(r.installUrl))throw Error(`Invalid GitHub installation response.`);return r}async function lr(e,t,n,r){return(await R(`/api/admin/repositories/remove`,r,{repoId:e,fullName:t,acknowledge:!0,deleteTriage:n})).json()}function ur(e){return I(`/api/admin/reports`,e)}var dr={"unsupported-entries":`Select JavaScript/TypeScript files (including JSX/TSX) or Solidity files. Stasis cannot mix languages or use JSON or Rust as remote entry points.`,"bad-conditions":`Check the export conditions and selected platforms.`,"metro-conditions":`Stasis’s Metro preset requires the react-native condition without manual changes.`,"config-invalid":`Stasis can’t read the stasis.config.json these entry points are under, build them with the options it sets, or lay out the lockfiles it names. Check it at this revision.`,"config-mixed":`Entry points listed in a stasis.config.json are built with its options, alone. Select only those it lists, or only other files.`,"config-conditions":`These entry points are listed in stasis.config.json, which sets their options, so they take no conditions. Reload the directory and try again.`,"config-runs-code":`stasis.config.json sets an option for these entry points that runs the repository’s code, such as babel. Bundles built here never run it.`,"config-policy":`The bundle holds a path or package that stasis.config.json’s allowedPaths, disallowedPaths, allowedModules or disallowedModules refuses, or that its excludeModules excludes.`,"stasis-lock":`The build doesn’t agree with the repository’s stasis.lock.json, or stasis.config.json’s lock = frozen needs one that isn’t there. Update it at this revision.`,"commit-not-own":`Stasis can’t find this commit in the history of the repository’s branches or tags: it may be a fork’s, which GitHub serves through the repository too. Pick a commit of its default branch, a branch or a tag.`,"build-lockfile":`Stasis needs a supported lockfile: pnpm-lock.yaml, yarn.lock (Yarn 1), package-lock.json, or soldeer.lock.`,"build-scope":`Your team needs access to the bundle’s project root, including its lockfile and dependencies.`,"build-busy":`A bundle is already being built, or the server is busy. Try again shortly.`,"build-timeout":`The bundle build timed out. Try a smaller selection or retry.`,"too-large":`This bundle exceeds the server’s size limit.`,"build-memory":`Building this selection needs more memory than the server gives a build. Select fewer entry points, or build it with stasis github-bundle and upload the bundle.`,"github-rate-limited":`GitHub’s API rate limit has been reached. Retry after the limit resets.`,"github-build-failed":`Could not fetch the repository from GitHub. Check access and retry.`,"repository-changed":`The repository connection changed during the build. Reload and try again.`,"bundle-conflict":`This bundle already exists but is outside your current access.`,"build-failed":`Stasis could not build this selection. Check that its lockfile is supported and all entry points and imports exist at this commit.`};async function fr(e,t,n){let r=await L(`/api/admin/bundles/create`,t,e,{signal:n,token:!0}),i=await r.json();if(!r.ok)throw Error(dr[i.error]??(r.status===401?`Sign in again to create a bundle.`:r.status===403||r.status===404?`Repository access is required to create this bundle.`:`Could not create the bundle. Try again.`));return i}async function pr(e,t){let n=(await I(`/api/config`)).managed?.uploadMaxBytes?.reports;if(Number.isSafeInteger(n)&&n>0){if(e.size>n)throw Error(`too large`)}else if(e.size>3145728)return mr(e,t);let r=je(await e.text(),e.name);if(!r)return mr(e,t);let i=[],a=[];for(let{name:e,content:n}of r)try{a.push(await mr(new File([n],e,{type:`application/json`}),t))}catch(t){i.push(`${e}: ${String(t?.message??t)}`)}if(i.length>0)throw Error(`${i.length} of ${r.length} products failed (${i.join(`; `)})`);return a.at(-1)}async function mr(e,t){let n=await Xn(`report`,e,t,e.type||`application/json`);if(!n.ok){if(n.status===413)throw Error(`too large`);if(n.status===403)throw Error(await Jn(n));let e=await n.json().catch(()=>null);if(e?.error===`storage-encryption-required`)throw Error(`Link reports require managed storage encryption. Configure MANAGED_STORAGE_ENCRYPTION_KEY.`);if(e?.error===`invalid-report`)throw Error(typeof e.reason==`string`&&e.reason?`This file is not a report: ${e.reason}`:`This file is not a recognized report.`);let t=e?.error===`repo-not-connected`&&typeof e.repo==`string`?`: ${e.repo} is not connected`:``;throw Error(`HTTP ${n.status}${t}`)}return n.json()}async function hr(e,t,n){await R(`/api/admin/reports/set-visible`,n,{reportId:e,visible:t})}async function gr(e,t,n){let r=await L(`/api/admin/reports/set-opening`,n,{reportId:e,confirmedDefault:t});if(!r.ok)throw Error(r.status===409?`this report already opens as an App view, or has no Confirmed findings`:`HTTP ${r.status}`)}async function _r(e,t,n,r){let i=await L(`/api/admin/reports/set-repo`,r,{reportId:e,repoId:t,directory:n});if(!i.ok)throw i.status===409?Error(`this report already defines its repository`):i.status===403?Error(await Jn(i)):Error(i.status===400?`invalid repository or directory`:`HTTP ${i.status}`);return i.json()}async function vr(e,t){let n=await l(`/api/admin/reports/${encodeURIComponent(e)}/location`,{signal:t,credentials:`same-origin`});if(!n.ok)throw Error(`Report location suggestion request failed (${n.status})`);return(await n.json())?.location??null}function yr(e,t){return Yn(`reports`,e,t)}function br(e){return I(`/api/admin/bundles`,e)}async function xr(e,t){let n=await Xn(`bundle`,e,t,`application/octet-stream`);if(!n.ok)throw Error(n.status===413?`too large`:n.status===403?await Jn(n):`HTTP ${n.status}`);return n.json()}async function Sr(e,t){let n=await I(`/api/admin/bundles/${encodeURIComponent(e)}/usage`,t);if(n?.bundleId!==e||!Array.isArray(n.reports)||!n.reports.every(e=>typeof e?.filename==`string`)||!Number.isSafeInteger(n.otherReports)||n.otherReports<0)throw Error(`Invalid bundle usage`);return n}function Cr(e,t){return Yn(`bundles`,e,t)}async function wr(e,t,n){await R(`/api/admin/bundles/set-visible`,n,{bundleId:e,visible:t})}async function Tr(e,t,n,r){let i=await L(`/api/admin/bundles/set-repo`,r,{bundleId:e,repoId:t,directory:n});if(!i.ok)throw Error(i.status===403?await Jn(i):i.status===400?`invalid repository or directory`:`HTTP ${i.status}`)}function Er(e){return I(`/api/admin/teams`,e)}async function Dr(e,t,n){let r=await L(`/api/admin/teams${e}`,t,n);if(!r.ok)throw Error(r.status===409?`name already taken`:`HTTP ${r.status}`)}var Or=`.local-import-toggle{flex-shrink:0;margin-block:calc(-.25rem - 1px);margin-left:auto;padding:.25rem .6rem;border:1px solid var(--border);border-radius:var(--ui-radius, 6px);background:transparent;color:var(--muted);font:inherit;font-size:.75rem;line-height:1.5}.local-import-toggle:hover,.local-import-toggle[aria-expanded=true]{color:var(--text);background:rgb(from var(--text) r g b / .06)}.local-import-panel{display:grid;gap:.8rem;padding:1rem;margin-bottom:1.25rem;border:1px solid var(--border);border-radius:var(--ui-radius, 8px);background:rgb(from var(--accent) r g b / .025)}.local-import-copy strong{font-size:.82rem;font-weight:600}.local-import-copy p,.local-import-message{margin:.3rem 0 0;color:var(--muted);font-size:.75rem;line-height:1.5}.local-import-controls{display:flex;align-items:center;flex-wrap:wrap;gap:.5rem}managed-local-item-selector{flex:1 1 16rem;min-width:0}.local-import-controls button,.local-import-message button{padding:.35rem .7rem;border:1px solid var(--border);border-radius:var(--ui-radius, 5px);background:transparent;color:var(--text);font:inherit;font-size:.75rem;line-height:1.5}.local-import-controls .local-import-submit{border-color:rgb(from var(--accent) r g b / .4);background:rgb(from var(--accent) r g b / .1);color:var(--accent)}.local-import-controls .local-import-close{color:var(--muted)}.local-import-panel button:disabled,.local-import-toggle:disabled{opacity:.5}.local-import-panel button:focus-visible,.local-import-toggle:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.local-import-message.error{color:var(--critical)}
4
4
  `,kr=`.home-section{margin-block:1.1rem 2rem}.section-heading{display:flex;align-items:baseline;gap:1rem;margin-bottom:.85rem}.section-heading h2{margin:0;font-size:.86rem;font-weight:600}.section-heading>span{color:var(--muted);font-size:.75rem}.pages{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:.9rem}.page{display:flex;flex-direction:column;gap:.85rem;padding:1.35rem;border:1px solid var(--border);border-radius:var(--ui-radius, 12px);color:var(--text);background:var(--panel);text-align:left;font:inherit}.page:hover{background:var(--panel-hover);border-color:color-mix(in srgb,var(--muted) 60%,var(--border))}.page-top{display:flex;align-items:center;gap:.75rem;width:100%}.page-icon{display:grid;place-items:center;flex-shrink:0;width:2.5rem;height:2.5rem;border:1px solid color-mix(in srgb,var(--accent) 16%,var(--border));border-radius:var(--ui-radius, 9px);background:color-mix(in srgb,var(--accent) 7%,var(--panel));color:var(--accent)}.page-bundle .page-icon{color:var(--green);border-color:color-mix(in srgb,var(--green) 18%,var(--border));background:color-mix(in srgb,var(--green) 6%,var(--panel))}.page-scan .page-icon{color:var(--scan-icon-color, var(--yellow));border-color:color-mix(in srgb,var(--scan-icon-color, var(--yellow)) 18%,var(--border));background:color-mix(in srgb,var(--scan-icon-color, var(--yellow)) 6%,var(--panel))}:host-context(body.theme-light) .page-scan .page-icon{--scan-icon-color: #bf8700}:host-context(body.theme-green) :is(.page-bundle,.page-scan) .page-icon,:host-context(body.theme-pink) :is(.page-bundle,.page-scan) .page-icon{color:var(--accent);border-color:color-mix(in srgb,var(--accent) 16%,var(--border));background:color-mix(in srgb,var(--accent) 7%,var(--panel))}.page-icon svg{width:1.2rem;height:1.2rem}.arrow{display:flex;margin-left:auto;flex-shrink:0;color:var(--muted)}.arrow svg{width:1rem;height:1rem}.page:hover .arrow{color:var(--text)}.page-copy{display:grid;gap:.45rem}.page>.page-copy{margin-inline-start:3.25rem}.page-copy strong,.page-title{font-size:1rem;font-weight:600;letter-spacing:-.015em}.page-copy>span{color:var(--muted);font-size:.8rem;line-height:1.65}.workspace-pages .page{padding:1.2rem 1.35rem}.workspace-pages .page-icon{width:2rem;height:2rem;color:var(--muted);background:transparent;border-color:var(--border)}.workspace-pages .page-title{font-size:.9rem}.workspace-pages .page-copy{margin-inline-start:2.75rem}.history-link{display:flex;align-items:center;gap:1rem;width:100%;padding:1.25rem 0;border:0;border-top:1px solid var(--border);text-align:left;color:var(--text);background:transparent}.history-link>.page-icon{color:var(--muted);background:transparent;border-color:var(--border)}.history-link .page-copy strong{font-size:.85rem}.history-cta{display:flex;align-items:center;gap:.6rem;flex-shrink:0;margin-left:auto;color:var(--muted);font-size:.78rem}.history-cta svg{width:1rem;height:1rem}.history-link:hover .history-cta{color:var(--accent)}@container (max-width: 48rem){.pages{grid-template-columns:1fr;gap:.65rem}.page,.workspace-pages .page{gap:.65rem;padding:1.15rem}.page-top .arrow{display:none}.workspace-pages .page-icon{width:2.5rem;height:2.5rem}.workspace-pages .page-copy{margin-inline-start:3.25rem}.page-copy{gap:.2rem}.page-copy strong,.page-title{font-size:.95rem}.section-heading>span{display:none}.history-cta{font-size:0}}
@@ -18,9 +18,9 @@ import{b as e,d as t,i as n}from"./chunk-WB3NRZL7.js";import{a as r}from"./chunk
18
18
  `)}var Ri=class extends Ni{static kind=`bundle`;static view=`manage-bundles`;static collection=[`bundles`,`bundles`,br];static upload=xr;static uploadFamilies=[`bundles`,`bundle-metadata`,`reports`,`repo-impact`,`history`,`scan-sources`];static importFamilies=[`bundles`,`reports`,`repo-impact`,`history`,`scan-sources`];static setVisible=wr;static visibleFamilies=[`bundles`,`teams`,`history`,`scan-sources`];static setRepo=Tr;static locationFamilies=[`bundles`,`teams`,`repo-impact`,`history`,`scan-sources`];static hintSource=`metadata`;static uploadCopy=`Drop source archives here or browse files above.`;static properties={createRepoId:{attribute:!1},installTooltips:{attribute:!1},_visibilityBusy:{state:!0},_deleting:{state:!0},_creating:{state:!0}};static styles=[v(Pr),v(Fr),v(r),v(Or)];constructor(){super(),Object.assign(this,{_visibilityBusy:null,_deleting:null,_creating:!1})}_acceptsDrop(){return!this._creating}_searchText(e){return[e.filename,e.repoFullName,e.repoDirectory,e.kind,e.provenance===`build`?`built`:null,e.uploadedByLogin]}_visible(e){return e.visible!==!1}_suggests(e){return e.kind===`stasis`}_fetchOrigin(e,t){return bt(e,{signal:t})}_suggestion(e){return{github:e.github,directory:typeof e.directory==`string`?e.directory:e.root===!0?`/`:null}}_originRepo(e,t){let n=rt({repo:e})?.toLowerCase();return n&&t.find(e=>e.fullName.toLowerCase()===n)}_showCreate(e){!e&&this.createRepoId!=null?f(`manage-bundles`):(this._creating=e,this._drop.active=!1,e||this.updateComplete.then(()=>this.renderRoot.querySelector(`.create-bundle-action`)?.focus()))}willUpdate(e){e.has(`createRepoId`)&&(this._creating=this.createRepoId!=null)}render(){return this._creating?y`<div class="wrap">${this._nav()} ${hi(`Bundles`,`Back to bundles`,()=>this._showCreate(!1),`Create a bundle`)}<managed-create-bundle .initialRepoId="${this.createRepoId??null}" .installTooltips="${this.installTooltips}" .createBundle="${this._csrf?(e,t)=>this.appState.mutate(()=>fr(e,this._csrf,t),[`bundles`,`bundle-metadata`,`reports`,`repo-impact`,`history`,`scan-sources`]):void 0}" @bundle-created="${e=>this._emit(`managed-bundle-open`,e.detail)}"></managed-create-bundle></div>`:this._page(y`<p class="intro">Source bundles for your repositories.</p><div class="bundle-actions">${this._localImport.renderAction()}<button type="button" class="local-import-toggle create-bundle-action" ?disabled="${!this._data}" @click="${()=>this._showCreate(!0)}">Create</button></div>`,y`<section class="drop-card" aria-label="Upload bundles">${this._drop.card(`Upload source bundles`,`Drop source archives anywhere on this page.`,this._busy)}</section>`)}_count(e,t){let n=this._data!=null,r=e.filter(e=>e.repoId==null).length,i=e.reduce((e,t)=>e+(Number.isFinite(t.byteSize)?t.byteSize:0),0);return y`<span class="summary result-count" role="status"><span>${n?t:`… bundles`}</span><span>${n?h(i):`…`}</span> ${!n||r?y`<span class="unassigned">${n?`${r} unattached`:`… unattached`}</span>`:b}</span>`}_items(e){let t=[...Map.groupBy(e,e=>e.repoFullName||`Unattached`)].toSorted(([e],[t])=>e===`Unattached`?-1:t===`Unattached`?1:e.localeCompare(t));return y`<div class="bundle-groups">${t.map(([e,t])=>y`<section class="bundle-group"><div class="bundle-group-head"><strong>${e}</strong><span>${t.length} ${t.length===1?`bundle`:`bundles`}</span></div><ul class="bundles">${t.map(e=>this._row(e))}</ul></section>`)}</div>`}_row(e){let t=e.visible!==!1,n=Mi(e);return y`<li class="${`bundle-row${t?``:` content-hidden`}`}"><span class="identity"><span class="bundle-icon" aria-hidden="true">${e.kind===`stasis`?y`<img src="./stasis.svg" width="16" height="16" alt="">`:Fi}</span> <button type="button" class="filename bundle-open" data-tooltip-truncated data-tooltip="${e.filename}" @click="${()=>this._emit(`managed-bundle-open`,e)}">${e.filename}</button> ${e.provenance===`build`?y`<span class="bundle-provenance" data-tooltip="Generated on this server from the repository">Built</span>`:b} </span><span class="meta bundle-uploader" data-tooltip-truncated data-tooltip="${e.uploadedByLogin?`@${e.uploadedByLogin}`:``}">${e.uploadedByLogin?`@${e.uploadedByLogin}`:``}</span> <span class="meta bundle-date">${ji(e)}</span> <span class="meta bundle-size">${h(e.byteSize)}</span> <span class="bundle-location" data-tooltip-truncated data-tooltip="${n}">${n}</span> <span class="${`status ${t?`visible`:`hidden`}`}">${t?`Visible`:`Hidden`}</span> <span class="actions">${e.canChangeRepo===!1?b:y`<button type="button" class="action" aria-label="${`Set location for ${e.filename}`}" data-tooltip="Set repository location" ?disabled="${this._locationBusy}" @click="${()=>this._openLocation(e)}">${p(`repo`)}</button>`} <button type="button" class="action" aria-label="${`${t?`Hide`:`Make visible`} ${e.filename}`}" data-tooltip="${t?`Hide from teams`:e.repoId==null?`Assign a repository before publishing`:`Make visible to teams`}" ?disabled="${this._visibilityBusy!=null||e.canChangeRepo===!1||!t&&e.repoId==null}" @click="${()=>{this._setVisible(e,!t)}}">${p(t?`hide`:`show`)}</button> <a class="action" aria-label="${`Download ${e.filename}`}" href="${`/api/admin/bundles/${encodeURIComponent(e.id)}`}"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2v8m-3-3 3 3 3-3M3 11v3h10v-3"/></svg></a><button type="button" class="action danger" aria-label="${`Delete ${e.filename}`}" ?disabled="${e.canChangeRepo===!1||this._deleting!=null}" data-tooltip="${e.canChangeRepo===!1?`Repository access is required to detach or delete this bundle`:b}" @click="${()=>this._delete(e)}">${ui}</button> </span>${this._locationId===e.id?this._locationEditor(e):b}</li>`}async _setVisible(e,t){if(this._visibilityBusy==null&&e.canChangeRepo!==!1){this._visibilityBusy=e.id;try{await super._setVisible(e,t)}finally{this._visibilityBusy=null}}}_openLocation(e){this._locationBusy||super._openLocation(e)}_saveLocation(e){return e.canChangeRepo===!1?Promise.resolve():super._saveLocation(e)}async _delete(e){if(this._deleting==null&&e.canChangeRepo!==!1){this._deleting=e.id,this._error=null;try{let t;try{t=await Sr(e.id)}catch(t){this._error=`Couldn't check which reports use \u201C${e.filename}\u201D: ${String(t?.message??t)}`;return}if(!globalThis.confirm?.(Li(e,t)))return;try{await this.appState.mutate(()=>Cr(e.id,this._csrf),[`bundles`,`bundle-metadata`,`reports`,`repo-impact`,`history`,`scan-sources`])}catch(e){this._error=`Delete failed: ${String(e?.message??e)}`}await this._load({preserveError:!0})}finally{this._deleting=null}}}};customElements.define(`managed-admin-bundles`,Ri);var zi=class extends x{static view=`manage-scans`;static properties={selection:{attribute:!1},_source:{state:!0}};static styles=v(r);static collection=[`bundles`,`bundles`,br];constructor(){super(),this._source=null,this._loadModels=(e,t)=>this.appState.load(`models`,`scan models`,e=>n(e,l),{signal:e,apply:t}),this._loadReportSources=(e,n)=>this.appState.load(`scan-sources`,`scan report inputs`,async e=>{let[n,r]=await Promise.all([l(`/api/admin/reports`,{signal:e,credentials:`same-origin`}),l(`/api/admin/scan-results`,{signal:e,credentials:`same-origin`})]);if(!n.ok)throw Error(`Reports: HTTP ${n.status}`);if(!r.ok&&r.status!==404)throw Error(`Scan results: HTTP ${r.status}`);let i=await n.json();return i.reports=await Promise.all((i.reports??[]).filter(e=>e.visible&&e.repoId!=null).map(async t=>{let n=await l(`/api/admin/reports/${encodeURIComponent(t.id)}`,{signal:e,credentials:`same-origin`});if(!n.ok)throw Error(`Report ${m(t.filename)}: HTTP ${n.status}`);return{...t,content:await n.text()}})),t(i,r.ok?await r.json():{bundles:[],results:[]})},{signal:e,apply:n})}_load(){return Ne().catch(e=>{this._error=String(e?.message??e)}),super._load()}_show(e){this._source=Zr(e)}render(){return y`<div class="wrap">${this._nav()} ${this._error?y`<p class="msg error" role="alert">Couldn’t load scan sources: ${this._error} <button type="button" class="btn" @click="${()=>{this._load()}}">Retry</button></p>`:b}<deepview-scan-page hide-heading .selection="${this.selection}" .source="${this._source}" .sourceLoading="${this._loading&&this._source==null}" .loadBundle="${Qr}" .loadModels="${this._loadModels}" .loadReportSources="${this._loadReportSources}" .createBundleHref="${e=>Number.isSafeInteger(e)&&e>0?tt({view:`manage-bundles`,createRepoId:e}):null}"></deepview-scan-page></div>`}};customElements.define(`managed-admin-scans`,zi);var Bi=(e,t)=>new Map([...e].filter(([e])=>e!==t)),Vi=class extends x{static view=`manage-teams`;static properties={_busy:{state:!0},_renamingId:{state:!0},_repoChoices:{state:!0},_memberChoices:{state:!0}};static styles=[v(Ir),v(r)];static collection=[`teams`,`teams`,Er];constructor(){super(),Object.assign(this,{_busy:!1,_renamingId:null,_repoChoices:new Map,_memberChoices:new Map})}async _do(e){if(!this._busy){this._busy=!0,this._error=null;try{await this.appState.mutate(e,[`teams`,`users`,`reports`,`history`,`repos`]),globalThis.dispatchEvent?.(new Event(`dependency-review-changed`))}catch(e){this._error=String(e?.message??e)}finally{this._busy=!1,await this._load({preserveError:!0})}}}_post(e,t,n=()=>{}){return this._do(async()=>{await Dr(e,this._csrf,t),n()})}render(){return y`<div class="wrap">${this._nav()}<h1 class="sr-only">Teams</h1><div class="page-intro"><p class="intro">Manage repository and finding access for each team.</p><span class="result-count">${this._data?.teams?.length??`…`} teams</span></div><div class="create-team"><label class="sr-only" for="new-team-name">New team</label> <input id="new-team-name" class="new-name" type="text" placeholder="Team name" maxlength="100" ?disabled="${this._busy}" @keydown="${e=>{e.key===`Enter`&&this._create()}}"> <button class="btn primary" ?disabled="${this._busy}" @click="${()=>this._create()}">${fi} Create team</button><p class="access-note ui-hint">All members can view standard findings. Set dependencies and security access per member.</p></div><div class="manage-list" aria-busy="${this._loading}">${this._body()}</div></div>`}_body(){if(this._error!=null&&this._data==null)return y`<p class="msg error">Couldn't load teams: ${this._error}</p>`;if(this._data==null)return S(`Loading teams…`);let e=Array.isArray(this._data.teams)?this._data.teams:[];return y`${this._error==null?b:y`<p class="msg error">${this._error}</p>`} ${e.length===0?y`<p class="msg">No teams yet. Create one above.</p>`:e.map(e=>this._team(e))}`}_team(e){return y`<section class="team" aria-label="${e.name}"><div class="team-head"><span class="team-icon" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="5" r="2.5"/><path d="M1.5 13v-1c0-2 1.8-3.5 4.5-3.5s4.5 1.5 4.5 3.5v1M11 2.5a2.5 2.5 0 0 1 0 5M12 9c1.7.5 2.5 1.5 2.5 3v1"/></svg></span>${this._renamingId===e.id?y`<input class="rename-input" type="text" .value="${e.name}" maxlength="100" aria-label="Team name" @keydown="${t=>this._renameKey(t,e)}"> <button class="btn" ?disabled="${this._busy}" @click="${t=>this._saveRename(e,t)}">Save</button> <button class="btn" @click="${()=>{this._renamingId=null}}">Cancel</button>`:y`<h2 class="team-name">${e.name}</h2>${e.hidden?y`<span class="muted ui-hint">Disabled</span>`:b} <span class="team-actions"><button class="icon-btn" aria-label="${`${e.hidden?`Restore`:`Hide`} ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/set-hidden`,{teamId:e.id,hidden:!e.hidden})}">${p(e.hidden?`show`:`hide`)}</button> <button class="icon-btn" aria-label="${`Rename ${e.name}`}" ?disabled="${this._busy}" @click="${()=>{this._renamingId=e.id}}">${li}</button> <button class="icon-btn danger" aria-label="${`Delete ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._deleteTeam(e)}">${ui}</button></span>`}</div><div class="team-body">${[[`Repositories`,e.repos,`No repositories linked.`,t=>this._repoRow(e,t),this._addRepoRow(e)],[`Members`,e.members,`No members.`,t=>this._memberRow(e,t),this._addMemberRow(e)]].map(([e,t,n,r,i])=>y`<div class="sub"><h3 class="sub-title">${e} <span class="count">${t.length}</span></h3>${t.length===0?y`<p class="muted ui-hint">${n}</p>`:y`<ul class="links">${t.map(r)}</ul>`} ${i}</div>`)}${this._npmScopes(e)}</div></section>`}_npmScopes(e){let t=Array.isArray(e.npmScopes)?e.npmScopes:[];return y`<div class="sub npm-scopes"><div class="sub-head"><h3 class="sub-title">npm scopes <span class="count">${t.length}</span><mode-switch class="npm-review-toggle" label="Enable dependency review" .checked="${!!e.dependencyReview}" .disabled="${this._busy}" @click="${()=>{this._busy||this._post(`/set-dependency-review`,{teamId:e.id,enabled:!e.dependencyReview})}}"></mode-switch></h3><p class="muted ui-hint">Members can open private packages in these scopes. Everyone can open public packages.</p></div><div class="add-row npm-scope-row"><input class="add-npm-scope" type="text" placeholder="@scope" aria-label="${`npm scope to add to ${e.name}`}" maxlength="215" ?disabled="${this._busy}" @keydown="${t=>{t.key===`Enter`&&this._addNpmScope(e,t)}}"> <button class="btn" aria-label="${`Add npm scope to ${e.name}`}" ?disabled="${this._busy}" @click="${t=>this._addNpmScope(e,t)}">${fi} Add</button> ${t.length===0?b:y`<ul class="npm-scope-list">${t.map(n=>y`<li class="npm-scope"><span>${n}</span> <button class="icon-btn danger" aria-label="${`Remove ${n} from ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/set-npm-scopes`,{teamId:e.id,scopes:t.filter(e=>e!==n)})}">${di}</button></li>`)}</ul>`}</div></div>`}_addNpmScope(e,t){let n=t.target.closest(`.add-row`)?.querySelector(`.add-npm-scope`);if(!n?.value.trim())return;let r=et(n.value);if(r===null){this._error=`\u201C${n.value.trim()}\u201D is not an npm scope. Scopes look like @example.`;return}let i=Array.isArray(e.npmScopes)?e.npmScopes:[];i.includes(r)?n.value=``:this._post(`/set-npm-scopes`,{teamId:e.id,scopes:[...i,r]},()=>{n.value=``})}_repoRow(e,t){return y`<li class="repo-row">${pi} <span class="repo-copy"><span class="ln">${t.fullName}</span>${t.path?y`<span class="path">/${t.path.replace(/^\/+/u,``)}</span>`:b}</span> <button class="icon-btn danger" aria-label="${`Remove ${t.fullName}${t.path?`/${t.path}`:``} from ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/remove-repo`,{teamId:e.id,repoId:t.repoId,path:t.path??null})}">${di}</button></li>`}_addRepoRow(e){let t=Array.isArray(this._data.repos)?this._data.repos:[];return t.length===0?y`<p class="muted ui-hint">No selected repositories to link — pick some on “Manage repositories”.</p>`:y`<div class="add-row"><repository-selector class="add-repo-sel" label="${`Repository to add to ${e.name}`}" placeholder="Add repository…" ?disabled="${this._busy}" .options="${t.map(e=>({value:e.repoId,label:e.fullName}))}" .value="${this._repoChoices.get(e.id)??null}" @repository-change="${t=>{this._repoChoices=new Map(this._repoChoices).set(e.id,t.detail.value)}}"></repository-selector><input class="add-repo-path" type="text" placeholder="Path (optional)" aria-label="${`Repository path in ${e.name} (optional)`}" maxlength="500" ?disabled="${this._busy}"> <button class="btn" aria-label="${`Add repository to ${e.name}`}" ?disabled="${this._busy||!this._repoChoices.has(e.id)}" @click="${t=>this._addRepo(e,t)}">${fi} Add</button></div>`}_fullAccess(e){return this._data.users?.some(t=>t.id===e.userId&&Le(t.role,`manage`))}_memberRow(e,t){let n=Array.isArray(this._data.permissions)?this._data.permissions:[],r=this._fullAccess(t);return y`<li class="member-row"><span class="member">${ai(t.userId,t.login)}<span class="ln">${t.login}</span></span> <span class="perms">${n.map(n=>y`<label class="perm"><input type="checkbox" .checked="${r||t[n]===!0}" ?disabled="${this._busy||r}" aria-label="${`${o[n]??n} access for ${t.login} in ${e.name}`}" @change="${r=>this._togglePerm(e,t,n,r.target.checked)}"> ${o[n]??n}</label>`)} </span><button class="icon-btn danger" aria-label="${`Remove ${t.login} from ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/remove-member`,{teamId:e.id,userId:t.userId})}">${di}</button></li>`}_addMemberRow(e){let t=Array.isArray(this._data.users)?this._data.users:[],n=new Set(e.members.map(e=>e.userId));return y`<div class="add-row"><user-selector class="add-member-sel" label="${`Member to add to ${e.name}`}" placeholder="Add member…" ?disabled="${this._busy}" .users="${t.map(e=>({...e,disabled:n.has(e.id),detail:n.has(e.id)?`Member`:``}))}" .value="${this._memberChoices.get(e.id)??null}" @user-change="${t=>{this._memberChoices=new Map(this._memberChoices).set(e.id,t.detail.value)}}"></user-selector><button class="btn" aria-label="${`Add member to ${e.name}`}" ?disabled="${this._busy||!this._memberChoices.has(e.id)||n.has(this._memberChoices.get(e.id))}" @click="${()=>this._addMember(e)}">${fi} Add</button></div>`}_create(){let e=this.renderRoot.querySelector(`.new-name`),t=e?.value.trim();t&&this._post(``,{name:t},()=>{e&&(e.value=``)})}_deleteTeam(e){globalThis.confirm?.(`Delete team \u201C${e.name}\u201D? Its repo + member links are removed.`)&&this._post(`/delete`,{teamId:e.id})}_renameKey(e,t){e.key===`Enter`?this._saveRename(t,e):e.key===`Escape`&&(this._renamingId=null)}_saveRename(e,t){if(this._busy)return;let n=t.target.closest(`.team-head`)?.querySelector(`.rename-input`)?.value.trim()??``;this._renamingId=null,n!==``&&n!==e.name&&this._post(`/rename`,{teamId:e.id,name:n})}_addRepo(e,t){let n=t.target.closest(`.add-row`)?.querySelector(`.add-repo-path`),r=this._repoChoices.get(e.id);!Number.isSafeInteger(r)||r<=0||this._post(`/set-repo`,{teamId:e.id,repoId:r,path:n?.value??``},()=>{this._repoChoices=Bi(this._repoChoices,e.id),n&&(n.value=``)})}_addMember(e){let t=this._memberChoices.get(e.id);!t||e.members.some(e=>e.userId===t)||this._post(`/set-member`,{teamId:e.id,userId:t},()=>{this._memberChoices=Bi(this._memberChoices,e.id)})}_togglePerm(e,t,n,r){if(this._fullAccess(t))return;let i={...Object.fromEntries((this._data.permissions??[]).map(e=>[e,t[e]===!0])),[n]:r};this._post(`/set-member`,{teamId:e.id,userId:t.userId,...i})}};customElements.define(`managed-admin-teams`,Vi);var Hi=`.link-team{margin-top:1.5rem}.link-team h2{margin:0 0 .5rem;font-size:1rem;font-weight:600}.link-table{overflow-x:auto}table{width:100%;border-collapse:collapse;text-align:left;font-size:.8rem}th{color:var(--muted);font-weight:500}th,td{padding:.6rem .65rem;border-bottom:1px solid var(--border);white-space:nowrap}th:first-child,td:first-child{padding-left:0}th:last-child,td:last-child{padding-right:0;text-align:right}
19
19
  `;async function Ui(e){let t=await l(`/api/admin/links`,{signal:e,credentials:`same-origin`});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(!Array.isArray(n?.shares))throw TypeError(`No public links returned`);return n}var Wi=class extends x{static view=`manage-links`;static styles=[v(r),v(Hi)];static collection=[`links`,`public links`,Ui];async _edit(e){await Se({id:e.teamId,name:e.teamName},e.id,this.session),this.isConnected&&await this._load()}_groups(){return[...Map.groupBy(this._data?.shares??[],e=>e.teamId).values()].map(e=>({name:e[0].teamName,links:e}))}_body(){return this._data==null?this._error?y`<p class="msg error">Couldn't load public links: ${this._error}</p>`:S(`Loading public links…`):this._data.shares.length===0?y`<p class="msg">No public links. Create one with the share button beside a workspace in the sidebar.</p>`:this._groups().map(e=>y`<section class="link-team" aria-label="${e.name}"><h2>${e.name}</h2><div class="link-table"><table><thead><tr><th>Link</th><th>Created by</th><th>Created</th><th>Security</th><th>Dependencies</th><th><span class="sr-only">Actions</span></th></tr></thead><tbody>${e.links.map(t=>y`<tr><td><span data-tooltip="${t.id}">${t.id.slice(0,8)}</span></td><td>${t.createdBy}</td><td>${new Date(t.createdAt).toLocaleString()}</td><td>${t.permissions.security?`On`:`Off`}</td><td>${t.permissions.dependencies?`On`:`Off`}</td><td><button class="btn" aria-label="${`Edit public link ${t.id.slice(0,8)} for ${e.name}`}" @click="${()=>this._edit(t)}">Edit</button></td></tr>`)}</tbody></table></div></section>`)}render(){return y`<div class="wrap">${this._nav()}<h1 class="sr-only">Public links</h1><div class="page-intro"><p class="intro">Manage public links and the findings each link can show.</p><span class="result-count">${this._data?.shares.length??`…`} links</span></div>${this._loading&&this._data?y`<span class="sr-only" role="status">Refreshing public links…</span>`:b}<div class="manage-list" aria-busy="${this._loading}">${this._body()}</div></div>`}};customElements.define(`managed-admin-links`,Wi);var Gi=qn(`/api/admin/deduplication`,{"storage-encryption-required":`Configure MANAGED_STORAGE_ENCRYPTION_KEY on the server to import encrypted link reports.`,"invalid-link-report":`Choose a link report containing arrays of finding IDs, such as [["id1", "id2"]].`,"too-large":`This link report exceeds the server upload limit.`}),Ki=[`deduplication`,`reports`,`teams`],qi=class extends x{static view=`manage-deduplication`;static properties={_busy:{state:!0}};static styles=[v(r),v(Nr),v(Hi)];static collection=[`deduplication`,`deduplication reports`,e=>Gi(``,{signal:e})];constructor(){super(),this._busy=!1,this._queue=[],this._drop=new pt(this)}_upload(e){if(this._csrf&&this._role===`admin`)return ft(this,e,e=>Gi(``,{method:`POST`,headers:{"content-type":`application/json`,"x-report-filename":encodeURIComponent(e.name),"x-csrf-token":this._csrf},body:e}),Ki)}async _toggle(e){if(!this._busy&&this._csrf){this._busy=!0,this._error=null;try{await this.appState.mutate(()=>Gi(`/${encodeURIComponent(e.id)}`,{method:`PATCH`,headers:{"content-type":`application/json`,"x-csrf-token":this._csrf},body:JSON.stringify({enabled:!e.enabled})}),Ki)}catch(e){this._error=String(e?.message??e)}finally{this._busy=!1,await this._load({preserveError:!0});let e=this._queue.splice(0);e.length>0&&this._upload(e)}}}render(){let e=this._data?.reports??[];return y`${this._drop.overlay(`Drop link reports to import`)}<div class="wrap">${this._nav()}<h1 class="sr-only">Deduplication</h1><div class="page-intro"><p class="intro">Link duplicate findings across all teams.</p><span class="result-count">${this._data?e.length:`…`} reports</span><button type="button" class="btn" @click="${()=>f(`manage-scans`,{scanMode:`link`})}">Link reports</button></div><div class="drop-card">${this._drop.card(`Import link reports`,`Drop *.link.json files anywhere on this page.`,this._busy||!this._csrf,`Saving…`)}</div>${C(this._error)} ${this._list(this._data,`Loading deduplication reports…`,()=>e.length===0?w(`No link reports imported yet`,`Each row in a link report lists IDs for the same finding.`):y`<div class="link-table"><table><thead><tr><th>Report</th><th>Groups</th><th>Finding IDs</th><th>Imported by</th><th>Imported</th><th>Status</th><th><span class="sr-only">Actions</span></th></tr></thead><tbody>${e.map(e=>y`<tr><td>${e.filename}</td><td>${e.groupCount}</td><td>${e.findingCount}</td><td>${e.uploadedByLogin??`Removed user`}</td><td>${new Date(e.uploadedAt).toLocaleDateString()}</td><td>${e.enabled?`Enabled`:`Disabled`}</td><td><button type="button" class="btn" aria-label="${`View ${e.filename}`}" @click="${()=>f(`manage-deduplication`,{linkId:e.id})}">View</button> <button type="button" class="btn" ?disabled="${this._busy}" aria-label="${`${e.enabled?`Disable`:`Enable`} ${e.filename}`}" @click="${()=>{this._toggle(e)}}">${e.enabled?`Disable`:`Enable`}</button></td></tr>`)}</tbody></table></div>`)}</div>`}};customElements.define(`managed-admin-deduplication`,qi);var Ji=[[75,`critical`],[50,`high`],[25,`moderate`],[0,`low`]],Yi=e=>Ji.find(([t])=>e>=t)[1],Xi={osv:`OSV`,repository:`The repository’s own GitHub advisories`,registry:`npm registry`,packagist:`Packagist`,rubysec:`RubySec`,dependabot:`Dependabot`},Zi=e=>e===`dependabot`?g(Ze):De(e),Qi={critical:`Critical`,high:`High`,moderate:`Moderate`,low:`Low`},$i=e=>typeof e==`string`&&/^GHSA(?:-[\da-z]{4}){3}$/iu.test(e),ea=e=>typeof e==`string`&&/^CVE-\d{4}-\d{4,}$/iu.test(e);function ta(e){if(!$i(e.id))return[e.id];let t=[...new Set((e.aliases??[]).filter(ea).map(e=>e.toUpperCase()))];return t.length>0?t:[e.id]}var na=e=>typeof e.url==`string`&&/^https:\/\//iu.test(e.url)?e.url:null;function ra(e,t){return new Set([e.id,...e.aliases??[]].filter($i).map(e=>e.toUpperCase())).size>1?`https://github.com/advisories?query=${encodeURIComponent(t)}`:na(e)}var ia=e=>[...new Set([...e.ranges??[],...e.range?[e.range]:[]].flatMap(e=>e.split(/\s*\|\|\s*/u)).filter(Boolean))];function aa(e,t=ta(e)[0]){let n=ia(e),r=[...new Set([e.id,...e.aliases??[]].filter(e=>typeof e==`string`).map(e=>ea(e)?e.toUpperCase():e))].filter(e=>e.toUpperCase()!==t.toUpperCase()),i=[...new Set((e.related??[]).filter(e=>typeof e==`string`))].filter(e=>!r.includes(e)&&e.toUpperCase()!==t.toUpperCase()),a=e.malware?`critical`:!e.unrated&&Object.hasOwn(Qi,e.severity)?e.severity:`unrated`,o=e.malware?`Malware`:e.informational?`${e.informational[0].toUpperCase()}${e.informational.slice(1)}`:null;return{meta:[t],chips:[...o?[{level:e.malware?`critical`:`unrated`,said:o}]:[],{level:a,said:`${Qi[a]??`Unrated`}${Number.isFinite(e.cvss)?`, CVSS ${e.cvss.toFixed(1)}`:``}`}],title:e.title||null,rows:[n.length>0?[`Affected`,n]:null,e.versions?.length?[`Versions`,e.versions.join(`, `)]:null,e.cwe?.length?[`CWE`,e.cwe.join(`, `)]:null,r.length>0?[`Also`,r]:null,i.length>0?[`Related`,i]:null].filter(Boolean),source:e.source?{said:Xi[e.source]??e.source,icon:Zi(e.source)}:null}}var oa=({meta:e,chips:t,title:n,rows:r,source:i})=>[[...e,...t.map(e=>e.said)].join(` · `),n,...r.map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(e===`Affected`?` || `:`, `):t}`),i&&`Source: ${i.said}`].filter(Boolean).join(`
20
20
  `),sa=({meta:e,chips:t,title:n,rows:r,source:i})=>y`<div class="advisory-tip"><div class="advisory-tip-head"><div class="advisory-tip-meta">${e.map(e=>y`<span>${e}</span>`)}</div><span class="advisory-tip-chips">${t.map(({level:e,said:t})=>y`<span class="${`advisory-tip-chip is-${e}`}">${t}</span>`)}</span></div>${n?y`<div class="advisory-tip-title">${n}</div>`:b} ${r.length>0||i?y`<div class="advisory-tip-rows">${r.map(([e,t])=>Array.isArray(t)?y`<span class="advisory-tip-label">${e}</span><div>${t.map(e=>y`<div class="advisory-tip-line">${e}</div>`)}</div>`:y`<span class="advisory-tip-label">${e}</span><span>${t}</span>`)}${i?y`<span class="advisory-tip-label">Source</span><span class="advisory-tip-source">${i.icon?y`<span class="advisory-tip-source-icon" aria-hidden="true">${i.icon}</span>`:b}${i.said}</span>`:b}</div>`:b}</div>`;function ca(e){let t=e.severity?`risk-${e.severity}`:``,n=n=>{let r=ea(n)?ra(e,n):na(e),i=aa(e,n);return r?y`<a class="${`risk-advisory ${t}`.trim()}" href="${r}" target="_blank" rel="noopener noreferrer" data-tooltip="${oa(i)}" .tooltipContent="${sa(i)}">${n}${Oe}</a>`:y`<span class="${`risk-advisory ${t}`.trim()}" data-tooltip="${oa(i)}" .tooltipContent="${sa(i)}">${n}</span>`},r=ta(e);return r.length===1?n(r[0]):y`<span class="risk-advisory-ids">${r.map(n)}</span>`}var la={unpinned:[`Unpinned`,`By a tag or a branch, which its repository’s owner can point anywhere, not a full commit sha.`],"short-sha":[`Short sha`,`A short sha, which GitHub reads as a branch or tag named so too.`],"unpinned-image":[`Image by tag`,`An image by a tag, which its publisher can move, not a digest.`],"fetched-package":[`Fetched package`,`A package fetched and run as it resolves now, past what a lockfile locks.`],"unlocked-install":[`Unlocked install`,`An install that resolves anew where package.json and the lockfile disagree; npm ci holds to the lockfile.`],"remote-script":[`Remote script`,`A script fetched and run as it is fetched.`],clone:[`Clone`,`A repository cloned at whatever its branch has.`],hosts:[`Host`,`A service malicious code sends what it takes to, or fetches what it runs from.`],"script-injection":[`Script injection`,`An expression anyone can write, in a script: what it holds runs as the script’s own code.`],"pwn-request":[`Runs a fork’s code`,`Checks out a pull request’s own code where the workflow runs with the base repository’s secrets.`],"untrusted-artifact":[`Untrusted artifact`,`Takes another run’s artifacts, which a fork’s pull request writes, where the workflow runs with secrets.`],"secrets-inherited":[`Inherits secrets`,`Another owner’s reusable workflow handed every secret.`],"invalid-uses":[`Invalid`,`A uses: GitHub can’t read.`],"deprecated-runtime":[`Old Node.js`,`A Node.js GitHub no longer runs actions on.`],"repo-missing":[`Repository missing`,`No such repository on GitHub: anyone who takes its owner’s name can publish one.`],"repo-moved":[`Repository moved`,`Renamed or transferred: GitHub redirects the old name until someone takes it.`],"repo-fork":[`Fork`,`A fork of another repository.`],"repo-archived":[`Archived`,`Archived by its owner.`],"branch-ref":[`Branch`,`A branch, which moves with every push.`],"ambiguous-ref":[`Tag and branch`,`A tag and a branch of the same name.`],"ref-missing":[`Ref missing`,`Neither a tag nor a branch: GitHub runs whichever is pushed first.`],"not-version":[`Not a version`,`A tag that is no version.`],"tag-off-release":[`Tag off release`,`A major or minor tag on a commit no release of its line is on, as a tag moved by whoever took the repository is.`],"tag-off-branch":[`Tag off branch`,`The tag’s commit is on none of its branches, as a release’s built files may be.`],outdated:[`Outdated`,`An older major version than the latest release.`],"imposter-commit":[`Imposter commit`,`In the history of none of the repository’s branches and releases: GitHub serves a fork’s commit under the name of the repository it forked.`],"unverified-commit":[`Unverified commit`,`In the history of none of the branches and releases looked at; it has more.`],"commit-missing":[`Commit missing`,`GitHub has no such commit.`],"untagged-commit":[`Untagged commit`,`A commit no tag names: no release.`],"comment-mismatch":[`Comment mismatch`,`The version or branch the comment beside it names isn’t this commit’s.`],"action-missing":[`No action.yml`,`No action.yml where it names, at the commit.`],unreadable:[`Unreadable`,`Its file couldn’t be read as GitHub reads it.`],advisory:[`Advisory`],"advisories-unavailable":[`Advisories unavailable`,`Its advisories couldn’t be had: asked again by the next scan.`]},ua={all:`All`,actions:`Actions`,steps:`Steps`},B=e=>Ce.includes(e)?Ce.indexOf(e):Ce.length,da=e=>e.reduce((e,{severity:t})=>B(t)<B(e)?t:e,null);function fa(e){return e.id===`hosts`?e.tag===`IP lookup`?e.tag:`${e.tag??``} host`.trimStart():e.id===`advisory`?e.advisory:la[e.id]?.[0]??e.id}function pa(e){let t=[];if(e.id===`fetched-package`&&t.push(ma(e),...e.localFirst?[e.locked?e.installed?``:`locked, but run before any install`:`no lockfile here locks it`]:[]),e.services&&t.push(e.services.join(`, `)),e.expression&&t.push(`\${{ ${e.expression} }}`),e.to&&t.push(`now ${e.to}`),e.parent&&t.push(`of ${e.parent}`),e.latest&&t.push(`latest ${e.latest}`),e.release&&t.push(`its line\u2019s latest release is ${e.release}`),e.comment){let n=e.tags?.length?`tags here: ${e.tags.join(`, `)}`:`no tag is on it`;t.push(`# ${e.comment}, ${e.branch?`not in the history of branch ${e.branch}; ${n}`:n}`)}return e.image&&t.push(e.image),e.file&&t.push(`in ${e.file}${e.line?`, line ${e.line}`:``}`),e.detail&&t.push(e.detail),[la[e.id]?.[1],...t.filter(Boolean)].filter(Boolean).join(`
21
- `)}function ma(e){return e.id===`fetched-package`?`${e.tool} ${e.name}${e.spec?`@${e.spec}`:``}`:e.id===`unlocked-install`?e.tool:e.id===`unpinned-image`?e.image:e.id===`clone`?`git clone ${e.url??``}`.trim():e.id===`hosts`?e.services.join(`, `):e.id===`script-injection`?`\${{ ${e.expression} }}`:e.id===`secrets-inherited`||e.id===`invalid-uses`?e.uses:e.id===`deprecated-runtime`?`runs.using: ${e.using}`:e.id===`remote-script`&&e.command?e.command:e.id===`pwn-request`&&e.ref?e.ref===`gh pr checkout`?e.ref:`actions/checkout ref: ${e.ref}`:fa(e)}var ha=class{constructor(){this.listed=new Map,this.files=new Map,this.actions=new Map,this.built=null}apply(e){this.built=null,e.type===`workflows`?(this.forget(e.repo),this.listed.set(e.repo,e)):e.type===`workflow`?(this.files.get(e.repo)??this.files.set(e.repo,new Map).get(e.repo)).set(e.path,e):e.type!==`action`||e.error&&this.actions.has(e.key)||this.actions.set(e.key,e)}forget(e){this.listed.delete(e),this.files.delete(e),this.built=null}filesOf(e){return[...this.files.get(e)?.values()??[]]}told(){return this.listed.size+this.rows(`actions`).filter(e=>e.line).length+[...this.files.values()].reduce((e,t)=>e+t.size,0)}counts(){let e=this.rows(`actions`);return{workflows:[...this.listed.values()].reduce((e,t)=>e+(t.paths?.length??0),0),workflowsRead:[...this.files.values()].reduce((e,t)=>e+[...t.values()].filter(e=>e.kind===`workflow`).length,0),actions:e.length,resolved:e.filter(e=>e.line).length}}#e(){let e=new Map,t=new Map,n=t=>e.get(t)??e.set(t,{key:t,kind:`action`,usedIn:[],local:[]}).get(t);for(let[e,r]of this.files)for(let i of r.values()){for(let t of i.uses??[])t.key&&Object.assign(n(t.key),{uses:t}).usedIn.push({repo:e,path:i.path,line:t.line});for(let r of i.findings??[]){if(r.key){n(r.key).local.push(r);continue}let a=ma(r),o=`${r.id}\0${r.tag??``}\0${a}`,s=t.get(o)??t.set(o,{key:o,kind:`step`,name:a,findings:[r],severity:r.severity,usedIn:[]}).get(o);B(r.severity)<B(s.severity)&&Object.assign(s,{severity:r.severity,findings:[r]}),s.usedIn.push({repo:e,path:i.path,line:r.line})}}let r=[...e.keys()];for(let t=0;t<r.length;t++)for(let i of this.actions.get(r[t])?.uses??[])e.has(i)||r.push(i),n(i).usedIn.push({via:r[t]});for(let t of e.values()){let e=new Map;t.line=this.actions.get(t.key)??null;for(let n of[...t.local,...t.line?.findings??[]]){let t=`${n.id}\0${ma(n)}\0${n.file??``}\0${n.file?n.line:``}`;(!e.has(t)||B(n.severity)<B(e.get(t).severity))&&e.set(t,n)}t.findings=[...e.values()],t.severity=da(t.findings)}let i=e=>e.findings.length>0?0:e.line?.error?1:e.line||e.kind===`step`?3:2;return[...e.values(),...t.values()].toSorted((e,t)=>B(e.severity)-B(t.severity)||i(e)-i(t)||t.findings.length-e.findings.length||(e.name??e.key).localeCompare(t.name??t.key))}rows(e,t=``){this.built??=this.#e();let n=t.trim().toLowerCase();return this.built.filter(t=>(e===`all`||e===`actions`==(t.kind===`action`))&&(!n||(t.name??t.key).toLowerCase().includes(n)))}};function ga(e){if(!e||e.error||!e.commit)return null;let t=e.commit.slice(0,7),n=e.tags?.length?` (${e.tags.join(`, `)})`:``;return e.at===`sha`?`${t}${n}`:`${e.at} \u2192 ${t}${n}`}function _a(e){return y`<ul class="risk-findings">${e.map(e=>e.id===`advisory`?y`<li class="${`risk-${e.severity}`}">${ca({...e,id:e.advisory})}</li>`:y`<li class="${`risk-${e.severity}`}" data-tooltip="${pa(e)||b}">${fa(e)}${e.file?y`<span class="risk-in-code">in code</span>`:b}</li>`)}</ul>`}function va({uses:e,line:t}){let n=t?.commit??e?.ref??t?.ref,r=t?.repository?.fullName??e?.repo??t?.repo;return r&&n?V(r,n,e?.path??t?.path,t?.kind===`workflow`||e?.kind===`workflow`?`blob`:`tree`):null}var V=(e,t,n,r=`blob`)=>`https://github.com/${e}/${r}/${encodeURIComponent(t)}${n?`/${Ve(n)}`:``}`,ya=`.wrap{max-width:none}.wrap>:not(.manage-list,.sr-only),.manage-list>.risk-files,.risk-section>:not(.link-table,.risk-results-head),.risk-results-head>*{max-width:var(--page-width);margin-left:max(0px,(100cqw - var(--page-width)) / 2)}.wrap.team-risk{--page-width: 100cqw}.wrap.team-risk .page-intro>.btn{margin-block:0}.risk-progress{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem 1.25rem;margin:0 0 1rem;color:var(--muted);font-size:.8rem}.risk-progress-line{display:flex;align-items:center;gap:.5rem 1.25rem;min-height:2.25rem;margin:0 0 1rem}.risk-progress-line>.risk-progress{flex:1;margin:0}.risk-files-toggle{position:relative;display:inline-grid;flex:none;place-items:center;width:2.25rem;height:2.25rem;padding:0;border:0;border-radius:var(--ui-radius, 6px);background:transparent;color:var(--muted)}.risk-files-toggle:hover,.risk-files-toggle[aria-expanded=true]{color:var(--text)}.risk-files-toggle:hover{background:var(--surface-active)}.risk-files-toggle .n{position:absolute;top:1px;right:1px;min-width:11px;padding:0 3px;border-radius:999px;background:color-mix(in srgb,var(--critical) 14%,var(--bg));color:var(--critical);font-size:8.5px;font-variant-numeric:tabular-nums;font-weight:600;line-height:11px;text-align:center}.risk-files-chevron{width:1.35rem;height:1.35rem;transition:transform .15s}.risk-files-toggle[aria-expanded=true] .risk-files-chevron{transform:rotate(180deg)}@media(prefers-reduced-motion:reduce){.risk-files-chevron{transition:none}}.risk-progress-idle{margin:0}.risk-state{display:inline-flex;align-items:center;gap:.4rem;margin-block:calc(-.15rem - 1px);margin-left:auto;padding:.15rem .6rem;border:1px solid var(--border);border-radius:999px;color:var(--text);font-weight:500;white-space:nowrap;user-select:none;-webkit-user-select:none}.risk-state:before{width:.5rem;height:.5rem;border-radius:50%;background:var(--muted);content:""}.risk-state[data-state=running]:before{background:var(--accent);animation:risk-pulse 1.4s ease-in-out infinite}.risk-state[data-state=done]:before{background:var(--green)}@keyframes risk-pulse{50%{opacity:.3}}@media(prefers-reduced-motion:reduce){.risk-state[data-state=running]:before{animation:none}}.risk-metric{display:grid;grid-template-columns:auto auto;justify-content:start;align-items:baseline;gap:.35rem .45rem;min-width:6rem;line-height:1}.risk-metric-label{font-size:.7rem;letter-spacing:.02em;text-transform:uppercase}.risk-metric-value{color:var(--text);font-size:.95rem;font-weight:600;font-variant-numeric:tabular-nums;white-space:nowrap}.risk-metric-value:not(:has(.risk-metric-of)){min-width:3ch}.risk-metric-of{color:var(--muted);font-weight:400}.risk-metric-slash{margin:0 .1em}.risk-metric.risk-high .risk-metric-value{color:var(--high)}.risk-bar{display:flex;grid-column:1 / -1;height:3px;overflow:hidden;border-radius:2px;background:var(--border)}.risk-bar>span{height:100%;transition:width .25s}.risk-bar-read{background:var(--accent)}.risk-bar-prod{background:color-mix(in srgb,var(--accent) 70%,var(--text))}.risk-bar-dev{background:color-mix(in srgb,var(--accent) 50%,var(--bg))}.risk-bar-malware{background:var(--critical)}.risk-section{margin-top:1rem}.risk-section:first-child{margin-top:0}.risk-files{margin-bottom:1rem;padding:.5rem .75rem .25rem;border:1px solid var(--border);border-radius:6px}.risk-files-head{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem .75rem;margin-bottom:.25rem}.risk-files-head .risk-tabs{margin-bottom:0}.risk-files-head h2{margin:0;font-size:.875rem;font-weight:600}.risk-files .risk-repos>li:last-child{border-bottom:0}.risk-results-head{position:sticky;top:0;z-index:1;padding-bottom:.25rem;background:var(--bg)}.risk-results-head .collection-toolbar,.risk-results-head .risk-tabs{margin-bottom:0}.risk-search{display:flex;flex:1 1 18rem;align-items:center;gap:.75rem;min-width:0}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}.risk-name,.risk-name:visited{color:var(--text)}.risk-name:hover{color:var(--accent);text-decoration:none}.risk-icon{display:inline-flex;flex:none;color:var(--muted)}.risk-icon svg{display:block;width:14px;height:14px}.risk-package,.risk-used,.risk-used-why{display:inline-flex;align-items:center;gap:.4rem;max-width:100%}.risk-version{color:var(--muted);font-variant-numeric:tabular-nums}.risk-package .risk-dev{margin-left:0}.risk-used .risk-clip{min-width:0}.risk-used-why{min-width:0;padding:0;border:0;font:inherit;background:none}.risk-used-external{display:inline-flex;flex:none;color:var(--muted)}.risk-used .external-link-icon{flex:none;opacity:.6}.risk-used-external:hover .external-link-icon,a.risk-used:hover .external-link-icon{color:var(--accent);opacity:1}.risk-used.is-dismissed,.risk-used.is-dismissed:visited{color:var(--muted)}.risk-used.is-dismissed .risk-used-in{text-decoration:line-through}.risk-name:hover .risk-icon{color:inherit}.risk-used-all summary{list-style:none}.risk-used-all summary::-webkit-details-marker{display:none}.risk-used-all summary:hover,.risk-used-all[open] summary{color:var(--accent)}.risk-used-lines{display:grid;gap:.15rem;margin:0;padding:0;list-style:none}.risk-used-all .risk-used-lines{margin-top:.25rem}.risk-repos{margin:0;padding:0;list-style:none;font-size:.8rem}.risk-repos>li{display:grid;grid-template-columns:minmax(8rem,16rem) 1fr;gap:.75rem;align-items:baseline;padding:.3rem 0;border-bottom:1px solid var(--border)}.risk-repo-name{overflow:hidden;font-weight:500;text-overflow:ellipsis;white-space:nowrap}.risk-lockfiles{display:flex;flex-wrap:wrap;gap:.15rem 1.5rem;margin:0;padding:0;list-style:none}.risk-lockfiles li{white-space:nowrap}.risk-lockfile-meta{margin-left:.5rem;color:var(--muted)}@container (max-width: 40rem){.risk-repos>li{grid-template-columns:1fr;gap:0}}th:last-child,td:last-child{text-align:left}td{padding-block:.35rem;vertical-align:top}.risk-used-column{width:100%}.risk-advisories :is(th,td){padding-inline:.375rem}.risk-advisories :is(th,td):first-child{padding-left:0}.risk-advisories :is(th,td):last-child{padding-right:0}.risk-versions{min-width:22ch;white-space:normal}.risk-pin{white-space:nowrap}.risk-clip{display:block;max-width:18rem;overflow:hidden;text-overflow:ellipsis}.risk-used-in{max-width:14rem}.risk-pending,.risk-none{color:var(--muted)}.risk-step{min-width:20rem;white-space:normal;overflow-wrap:anywhere}.risk-step .risk-package{align-items:flex-start}.risk-step .risk-icon{margin-top:.15em}.risk-dependabot,.risk-stasis{display:flex;flex-wrap:wrap;align-items:center;gap:.25rem .5rem;margin:.25rem 0 .5rem;color:var(--muted);font-size:.75rem}.risk-dependabot-failed{color:var(--high)}.risk-icon img{display:block;width:14px;height:14px}.risk-builds{flex:none;width:6rem;height:4px;overflow:hidden;border-radius:2px;background:var(--border)}.risk-builds>span{display:block;height:100%;background:var(--accent);transition:width .3s ease}.risk-builds-n{font-variant-numeric:tabular-nums}@media(prefers-reduced-motion:reduce){.risk-builds>span{transition:none}}.risk-error{color:var(--critical)}.risk-chip,.risk-score{display:inline-block;border-radius:999px;font-weight:600;color:var(--sev);background:color-mix(in srgb,var(--sev) 14%,transparent)}.risk-chip{padding:0 .45rem;white-space:nowrap}.risk-score{min-width:2.25rem;padding:0 .4rem;font-variant-numeric:tabular-nums;text-align:center}.risk-score.risk-low{color:var(--muted);background:none;font-weight:400}.is-stale .risk-score,.is-stale .risk-findings{opacity:.55}.risk-stale,.risk-dev{margin-left:.35rem;padding:0 .35rem;border:1px solid var(--border);border-radius:999px;color:var(--muted);font-size:.7rem}.risk-findings{display:flex;flex-wrap:wrap;width:max-content;max-width:24rem;gap:.25rem .75rem;margin:0;padding:0;list-style:none}.risk-findings li{color:var(--sev);white-space:nowrap}.risk-advisory{color:var(--sev, currentcolor);text-decoration:none;&:hover{text-decoration:underline}.external-link-icon{margin-left:.2em;vertical-align:-.05em;opacity:.6}&:hover .external-link-icon{opacity:1}}.risk-advisory-ids{display:inline-flex;flex-direction:column;align-items:flex-start;gap:.1rem;vertical-align:top}.risk-critical{--sev: var(--critical)}.risk-high{--sev: var(--high)}.risk-moderate{--sev: var(--yellow)}.risk-low,.risk-notice{--sev: var(--muted)}.risk-scope-bar{display:flex;flex-wrap:wrap;align-items:center;gap:.75rem;margin:0 0 1rem}.risk-scope,.risk-tabs{display:flex;gap:2px;padding:3px;border:1px solid var(--border);border-radius:var(--ui-radius, 6px);background:var(--bg)}.risk-scope button,.risk-tabs button{display:inline-flex;align-items:center;gap:.35rem;padding:.3rem .65rem;border:0;border-radius:var(--ui-radius, 3px);background:transparent;color:var(--muted);font-size:.75rem}.risk-scope button:hover:not(:disabled),.risk-tabs button:hover{background:var(--surface-active);color:var(--text)}.risk-scope button[aria-pressed=true],.risk-tabs button[aria-selected=true]{background:color-mix(in srgb,var(--accent) 15%,var(--bg));color:var(--accent)}.risk-scope button:focus-visible,.risk-tabs button:focus-visible{outline-offset:-1px}.risk-scope .n,.risk-tabs .n{align-self:flex-start;margin:-1px -5px 0;color:var(--muted);font-variant-numeric:tabular-nums;font-size:8.5px;font-weight:600;background:var(--bg);border-radius:999px;padding:0 3px;min-width:11px;text-align:center;line-height:11px}.risk-scope button[aria-pressed=true] .n,.risk-tabs button[aria-selected=true] .n{color:inherit}.risk-scope{flex-wrap:wrap;max-width:100%}.risk-scope-bar select{min-width:14rem}.risk-scope-bar repository-selector{flex:0 1 20rem;min-width:14rem}.risk-tabs{width:fit-content;margin-bottom:.5rem}.risk-in-code{margin-left:.3em;color:var(--muted);font-size:.9em}
22
- `,ba={malware:`Malware`,deprecated:`Deprecated`,publisher:`Publisher changed`,"provenance-lost":`Provenance lost`,"too-new":`Too new`,popularity:`Unpopular`,"held-install-scripts":`Install scripts`,"held-runs-code":`Runs code`,"held-credentials":`Credentials`,"held-exfiltration":`Exfiltration host`,"held-remote":`Remote host`,"held-ip-lookup":`IP lookup`,"held-obfuscated":`Obfuscated`,"held-symlinks":`Symlinks`,"held-non-registry-deps":`Non-registry dependencies`,"held-unused-deps":`Unused deps`,"large-code":`Large new code`,"now-unreadable":`Now unreadable`,"binary-code":`Binary code`,"new-hosts":`New hosts`},xa={"no-repository":`No GitHub access`,"github-not-found":`Not found on GitHub`,"github-unauthorized":`GitHub sign-in expired`,"github-rate-limited":`GitHub rate limit reached`,"github-unreachable":`GitHub unreachable`,"github-moved":`Moved on GitHub`,"github-malformed":`GitHub answered unexpectedly`,"unsupported-format":`Format not read`,"lockfile-unreadable":`Unreadable`,"package-not-found":`Not on npm`,"version-not-found":`Version not on npm`,"integrity-mismatch":`Differs from npm’s`,"npm-busy":`Server busy`,"package-too-large":`Too large to assess`,"upstream-busy":`npm busy`,"upstream-unavailable":`npm unavailable`,"upstream-too-large":`npm answered too much`,"upstream-invalid":`npm answered unexpectedly`,"dependabot-disabled":`Dependabot alerts off`,"dependabot-forbidden":`No access to Dependabot alerts`,"dependabot-app-permission":`App lacks Dependabot alerts permission`,"dependabot-not-installed":`App not installed`,"dependabot-unverified":`Sign-in not verified, sign in again`,"github-app-not-configured":`GitHub App not configured`,"workflow-unreadable":`Unreadable`,"workflow-too-large":`Too large to read`,"invalid-uses":`Not a reference GitHub reads`,"stasis-failed":`Stasis build failed`,"no-config":`No longer at this commit`,"github-token-required":`GitHub sign-in required`},H=e=>xa[e]??e,U=({error:e,detail:t})=>y`<span class="risk-error" data-tooltip="${t??b}">${H(e)}</span>`,Sa={401:`Sign in again to scan repositories.`,403:`Only admins can scan repositories.`,404:`That team or repository is no longer connected. Choose again.`},Ca={...Sa,403:`Only the team’s managers and admins can scan its risk.`,404:`This team is no longer listed.`},wa=e=>e?.team?{team:e.team}:{},Ta=[[`all`,`All repositories`],[`team`,`Team`],[`repo`,`Repository`]],Ea=5,Da={registry:`npm`,mirror:`Mirror`,git:`Git`,tarball:`Tarball`,file:`File`},W=e=>e===`registry`||e===`mirror`,G=e=>K(e)?null:e.malware??null,K=e=>e.risk?.error===`integrity-mismatch`,Oa=e=>G(e)||K(e)?`critical`:e.risk?.severity??null,ka=e=>G(e)?100:e.risk&&!e.risk.error?e.risk.score??null:null,Aa=e=>{let t=e.risk?.findings??[];return G(e)?[{id:`malware`,severity:`critical`},...t.filter(({id:e})=>e!==`malware`)]:t},ja=e=>[...G(e)??[],...e.risk?.findings?.some(({id:e,takenDown:t})=>e===`malware`&&t)?[`Taken down by npm`]:[]],Ma=e=>Aa(e).some(({id:e})=>e===`malware`),Na=e=>K(e)||Ma(e),q=({name:e,version:t})=>`${e}@${t}`,Pa=(e,t,n)=>{let r=[...e].filter(e=>n.at.get(e)?.has(t));return r.length>0?r:[...e]},Fa=(e,t,n)=>t===`all`||Na(e)||(t===`stasis`?n.versions.has(q(e)):!!e.dev==(t===`development`)),Ia=(e,t,n)=>Na(e)?e.usedIn:t===`production`?e.neededIn:t===`stasis`?Pa(e.usedIn,q(e),n):e.usedIn,La=e=>`${e[0].toUpperCase()}${e.slice(1)}`,Ra=e=>!!e.risk?.error&&!K(e),za={all:[`All`,()=>!0],flagged:[`Flagged`,e=>!!Oa(e)||Ra(e)],failed:[`Failed`,Ra],elsewhere:[`Not from npm`,e=>!W(e.source)]},Ba=`Out of 100: what its findings call for, lowered by how long the version has been out among how many download its package. Malware is 100.`,Va=`Only devDependencies need it, in every lockfile that locks it: an install without them leaves it out. Assessed after the rest, unless a Stasis build installs it.`,Ha=`Only devDependencies need these versions, in every lockfile that locks them: an install without them leaves them out.`,Ua=`Its lockfile’s integrity, a mirror’s, isn’t npm’s of this name and version: not npm’s package, as a private one of a public one’s name is, or one tampered with.`,Wa={all:`All`,production:`Prod`,development:`Dev`},Ga={...Wa,actions:`Actions`},Ka={all:[`All`,()=>!0],flagged:[`Flagged`,e=>e.findings.length>0||!!e.line?.error]},qa=e=>e===`running`?`None flagged yet.`:`None flagged.`,Ja=(e,t)=>t?Object.fromEntries(Object.entries(e).flatMap(e=>e[0]===`production`?[[`stasis`,`Stasis`],e]:[e])):e,Ya=3e4,Xa=50,Za=e=>({path:e.path,dependencies:e.dependencies??null,pending:e.pending===!0,error:e.error??null,detail:e.detail??null,lockfiles:e.lockfiles??null}),Qa=e=>y`<span class="risk-dev" data-tooltip="${e}">dev</span>`;function $a({name:e,source:t,dev:n},r,i,a){let o=y`${e}${r?y`<span class="risk-version">@${r}</span>`:b}`;return y`<span class="risk-package">${Y(W(t)?Xe:Ye)}${i?y`<a class="risk-name" href="${i}">${o}</a>`:y`<span>${o}</span>`}${n?Qa(a):b}</span>`}var eo=e=>!e.error||e.error===`integrity-mismatch`;function to(e,t){let n=e.stale??null;return!eo(e)&&!n&&t?.stale&&eo(t)?{...t,refreshFailed:e.detail?`${H(e.error)}: ${e.detail}`:H(e.error)}:e.error?{error:e.error,detail:e.detail??null,stale:n}:{severity:e.severity,score:e.score??null,findings:e.findings,published:e.published,stale:n}}var no=new Intl.RelativeTimeFormat(`en`,{numeric:`auto`});function ro(e,t=Date.now()){let n=Math.round((e-t)/6e4);if(Math.abs(n)<60)return no.format(n,`minute`);let r=Math.round(n/60);return Math.abs(r)<48?no.format(r,`hour`):no.format(Math.round(r/24),`day`)}var io=100,ao=3,oo=5e3,so=250,J=new Intl.NumberFormat,co=e=>({total:e.length,told:e.filter(e=>e.risk).length,flagged:e.filter(Oa).length,stale:e.filter(e=>e.risk?.stale).length,wasStale:e.filter(e=>e.wasStale).length}),Y=e=>y`<span class="risk-icon" aria-hidden="true">${g(e)}</span>`,lo={fix_started:`A fix has already been started`,inaccurate:`This alert is inaccurate or incorrect`,no_bandwidth:`No bandwidth to fix this`,not_used:`Vulnerable code is not actually used`,tolerable_risk:`Risk is tolerable to this project`};function uo({number:e,dismissed:t}){if(!t)return`Dependabot alert #${e}`;let n=t.auto?`auto-dismissed by a rule`:`dismissed${lo[t.reason]?`: ${lo[t.reason]}`:``}`,r=[t.by?`by @${t.by}`:``,t.at?.slice(0,10)??``].filter(Boolean).join(`, `);return[`Dependabot alert #${e}, ${n}${r?` (${r})`:``}`,...t.comment?[`\u201C${t.comment}\u201D`]:[]].join(`
23
- `)}var X=ke({page:null});function fo(e,{repoId:t,commit:n,path:r,format:i},a,o){let s=X.page,c=A(`/api/admin/repositories/risk/lockfile?${new URLSearchParams({repoId:t,commit:n,path:r,...wa(s)})}`,{"github-not-found":`GitHub has it no longer.`},e=>e.json()).then(async({text:e,manifest:t})=>{let[{readLockfile:n},{lockfileWhy:r}]=await Promise.all([import(`./chunk-QBFT2DDR.js`),import(`./chunk-SSPDMA6D.js`)]);return r(await n(i,e,{manifest:t,env:!0}),{name:a,versions:o})});Ee({lockfile:e,packageKey:a,version:o.length===1?o[0]:void 0,load:c,isCurrent:()=>X.page===s})}function po(e,t,n,r){let i=n?.get(e);if(i&&nt(i.url))return y`<a class="${i.dismissed?`risk-name risk-used is-dismissed`:`risk-name risk-used`}" href="${i.url}" target="_blank" rel="noopener noreferrer">${Y(Ze)}<span class="risk-clip risk-used-in" data-tooltip="${`${e}
21
+ `)}function ma(e){return e.id===`fetched-package`?`${e.tool} ${e.name}${e.spec?`@${e.spec}`:``}`:e.id===`unlocked-install`?e.tool:e.id===`unpinned-image`?e.image:e.id===`clone`?`git clone ${e.url??``}`.trim():e.id===`hosts`?e.services.join(`, `):e.id===`script-injection`?`\${{ ${e.expression} }}`:e.id===`secrets-inherited`||e.id===`invalid-uses`?e.uses:e.id===`deprecated-runtime`?`runs.using: ${e.using}`:e.id===`remote-script`&&e.command?e.command:e.id===`pwn-request`&&e.ref?e.ref===`gh pr checkout`?e.ref:`actions/checkout ref: ${e.ref}`:fa(e)}var ha=class{constructor(){this.listed=new Map,this.files=new Map,this.actions=new Map,this.built=null}apply(e){this.built=null,e.type===`workflows`?(this.forget(e.repo),this.listed.set(e.repo,e)):e.type===`workflow`?(this.files.get(e.repo)??this.files.set(e.repo,new Map).get(e.repo)).set(e.path,e):e.type!==`action`||e.error&&this.actions.has(e.key)||this.actions.set(e.key,e)}forget(e){this.listed.delete(e),this.files.delete(e),this.built=null}filesOf(e){return[...this.files.get(e)?.values()??[]]}told(){return this.listed.size+this.rows(`actions`).filter(e=>e.line).length+[...this.files.values()].reduce((e,t)=>e+t.size,0)}counts(){let e=this.rows(`actions`);return{workflows:[...this.listed.values()].reduce((e,t)=>e+(t.paths?.length??0),0),workflowsRead:[...this.files.values()].reduce((e,t)=>e+[...t.values()].filter(e=>e.kind===`workflow`).length,0),actions:e.length,resolved:e.filter(e=>e.line).length}}#e(){let e=new Map,t=new Map,n=t=>e.get(t)??e.set(t,{key:t,kind:`action`,usedIn:[],local:[]}).get(t);for(let[e,r]of this.files)for(let i of r.values()){for(let t of i.uses??[])t.key&&Object.assign(n(t.key),{uses:t}).usedIn.push({repo:e,path:i.path,line:t.line});for(let r of i.findings??[]){if(r.key){n(r.key).local.push(r);continue}let a=ma(r),o=`${r.id}\0${r.tag??``}\0${a}`,s=t.get(o)??t.set(o,{key:o,kind:`step`,name:a,findings:[r],severity:r.severity,usedIn:[]}).get(o);B(r.severity)<B(s.severity)&&Object.assign(s,{severity:r.severity,findings:[r]}),s.usedIn.push({repo:e,path:i.path,line:r.line})}}let r=[...e.keys()];for(let t=0;t<r.length;t++)for(let i of this.actions.get(r[t])?.uses??[])e.has(i)||r.push(i),n(i).usedIn.push({via:r[t]});for(let t of e.values()){let e=new Map;t.line=this.actions.get(t.key)??null;for(let n of[...t.local,...t.line?.findings??[]]){let t=`${n.id}\0${ma(n)}\0${n.file??``}\0${n.file?n.line:``}`;(!e.has(t)||B(n.severity)<B(e.get(t).severity))&&e.set(t,n)}t.findings=[...e.values()],t.severity=da(t.findings)}let i=e=>e.findings.length>0?0:e.line?.error?1:e.line||e.kind===`step`?3:2;return[...e.values(),...t.values()].toSorted((e,t)=>B(e.severity)-B(t.severity)||i(e)-i(t)||t.findings.length-e.findings.length||(e.name??e.key).localeCompare(t.name??t.key))}rows(e,t=``){this.built??=this.#e();let n=t.trim().toLowerCase();return this.built.filter(t=>(e===`all`||e===`actions`==(t.kind===`action`))&&(!n||(t.name??t.key).toLowerCase().includes(n)))}};function ga(e){if(!e||e.error||!e.commit)return null;let t=e.commit.slice(0,7),n=e.tags?.length?` (${e.tags.join(`, `)})`:``;return e.at===`sha`?`${t}${n}`:`${e.at} \u2192 ${t}${n}`}function _a(e){return y`<ul class="risk-findings">${e.map(e=>e.id===`advisory`?y`<li class="${`risk-${e.severity}`}">${ca({...e,id:e.advisory})}</li>`:y`<li class="${`risk-${e.severity}`}" data-tooltip="${pa(e)||b}">${fa(e)}${e.file?y`<span class="risk-in-code">in code</span>`:b}</li>`)}</ul>`}function va({uses:e,line:t}){let n=t?.commit??e?.ref??t?.ref,r=t?.repository?.fullName??e?.repo??t?.repo;return r&&n?V(r,n,e?.path??t?.path,t?.kind===`workflow`||e?.kind===`workflow`?`blob`:`tree`):null}var V=(e,t,n,r=`blob`)=>`https://github.com/${e}/${r}/${encodeURIComponent(t)}${n?`/${Ve(n)}`:``}`,ya=`.wrap{max-width:none}.wrap>:not(.manage-list,.sr-only),.manage-list>.risk-files,.risk-section>:not(.link-table,.risk-results-head),.risk-results-head>*{max-width:var(--page-width);margin-left:max(0px,(100cqw - var(--page-width)) / 2)}.wrap.team-risk{--page-width: 100cqw}.wrap.team-risk .page-intro>.btn{margin-block:0}.risk-progress{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem 1.25rem;margin:0 0 1rem;color:var(--muted);font-size:.8rem}.risk-progress-line{display:flex;align-items:center;gap:.5rem 1.25rem;min-height:2.25rem;margin:0 0 1rem}.risk-progress-line>.risk-progress{flex:1;margin:0}.risk-files-toggle{position:relative;display:inline-grid;flex:none;place-items:center;width:2.25rem;height:2.25rem;padding:0;border:0;border-radius:var(--ui-radius, 6px);background:transparent;color:var(--muted)}.risk-files-toggle:hover,.risk-files-toggle[aria-expanded=true]{color:var(--text)}.risk-files-toggle:hover{background:var(--surface-active)}.risk-files-toggle .n{position:absolute;top:1px;right:1px;min-width:11px;padding:0 3px;border-radius:999px;background:color-mix(in srgb,var(--critical) 14%,var(--bg));color:var(--critical);font-size:8.5px;font-variant-numeric:tabular-nums;font-weight:600;line-height:11px;text-align:center}.risk-files-chevron{width:1.35rem;height:1.35rem;transition:transform .15s}.risk-files-toggle[aria-expanded=true] .risk-files-chevron{transform:rotate(180deg)}@media(prefers-reduced-motion:reduce){.risk-files-chevron{transition:none}}.risk-progress-idle{margin:0}.risk-state{display:inline-flex;align-items:center;gap:.4rem;margin-block:calc(-.15rem - 1px);margin-left:auto;padding:.15rem .6rem;border:1px solid var(--border);border-radius:999px;color:var(--text);font-weight:500;white-space:nowrap;user-select:none;-webkit-user-select:none}.risk-state:before{width:.5rem;height:.5rem;border-radius:50%;background:var(--muted);content:""}.risk-state[data-state=running]:before{background:var(--accent);animation:risk-pulse 1.4s ease-in-out infinite}.risk-state[data-state=done]:before{background:var(--green)}@keyframes risk-pulse{50%{opacity:.3}}@media(prefers-reduced-motion:reduce){.risk-state[data-state=running]:before{animation:none}}.risk-metric{display:grid;grid-template-columns:auto auto;justify-content:start;align-items:baseline;gap:.35rem .45rem;min-width:6rem;line-height:1}.risk-metric-label{font-size:.7rem;letter-spacing:.02em;text-transform:uppercase}.risk-metric-value{color:var(--text);font-size:.95rem;font-weight:600;font-variant-numeric:tabular-nums;white-space:nowrap}.risk-metric-value:not(:has(.risk-metric-of)){min-width:3ch}.risk-metric-of{color:var(--muted);font-weight:400}.risk-metric-slash{margin:0 .1em}.risk-metric.risk-high .risk-metric-value{color:var(--high)}.risk-bar{display:flex;grid-column:1 / -1;height:3px;overflow:hidden;border-radius:2px;background:var(--border)}.risk-bar>span{height:100%;transition:width .25s}.risk-bar-read{background:var(--accent)}.risk-bar-prod{background:color-mix(in srgb,var(--accent) 70%,var(--text))}.risk-bar-dev{background:color-mix(in srgb,var(--accent) 50%,var(--bg))}.risk-bar-malware{background:var(--critical)}.risk-section{margin-top:1rem}.risk-section:first-child{margin-top:0}.risk-files{margin-bottom:1rem;padding:.5rem .75rem .25rem;border:1px solid var(--border);border-radius:6px}.risk-files-head{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem .75rem;margin-bottom:.25rem}.risk-files-head .risk-tabs{margin-bottom:0}.risk-files-head h2{margin:0;font-size:.875rem;font-weight:600}.risk-files .risk-repos>li:last-child{border-bottom:0}.risk-results-head{position:sticky;top:0;z-index:1;padding-bottom:.25rem;background:var(--bg)}.risk-results-head .collection-toolbar,.risk-results-head .risk-tabs{margin-bottom:0}.risk-search{display:flex;flex:1 1 18rem;align-items:center;gap:.75rem;min-width:0}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}.risk-name,.risk-name:visited{color:var(--text)}.risk-name:hover{color:var(--accent);text-decoration:none}.risk-icon{display:inline-flex;flex:none;color:var(--muted)}.risk-icon svg{display:block;width:14px;height:14px}.risk-package,.risk-used,.risk-used-why{display:inline-flex;align-items:center;gap:.4rem;max-width:100%}.risk-version{color:var(--muted);font-variant-numeric:tabular-nums}.risk-package .risk-dev{margin-left:0}.risk-package-name{width:max-content;max-width:26ch;white-space:normal;overflow-wrap:break-word}.risk-used .risk-clip{min-width:0}.risk-used-why{min-width:0;padding:0;border:0;font:inherit;background:none}.risk-used-external{display:inline-flex;flex:none;color:var(--muted)}.risk-used .external-link-icon{flex:none;opacity:.6}.risk-used-external:hover .external-link-icon,a.risk-used:hover .external-link-icon{color:var(--accent);opacity:1}.risk-used.is-dismissed,.risk-used.is-dismissed:visited{color:var(--muted)}.risk-used.is-dismissed .risk-used-in{text-decoration:line-through}.risk-name:hover .risk-icon{color:inherit}.risk-used-all summary{list-style:none}.risk-used-all summary::-webkit-details-marker{display:none}.risk-used-all summary:hover,.risk-used-all[open] summary{color:var(--accent)}.risk-used-lines{display:grid;gap:.15rem;margin:0;padding:0;list-style:none}.risk-used-all .risk-used-lines{margin-top:.25rem}.risk-repos{margin:0;padding:0;list-style:none;font-size:.8rem}.risk-repos>li{display:grid;grid-template-columns:minmax(8rem,16rem) 1fr;gap:.75rem;align-items:baseline;padding:.3rem 0;border-bottom:1px solid var(--border)}.risk-repo-name{overflow:hidden;font-weight:500;text-overflow:ellipsis;white-space:nowrap}.risk-lockfiles{display:flex;flex-wrap:wrap;gap:.15rem 1.5rem;margin:0;padding:0;list-style:none}.risk-lockfiles li{white-space:nowrap}.risk-lockfile-meta{margin-left:.5rem;color:var(--muted)}@container (max-width: 40rem){.risk-repos>li{grid-template-columns:1fr;gap:0}}th:last-child,td:last-child{text-align:left}td{padding-block:.35rem;vertical-align:top}.risk-used-column{width:100%}.risk-advisories :is(th,td){padding-inline:.375rem}.risk-advisories :is(th,td):first-child{padding-left:0}.risk-advisories :is(th,td):last-child{padding-right:0}.risk-versions{width:calc(22ch + .75rem);min-width:calc(22ch + .75rem);max-width:calc(22ch + .75rem);white-space:normal}.risk-pin{white-space:nowrap}.risk-clip{display:block;max-width:18rem;overflow:hidden;text-overflow:ellipsis}.risk-used-in{max-width:14rem}.risk-pending,.risk-none{color:var(--muted)}.risk-step{min-width:20rem;white-space:normal;overflow-wrap:anywhere}.risk-step .risk-package{align-items:flex-start}.risk-step .risk-icon{margin-top:.15em}.risk-dependabot,.risk-stasis{display:flex;flex-wrap:wrap;align-items:center;gap:.25rem .5rem;margin:.25rem 0 .5rem;color:var(--muted);font-size:.75rem}.risk-dependabot-failed{color:var(--high)}.risk-icon img{display:block;width:14px;height:14px}.risk-builds{flex:none;width:6rem;height:4px;overflow:hidden;border-radius:2px;background:var(--border)}.risk-builds>span{display:block;height:100%;background:var(--accent);transition:width .3s ease}.risk-builds-n{font-variant-numeric:tabular-nums}@media(prefers-reduced-motion:reduce){.risk-builds>span{transition:none}}.risk-error{color:var(--critical)}.risk-chip,.risk-score{display:inline-block;border-radius:999px;font-weight:600;color:var(--sev);background:color-mix(in srgb,var(--sev) 14%,transparent)}.risk-chip{padding:0 .45rem;white-space:nowrap}.risk-score{min-width:2.25rem;padding:0 .4rem;font-variant-numeric:tabular-nums;text-align:center}.risk-score.risk-low{color:var(--muted);background:none;font-weight:400}.is-stale .risk-score,.is-stale .risk-findings{opacity:.55}.risk-stale,.risk-dev{margin-left:.35rem;padding:0 .35rem;border:1px solid var(--border);border-radius:999px;color:var(--muted);font-size:.7rem}.risk-findings{display:flex;flex-wrap:wrap;width:max-content;max-width:24rem;gap:.25rem .75rem;margin:0;padding:0;list-style:none}.risk-findings li{color:var(--sev);white-space:nowrap}.risk-advisory{color:var(--sev, currentcolor);text-decoration:none;&:hover{text-decoration:underline}.external-link-icon{margin-left:.2em;vertical-align:-.05em;opacity:.6}&:hover .external-link-icon{opacity:1}}.risk-advisory-ids{display:inline-flex;flex-direction:column;align-items:flex-start;gap:.1rem;vertical-align:top}.risk-critical{--sev: var(--critical)}.risk-high{--sev: var(--high)}.risk-moderate{--sev: var(--yellow)}.risk-low,.risk-notice{--sev: var(--muted)}.risk-scope-bar{display:flex;flex-wrap:wrap;align-items:center;gap:.75rem;margin:0 0 1rem}.risk-scope,.risk-tabs{display:flex;gap:2px;padding:3px;border:1px solid var(--border);border-radius:var(--ui-radius, 6px);background:var(--bg)}.risk-scope button,.risk-tabs button{display:inline-flex;align-items:center;gap:.35rem;padding:.3rem .65rem;border:0;border-radius:var(--ui-radius, 3px);background:transparent;color:var(--muted);font-size:.75rem}.risk-scope button:hover:not(:disabled),.risk-tabs button:hover{background:var(--surface-active);color:var(--text)}.risk-scope button[aria-pressed=true],.risk-tabs button[aria-selected=true]{background:color-mix(in srgb,var(--accent) 15%,var(--bg));color:var(--accent)}.risk-scope button:focus-visible,.risk-tabs button:focus-visible{outline-offset:-1px}.risk-scope .n,.risk-tabs .n{align-self:flex-start;margin:-1px -5px 0;color:var(--muted);font-variant-numeric:tabular-nums;font-size:8.5px;font-weight:600;background:var(--bg);border-radius:999px;padding:0 3px;min-width:11px;text-align:center;line-height:11px}.risk-scope button[aria-pressed=true] .n,.risk-tabs button[aria-selected=true] .n{color:inherit}.risk-scope{flex-wrap:wrap;max-width:100%}.risk-scope-bar select{min-width:14rem}.risk-scope-bar repository-selector{flex:0 1 20rem;min-width:14rem}.risk-tabs{width:fit-content;margin-bottom:.5rem}.risk-in-code{margin-left:.3em;color:var(--muted);font-size:.9em}
22
+ `,ba={malware:`Malware`,deprecated:`Deprecated`,publisher:`Publisher changed`,"provenance-lost":`Provenance lost`,"too-new":`Too new`,popularity:`Unpopular`,"held-install-scripts":`Install scripts`,"held-runs-code":`Runs code`,"held-credentials":`Credentials`,"held-exfiltration":`Exfiltration host`,"held-remote":`Remote host`,"held-ip-lookup":`IP lookup`,"held-obfuscated":`Obfuscated`,"held-symlinks":`Symlinks`,"held-non-registry-deps":`Non-registry dependencies`,"held-unused-deps":`Unused deps`,"large-code":`Large new code`,"now-unreadable":`Now unreadable`,"binary-code":`Binary code`,"new-hosts":`New hosts`},xa={"no-repository":`No GitHub access`,"github-not-found":`Not found on GitHub`,"github-unauthorized":`GitHub sign-in expired`,"github-rate-limited":`GitHub rate limit reached`,"github-unreachable":`GitHub unreachable`,"github-moved":`Moved on GitHub`,"github-malformed":`GitHub answered unexpectedly`,"unsupported-format":`Format not read`,"lockfile-unreadable":`Unreadable`,"package-not-found":`Not on npm`,"version-not-found":`Version not on npm`,"integrity-mismatch":`Differs from npm’s`,"npm-busy":`Server busy`,"package-too-large":`Too large to assess`,"upstream-busy":`npm busy`,"upstream-unavailable":`npm unavailable`,"upstream-too-large":`npm answered too much`,"upstream-invalid":`npm answered unexpectedly`,"dependabot-disabled":`Dependabot alerts off`,"dependabot-forbidden":`No access to Dependabot alerts`,"dependabot-app-permission":`App lacks Dependabot alerts permission`,"dependabot-not-installed":`App not installed`,"dependabot-unverified":`Sign-in not verified, sign in again`,"github-app-not-configured":`GitHub App not configured`,"workflow-unreadable":`Unreadable`,"workflow-too-large":`Too large to read`,"invalid-uses":`Not a reference GitHub reads`,"stasis-failed":`Stasis build failed`,"no-config":`No longer at this commit`,"github-token-required":`GitHub sign-in required`},H=e=>xa[e]??e,U=({error:e,detail:t})=>y`<span class="risk-error" data-tooltip="${t??b}">${H(e)}</span>`,Sa={401:`Sign in again to scan repositories.`,403:`Only admins can scan repositories.`,404:`That team or repository is no longer connected. Choose again.`},Ca={...Sa,403:`Only the team’s managers and admins can scan its risk.`,404:`This team is no longer listed.`},wa=e=>e?.team?{team:e.team}:{},Ta=[[`all`,`All repositories`],[`team`,`Team`],[`repo`,`Repository`]],Ea=5,Da={registry:`npm`,mirror:`Mirror`,git:`Git`,tarball:`Tarball`,file:`File`},W=e=>e===`registry`||e===`mirror`,G=e=>K(e)?null:e.malware??null,K=e=>e.risk?.error===`integrity-mismatch`,Oa=e=>G(e)||K(e)?`critical`:e.risk?.severity??null,ka=e=>G(e)?100:e.risk&&!e.risk.error?e.risk.score??null:null,Aa=e=>{let t=e.risk?.findings??[];return G(e)?[{id:`malware`,severity:`critical`},...t.filter(({id:e})=>e!==`malware`)]:t},ja=e=>[...G(e)??[],...e.risk?.findings?.some(({id:e,takenDown:t})=>e===`malware`&&t)?[`Taken down by npm`]:[]],Ma=e=>Aa(e).some(({id:e})=>e===`malware`),Na=e=>K(e)||Ma(e),q=({name:e,version:t})=>`${e}@${t}`,Pa=(e,t,n)=>{let r=[...e].filter(e=>n.at.get(e)?.has(t));return r.length>0?r:[...e]},Fa=(e,t,n)=>t===`all`||Na(e)||(t===`stasis`?n.versions.has(q(e)):!!e.dev==(t===`development`)),Ia=(e,t,n)=>Na(e)?e.usedIn:t===`production`?e.neededIn:t===`stasis`?Pa(e.usedIn,q(e),n):e.usedIn,La=e=>`${e[0].toUpperCase()}${e.slice(1)}`,Ra=e=>!!e.risk?.error&&!K(e),za={all:[`All`,()=>!0],flagged:[`Flagged`,e=>!!Oa(e)||Ra(e)],failed:[`Failed`,Ra],elsewhere:[`Not from npm`,e=>!W(e.source)]},Ba=`Out of 100: what its findings call for, lowered by how long the version has been out among how many download its package. Malware is 100.`,Va=`Only devDependencies need it, in every lockfile that locks it: an install without them leaves it out. Assessed after the rest, unless a Stasis build installs it.`,Ha=`Only devDependencies need these versions, in every lockfile that locks them: an install without them leaves them out.`,Ua=`Its lockfile’s integrity, a mirror’s, isn’t npm’s of this name and version: not npm’s package, as a private one of a public one’s name is, or one tampered with.`,Wa={all:`All`,production:`Prod`,development:`Dev`},Ga={...Wa,actions:`Actions`},Ka={all:[`All`,()=>!0],flagged:[`Flagged`,e=>e.findings.length>0||!!e.line?.error]},qa=e=>e===`running`?`None flagged yet.`:`None flagged.`,Ja=(e,t)=>t?Object.fromEntries(Object.entries(e).flatMap(e=>e[0]===`production`?[[`stasis`,`Stasis`],e]:[e])):e,Ya=3e4,Xa=50,Za=e=>({path:e.path,dependencies:e.dependencies??null,pending:e.pending===!0,error:e.error??null,detail:e.detail??null,lockfiles:e.lockfiles??null}),Qa=e=>y`<span class="risk-dev" data-tooltip="${e}">dev</span>`;function $a({name:e,source:t,dev:n},r,i,a){let o=y`${e}${r?y`<span class="risk-version">@${r}</span>`:b}`;return y`<span class="risk-package">${Y(W(t)?Xe:Ye)}${i?y`<a class="risk-name risk-package-name" href="${i}">${o}</a>`:y`<span class="risk-package-name">${o}</span>`}${n?Qa(a):b}</span>`}var eo=e=>!e.error||e.error===`integrity-mismatch`;function to(e,t){let n=e.stale??null;return!eo(e)&&!n&&t?.stale&&eo(t)?{...t,refreshFailed:e.detail?`${H(e.error)}: ${e.detail}`:H(e.error)}:e.error?{error:e.error,detail:e.detail??null,stale:n}:{severity:e.severity,score:e.score??null,findings:e.findings,published:e.published,stale:n}}var no=new Intl.RelativeTimeFormat(`en`,{numeric:`auto`});function ro(e,t=Date.now()){let n=Math.round((e-t)/6e4);if(Math.abs(n)<60)return no.format(n,`minute`);let r=Math.round(n/60);return Math.abs(r)<48?no.format(r,`hour`):no.format(Math.round(r/24),`day`)}var io=100,ao=3,oo=5e3,so=250,J=new Intl.NumberFormat,co=e=>({total:e.length,told:e.filter(e=>e.risk).length,flagged:e.filter(Oa).length,stale:e.filter(e=>e.risk?.stale).length,wasStale:e.filter(e=>e.wasStale).length}),Y=e=>y`<span class="risk-icon" aria-hidden="true">${g(e)}</span>`,lo={fix_started:`A fix has already been started`,inaccurate:`This alert is inaccurate or incorrect`,no_bandwidth:`No bandwidth to fix this`,not_used:`Vulnerable code is not actually used`,tolerable_risk:`Risk is tolerable to this project`};function uo({number:e,dismissed:t}){if(!t)return`Dependabot alert #${e}`;let n=t.auto?`auto-dismissed by a rule`:`dismissed${lo[t.reason]?`: ${lo[t.reason]}`:``}`,r=[t.by?`by @${t.by}`:``,t.at?.slice(0,10)??``].filter(Boolean).join(`, `);return[`Dependabot alert #${e}, ${n}${r?` (${r})`:``}`,...t.comment?[`\u201C${t.comment}\u201D`]:[]].join(`
23
+ `)}var X=ke({page:null});function fo(e,{repoId:t,commit:n,path:r,format:i},a,o){let s=X.page,c=A(`/api/admin/repositories/risk/lockfile?${new URLSearchParams({repoId:t,commit:n,path:r,...wa(s)})}`,{"github-not-found":`GitHub has it no longer.`},e=>e.json()).then(async({text:e,manifest:t})=>{let[{readLockfile:n},{lockfileWhy:r}]=await Promise.all([import(`./chunk-UR4WYMIP.js`),import(`./chunk-SSPDMA6D.js`)]);return r(await n(i,e,{manifest:t,env:!0}),{name:a,versions:o})});Ee({lockfile:e,packageKey:a,version:o.length===1?o[0]:void 0,load:c,isCurrent:()=>X.page===s})}function po(e,t,n,r){let i=n?.get(e);if(i&&nt(i.url))return y`<a class="${i.dismissed?`risk-name risk-used is-dismissed`:`risk-name risk-used`}" href="${i.url}" target="_blank" rel="noopener noreferrer">${Y(Ze)}<span class="risk-clip risk-used-in" data-tooltip="${`${e}
24
24
  ${uo(i)}`}">${e}</span>${i.dismissed?y`<span class="sr-only">(dismissed)</span>`:b}${Oe}</a>`;let a=t.get(e),o=a?.href,s=y`<span class="risk-clip risk-used-in" data-tooltip-truncated data-tooltip="${e}">${e}</span>`;if(r&&[`npm`,`pnpm`,`yarn`].includes(a?.format)){let[t,n]=r(e);return y`<span class="risk-used"><button type="button" class="risk-name risk-used-why" aria-haspopup="dialog" aria-label="${`What depends on ${t} in ${e}`}" @click="${()=>fo(e,a,t,n)}">${Y(_)}${s}</button><a class="risk-used-external" href="${o}" target="_blank" rel="noopener noreferrer" aria-label="${`${e} on GitHub`}">${Oe}</a></span>`}return o?y`<a class="risk-name risk-used" href="${o}" target="_blank" rel="noopener noreferrer">${Y(_)}${s}${Oe}</a>`:s}function mo(e,t,n,r=`lockfiles`,i=null){let a=[...e];if(a.length===1)return po(a[0],t,n,i);let o=a.map(e=>y`<li>${po(e,t,n,i)}</li>`);if(a.length===2)return y`<ul class="risk-used-lines">${o}</ul>`;let s=a.filter(e=>n?.get(e)?.dismissed).length;return y`<details class="risk-used-all"><summary>${J.format(a.length)} ${r}${s>0?`, ${J.format(s)} dismissed`:``}</summary><ul class="risk-used-lines">${o}</ul></details>`}var ho=e=>typeof e==`string`&&/^GHSA(?:-[\da-z]{4}){3}$/iu.test(e),go=(e,t,n,r=Sa)=>A(`/api/admin/repositories/risk${e.size>0?`?${e}`:``}`,r,async e=>{for await(let t of Dn(e))n(t)},t),_o=({name:e,version:t,integrity:n})=>`${e}@${t}\0${n??``}`,vo=e=>W(e.source)?_o(e):`${e.source}\0${e.name}@${e.version??``}\0${e.from??``}`,yo=e=>[...e.lockfiles?.keys()??[]].map(t=>`${e.fullName}/${t}`);function bo(e,t,n){let r=e.versionsIn.get(t)??e.versionsIn.set(t,new Set).get(t);for(let t of n)r.add(t),e.versions.add(t)}function xo(e){if(Ma(e))return-102;if(K(e))return-101;let t=ka(e);return t>0?-t:W(e.source)?t===0?3:e.risk?2:1:4}var So=(e,t,n,r)=>y`<div class="risk-tabs" role="tablist" aria-label="${e}">${t.map(([e,t])=>y`<button type="button" role="tab" aria-selected="${n===e}" @click="${()=>r(e)}">${t}</button>`)}</div>`,Co={stasis:`Stasis`,lockfiles:`Lockfiles`,workflows:`Workflows`},Z=(e,t)=>y`${e}${t>0?y`<span class="n">${J.format(t)}</span>`:b}`,Q=(e,t,n=`${t}s`)=>`${J.format(e)} ${e===1?t:n}`,wo=y`<svg class="risk-files-chevron" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m4 6 4 4 4-4"/></svg>`,To=class extends x{static view=`manage-repo-risk`;static properties={selection:{attribute:!1},team:{attribute:!1},installTooltips:{attribute:!1},_state:{state:!0},_filter:{state:!0},_kind:{state:!0},_packageKind:{state:!0},_query:{state:!0},_tab:{state:!0},_actionKind:{state:!0},_actionFilter:{state:!0},_files:{state:!0},_scope:{state:!0},_target:{state:!0},_choices:{state:!0},_unlisted:{state:!0},_filesOpen:{state:!0},_filesShown:{state:!0}};static styles=[v(r),v(Hi),v(ya)];constructor(){super(),Object.assign(this,{selection:null,team:null,installTooltips:null,_state:`idle`,_filter:`flagged`,_kind:`production`,_packageKind:`all`,_actionKind:`all`,_actionFilter:`flagged`,_query:``,_tab:`advisories`,_files:`lockfiles`,_filesOpen:!1,_filesShown:`all`,_scope:`all`,_target:``,_choices:null,_unlisted:null}),this._awaiting=!1,this._scan=null,this._asking=null,this._drawTimer=null,this._parts=0,this._reset()}_load(){if(this.hasUpdated)return this._loadChoices()}_loadChoices(){if(!this.team)return this._loadCollection(`teams`,`teams`,Er,e=>{this._choices=e})}willUpdate(e){this.hasUpdated||this._loadChoices(),this.team?e.has(`team`)&&this._followTeam():(e.has(`selection`)||e.has(`_choices`)&&this._awaiting)&&this._follow()}updated(e){e.has(`installTooltips`)&&this.installTooltips?.(this.renderRoot),this.team&&this._state===`idle`&&this.isConnected&&queueMicrotask(()=>{this._state===`idle`&&this.isConnected&&this.start()})}_followTeam(){this._state===`running`&&this._target!==this.team&&this.stop(),this._choose(`team`,this.team)}_follow(){let{riskScope:e=`team`,riskTarget:t=null}=this.selection??{},n=t==null?null:e===`team`?this._choices&&this._shownTeams().filter(e=>e.slug===t).map(e=>e.id):this._choices?.repos?.filter(e=>e.repoId===t).map(e=>String(e.repoId)),r=n?.length===1?n[0]:``;this._awaiting=t!=null&&!this._choices,this._unlisted=t!=null&&this._choices&&!r?e:null,this._state===`running`&&(e!==this._scope||r!==this._target)&&this.stop(),this._choose(e,r)}_shownTeams(){return(this._choices?.teams??[]).filter(e=>!e.hidden)}_pick(e,t=``){if(this._state===`running`)return;this._choose(e,t),Object.assign(this,{_awaiting:!1,_unlisted:null});let n=t&&(e===`repo`?Number(t):this._choices?.teams?.find(e=>e.id===t)?.slug);f(`manage-repo-risk`,{riskScope:e,...n?{riskTarget:n}:{}})}_choose(e,t=``){this._state===`running`||e===this._scope&&t===this._target||(this._scope=e,this._target=t,this._reset(),this._error=null,this._state=`idle`)}_reset(){this._repos=new Map,this._archived=new Map,this._packages=new Map,this._advisories=new Map,this._actions=new ha,this._reach=null,this._stopAsking()}connectedCallback(){super.connectedCallback(),X.page=this}disconnectedCallback(){this.stop(),this._stopAsking(),X.page===this&&(X.page=null),super.disconnectedCallback()}async start(){if(this._state===`running`||this._scope!==`all`&&!this._target)return;let e=new URLSearchParams({...this._scope===`all`?{}:{[this._scope]:this._target},scan:crypto.randomUUID()});this._reset(),this._error=null,this._state=`running`;let t=new AbortController;this._scan=t,this._parts=0;try{for(let n=`continue`,r=0;n===`continue`;){if(++this._parts>io)throw Error(`Stopped after ${J.format(io)} parts. Scan again to go on from where it stopped.`);n=null;let i=this._told();if(await go(e,t.signal,e=>{(e.type===`done`||e.type===`continue`)&&(n=e.type),this._apply(e),this._draw()},this.team?Ca:Sa),n===null)throw Error(`The scan ended before it finished. Try again.`);if(r=this._told()>i?0:r+1,n===`continue`&&r>=ao)throw Error(`Stopped: the last ${J.format(ao)} parts found nothing more. Scan again to try once more.`)}this._state=`done`}catch(e){if(t.signal.aborted||e?.name===`AbortError`)return;this._error=e?.message??String(e),this._state=`stopped`}finally{this._scan===t&&(this._scan=null,this._state===`running`&&(this._state=`stopped`)),this._draw(!0)}}stop(){this._scan&&(this._scan.abort(),this._scan=null,this._state=`stopped`,this._draw(!0))}_draw(e=!1){e?(clearTimeout(this._drawTimer),this._drawTimer=null,this.requestUpdate()):this._drawTimer??=setTimeout(()=>{this._drawTimer=null,this.requestUpdate()},so)}_told(){let e=this._archived.size;for(let t of this._repos.values()){(t.lockfiles||t.error)&&e++,t.dependabot&&e++,t.stasis&&e++;for(let n of t.lockfiles?.values()??[])e+=+(n.packages!==null||!!n.error)+ +!!(n.advisories||n.advisoriesError)}for(let t of this._packages.values())t.risk&&!t.risk.stale&&e++;return e+this._actions.told()}_apply(e){if(e.type===`repos`){let t=new Map(e.repos.map(({id:e,fullName:t})=>[e,t]));for(let[e,n]of this._archived)t.get(e)!==n&&this._archived.delete(e);let n=[...this._repos.values()].filter(e=>t.get(e.id)!==e.fullName);for(let e of n)this._repos.delete(e.id),this._actions.forget(e.id);this._forget(n.flatMap(yo),n.some(e=>e.dependabot?.alerts));for(let{id:t,fullName:n}of e.repos)!this._repos.has(t)&&!this._archived.has(t)&&this._repos.set(t,{id:t,fullName:n,commit:null,lockfiles:null,error:null,detail:null,dependabot:null,stasis:null});this._reach=null}else if(e.type===`repo`){let t=this._repos.get(e.id);if(!t)return;if(e.archived){this._archived.set(t.id,t.fullName),this._repos.delete(t.id),this._actions.forget(t.id),this._forget(yo(t),!!t.dependabot?.alerts),this._reach=null;return}if(e.error){let n=yo(t),r=!!t.dependabot?.alerts;Object.assign(t,{lockfiles:null,error:e.error,detail:e.detail??null,dependabot:null,stasis:null}),this._reach=null,this._actions.forget(t.id),this._forget(n,r);return}let n=t.commit!==null&&t.commit!==e.commit,r=new Set(n?[]:e.lockfiles.map(({path:e})=>e)),i=[...t.lockfiles?.keys()??[]].filter(e=>!r.has(e)).map(e=>`${t.fullName}/${e}`);Object.assign(t,{commit:e.commit,error:null,detail:null}),n&&(t.stasis=null),this._reach=null,t.lockfiles=new Map(e.lockfiles.map(e=>[e.path,!n&&t.lockfiles?.get(e.path)||{...e,packages:null,error:null}])),this._forget(i)}else if(e.type===`lockfile`){let t=this._repos.get(e.repo),n=t?.lockfiles?.get(e.path);if(!n)return;if(e.error){Object.assign(n,{error:e.error,detail:e.detail??null});return}Object.assign(n,{packages:e.packages.length,error:null,detail:null});let r=`${t.fullName}/${e.path}`;for(let t of e.packages){let e=vo(t),n=this._packages.get(e);n||this._packages.set(e,n={...t,usedIn:new Set,neededIn:new Set,risk:null}),n.usedIn.add(r),t.dev!==!0&&n.neededIn.add(r),n.dev=n.neededIn.size===0}}else if(e.type===`risk`){let t=this._packages.get(_o(e));t&&(t.risk=to(e,t.risk),t.wasStale||=!!t.risk.stale)}else if(e.type===`advisories`)this._applyAdvisories(e);else if(e.type===`dependabot`)this._applyDependabot(e);else if(e.type===`stasis`){let t=this._repos.get(e.repo);if(!t)return;t.stasis=e.error?{error:e.error,detail:e.detail??null,configs:new Map}:{error:null,detail:null,configs:new Map(e.configs.map(e=>[e.path,Za(e)]))},this._reach=null,this._askStasis()}else(e.type===`action`||(e.type===`workflows`||e.type===`workflow`)&&this._repos.has(e.repo))&&this._actions.apply(e)}_forget(e,t=!1){if(e.length===0)t&&this._readvise();else{for(let[t,n]of this._packages){for(let t of e)n.usedIn.delete(t),n.neededIn.delete(t);n.usedIn.size===0&&this._packages.delete(t),n.dev=n.neededIn.size===0}this._readvise()}}_readvise(){this._advisories=new Map;for(let e of this._packages.values())e.malware=void 0;for(let e of this._repos.values())for(let[t,n]of e.lockfiles??[])n.advisories&&this._advise(`${e.fullName}/${t}`,n.advisories);this._alert()}_alerted(){return[...this._repos.values()].some(e=>e.dependabot?.alerts?.length>0)}_applyAdvisories(e){let t=this._repos.get(e.repo),n=t?.lockfiles?.get(e.path);if(!n)return;if(e.error){n.advisoriesError=e.error;return}let r=n.advisories;Object.assign(n,{advisories:e.advisories,advisoriesError:null}),!r&&!this._alerted()?this._advise(`${t.fullName}/${e.path}`,e.advisories):JSON.stringify(r)!==JSON.stringify(e.advisories)&&this._readvise()}_applyDependabot(e){let t=this._repos.get(e.repo);if(!t)return;let n=t.dependabot;t.dependabot=e.error?{...n?.alerts&&{alerts:n.alerts},error:e.error,detail:e.detail??null}:{alerts:e.alerts},JSON.stringify(n?.alerts??null)!==JSON.stringify(t.dependabot.alerts??null)&&this._readvise()}_alert(){let e=new Map,t=(e,t)=>`${e.toUpperCase()}\0${t}`;for(let n of this._advisories.values())for(let r of[n.id,n.ghsa,...n.aliases??[]])ho(r)&&!e.has(t(r,n.name))&&e.set(t(r,n.name),n);let n=[...this._repos.values()].flatMap(e=>(e.dependabot?.alerts??[]).map(t=>({repo:e,alert:t})));for(let{repo:r,alert:i}of[...n.filter(e=>!e.alert.dismissed),...n.filter(e=>e.alert.dismissed)]){let n=`${r.fullName}/${i.manifest}`,a=e.get(t(i.ghsa,i.name));!a&&i.dismissed||(a||(a={id:i.ghsa,ghsa:i.ghsa,name:i.name,title:i.title,severity:i.severity,url:`https://github.com/advisories/${i.ghsa}`,aliases:i.aliases,cwe:i.cwe,malware:!1,dependabot:!0,ranges:new Set,versions:new Set,usedIn:new Set,versionsIn:new Map},this._advisories.set(`${i.ghsa}\0${i.name}`,a),e.set(t(i.ghsa,i.name),a)),a.dependabot&&i.range&&a.ranges.add(i.range),a.alerts??=new Map,a.alerts.set(n,i),a.usedIn.add(n),i.versions.length>0&&bo(a,n,i.versions),a.malware||=i.malware,this._markMalware(a))}}_advise(e,t){for(let{range:n,versions:r,...i}of t){let t=`${i.id}\0${i.name}`,a=this._advisories.get(t);a||this._advisories.set(t,a={...i,ranges:new Set,versions:new Set,usedIn:new Set,versionsIn:new Map}),n&&a.ranges.add(n),a.malware||=i.malware,a.usedIn.add(e),bo(a,e,r),this._markMalware(a)}}_markMalware(e){if(e.malware){for(let t of this._packages.values())if(W(t.source)&&t.name===e.name&&e.versions.has(t.version))for(let n of ta(e))(t.malware??=new Set).add(n)}}_counts(){let e=[...this._repos.values()],t=e.flatMap(e=>[...e.lockfiles?.values()??[]]),n=[...this._packages.values()].filter(e=>W(e.source));return{repos:e.length,reposRead:e.filter(e=>e.lockfiles||e.error).length,archived:this._archived.size,lockfiles:t.length,lockfilesRead:t.filter(e=>e.packages!==null||e.error).length,needed:co(n.filter(e=>!e.dev)),dev:co(n.filter(e=>e.dev)),advisories:this._adviseCounts()}}_adviseCounts(){let e=this._advisoryKinds(),t=new Set(e.production.filter(e=>!e.malware).map(e=>`${e.id}\0${e.name}`)),n=[...this._advisories.values()].filter(e=>e.malware).length;return{total:this._advisories.size,malware:n,needed:t.size,dev:this._advisories.size-n-t.size}}_hasStasis(){return[...this._repos.values()].some(e=>e.stasis&&(e.stasis.error||e.stasis.configs.size>0))}_packageKindShown(){return this._packageKind===`stasis`&&!this._hasStasis()?`all`:this._packageKind}_kindShown(){return this._kind===`stasis`&&!this._hasStasis()?`production`:this._kind}_stasisConfigs(){return[...this._repos.values()].flatMap(e=>[...e.stasis?.configs.values()??[]].map(t=>({repo:e,config:t})))}_stasisReach(){if(this._reach)return this._reach;let e={versions:new Set,at:new Map};for(let{repo:t,config:n}of this._stasisConfigs()){for(let t of n.dependencies??[])e.versions.add(q(t));let r=e=>e.slice(0,Math.max(e.lastIndexOf(`/`),0)),i=r(n.path),a=[...t.lockfiles?.keys()??[]].filter(e=>r(e)===``||i===r(e)||i.startsWith(`${r(e)}/`)),o=Math.max(...a.map(e=>r(e).length));for(let i of n.lockfiles??a.filter(e=>r(e).length===o)){let r=e.at.get(`${t.fullName}/${i}`)??e.at.set(`${t.fullName}/${i}`,new Set).get(`${t.fullName}/${i}`);for(let e of n.dependencies??[])r.add(q(e))}}return this._reach=e}_stasisCounts(){let e=this._stasisConfigs().map(({config:e})=>e);return{total:e.length,built:e.filter(e=>e.dependencies).length,pending:e.filter(e=>e.pending).length,failed:e.filter(e=>e.error).length+[...this._repos.values()].filter(e=>e.stasis?.error).length}}_stasisNote(){let{total:e,pending:t,failed:n}=this._stasisCounts();if(t===0&&n===0)return b;let r=e-t,i=[...this._repos.values()].flatMap(e=>e.stasis?.error?[`${e.fullName}: ${H(e.stasis.error)}`]:[...e.stasis?.configs.values()??[]].filter(e=>e.error).map(t=>`${e.fullName}/${t.path}: ${H(t.error)}${t.detail?` (${t.detail})`:``}`));return y`<p class="risk-stasis" role="status"><span class="risk-icon" aria-hidden="true"><img src="./stasis.svg" alt=""></span>${t>0?y`<span>Stasis is still building ${Q(t,`project`)}.</span> <span class="risk-builds" role="progressbar" aria-label="Stasis builds made" aria-valuemin="0" aria-valuemax="${e}" aria-valuenow="${r}"><span style="${Qe({width:`${e?r/e*100:0}%`})}"></span></span><span class="risk-builds-n">${J.format(r)}/${J.format(e)}</span>`:b} ${n>0?y`<span class="risk-dependabot-failed" data-tooltip="${i.join(`
25
25
  `)}">${Q(n,`build`)} failed</span>`:b}</p>`}_askStasis(){this._asking||!this.isConnected||this._stasisConfigs().some(({config:e})=>e.pending)&&(this._asking={timer:setTimeout(()=>{this._pollStasis()},Ya),controller:new AbortController})}_stopAsking(){this._asking&&=(clearTimeout(this._asking.timer),this._asking.controller.abort(),null)}async _pollStasis(){let e=this._asking;if(!e)return;let{signal:t}=e.controller,n=[...this._repos.values()].flatMap(e=>{let t=[...e.stasis?.configs.values()??[]].filter(e=>e.pending).map(e=>e.path);return Array.from({length:Math.ceil(t.length/Xa)},(n,r)=>({repo:e,commit:e.commit,paths:t.slice(r*Xa,(r+1)*Xa)}))});await Promise.all(n.map(async({repo:e,commit:n,paths:r})=>{let i=new URLSearchParams([[`repoId`,String(e.id)],[`commit`,n],...r.map(e=>[`path`,e]),...Object.entries(wa(this))]);try{let{configs:r}=await A(`/api/admin/repositories/risk/stasis?${i}`,{},e=>e.json(),t);if(t.aborted||e.commit!==n||!e.stasis||this._repos.get(e.id)!==e)return;for(let t of r)e.stasis.configs.has(t.path)&&e.stasis.configs.set(t.path,{...Za(t),lockfiles:e.stasis.configs.get(t.path).lockfiles});this._reach=null}catch{}})),this._asking===e&&(this._asking=null,this._draw(!0),this._askStasis())}_rows(){let e=this._query.trim().toLowerCase(),[,t]=za[this._filter],n=this._packageKindShown(),r=this._stasisReach();return[...this._packages.values()].filter(i=>Fa(i,n,r)&&t(i)&&(!e||i.name.toLowerCase().includes(e))).toSorted((e,t)=>xo(e)-xo(t)||Aa(t).length-Aa(e).length||e.name.localeCompare(t.name)||(e.version??``).localeCompare(t.version??``))}_advisoryKinds(){let e=new Set,t=new Set;for(let n of this._packages.values())if(W(n.source)){for(let t of n.usedIn)e.add(`${n.name}@${n.version}\0${t}`);for(let e of n.neededIn)t.add(`${n.name}@${n.version}\0${e}`)}let n=this._stasisReach(),r={all:[],production:[],development:[],stasis:[]};for(let i of this._advisories.values()){let a=[...i.versions],o={production:new Map,development:new Map},s=(e,t,n)=>(e.get(t)??e.set(t,new Set).get(t)).add(n);for(let[n,r]of i.versionsIn)for(let a of r){let r=`${i.name}@${a}\0${n}`;s(o[(e.has(r)?!t.has(r):i.alerts?.get(n)?.dev)?`development`:`production`],n,a)}for(let[e,t]of i.alerts??[])i.versionsIn.get(e)?.size||o[t.dev?`development`:`production`].set(e,new Set);let c={...i,dev:o.production.size===0};if(r.all.push(c),i.malware){r.production.push(c),r.development.push(c),r.stasis.push(c);continue}let l=(e,t)=>({...i,dev:t,versions:new Set(a.filter(t=>[...e.values()].some(e=>e.has(t)))),usedIn:new Set([...i.usedIn].filter(t=>e.has(t)))});o.production.size>0&&r.production.push(l(o.production,!1)),o.development.size>0&&r.development.push(l(o.development,!0));let u=a.filter(e=>n.versions.has(q({name:i.name,version:e})));if(u.length>0){let e=new Map;for(let t of u){let r=[...i.versionsIn].flatMap(([e,n])=>n.has(t)?[e]:[]);for(let a of Pa(r,q({name:i.name,version:t}),n))s(e,a,t)}r.stasis.push({...l(e,!1),versions:new Set(u)})}}return r.actions=this._actionAdvisories(),r.all.push(...r.actions),r}_actionAdvisories(){let e=new Map;for(let t of this._actions.rows(`actions`)){let n=t.line?.repository?.fullName??t.line?.repo??t.uses?.repo;for(let r of n?t.findings:[]){if(r.id!==`advisory`)continue;let i=`${r.advisory}\0${n.toLowerCase()}`,a=e.get(i);if(!a){let{id:t,advisory:o,range:s,versions:c,...l}=r;e.set(i,a={...l,kind:`action`,id:o,name:n,severity:r.unrated?void 0:r.severity,malware:!!r.malware,ranges:new Set,versions:new Set,usedIn:[]})}r.range&&a.ranges.add(r.range),t.line?.commit&&a.versions.add(`${t.line.commit.slice(0,7)}${t.line.tags?.length?` (${t.line.tags.join(`, `)})`:``}`),a.usedIn.push(...t.usedIn.filter(e=>!a.usedIn.some(t=>JSON.stringify(t)===JSON.stringify(e))))}}return[...e.values()]}_advisoryRows(e=this._advisoryKinds()){let t=this._query.trim().toLowerCase();return e[this._kindShown()].filter(e=>!t||e.name.toLowerCase().includes(t)).toSorted((e,t)=>Number(t.malware)-Number(e.malware)||B(e.severity)-B(t.severity)||e.name.localeCompare(t.name)||e.id.localeCompare(t.id))}_kindToggle(e,t,n,r,i){return y`<div class="risk-scope" role="group" aria-label="${e}">${Object.entries(t).map(([e,t])=>y`<button type="button" aria-pressed="${r===e}" @click="${()=>i(e)}">${t}<span class="n">${J.format(n[e])}</span></button>`)}</div>`}_filterToggle(e){let t=Object.fromEntries(Object.entries(za).map(([t,[,n]])=>[t,e.filter(n).length])),n=Object.entries(za).filter(([e])=>e===`all`||e===this._filter||t[e]>0);return n.length===1?b:this._kindToggle(`Show packages`,Object.fromEntries(n.map(([e,[t]])=>[e,t])),t,this._filter,e=>{this._filter=e})}_lockfileLinks(){let e=new Map;for(let t of this._repos.values())for(let n of t.commit?t.lockfiles?.keys()??[]:[])e.set(`${t.fullName}/${n}`,{href:V(t.fullName,t.commit,n),repoId:t.id,commit:t.commit,path:n,format:t.lockfiles.get(n).format});return e}render(){let e=!!this.team;return y`<div class="${e?`wrap team-risk`:`wrap`}">${e?b:y`${this._nav()}<h1 class="sr-only">Repository risk</h1>`}<div class="page-intro"><p class="intro">${e?`Risks in the team’s repositories’ npm dependencies and GitHub Actions.`:`Risks in each repository’s npm dependencies and GitHub Actions.`}</p>${this._stateBadge()}${this._state===`running`?y`<button type="button" class="btn" @click="${()=>this.stop()}">Stop</button>`:y`<button type="button" class="${e?`btn`:`btn primary`}" ?disabled="${this._scope!==`all`&&!this._target}" @click="${()=>{this.start()}}">${this._state===`idle`?`Start scan`:`Scan again`}</button>`}</div>${e?b:this._scopeBar()} ${this._progress()} ${this._error?y`<p class="msg error" role="alert">${this._error}</p>`:b} ${this._repos.size===0?b:y`<div class="manage-list">${this._lockfiles()} ${this._packages.size===0&&this._actions.files.size===0?b:this._tab===`advisories`?this._advisoryTable():this._tab===`actions`?this._actionsTable():this._packageTable()}</div>`}</div>`}_tabs(){return So(`Results`,[[`advisories`,Z(`Advisories`,this._advisories.size+this._actionAdvisories().length)],[`packages`,Z(`Packages`,this._packages.size)],[`actions`,Z(`Actions`,this._actions.rows(`actions`).length)]],this._tab,e=>{this._tab=e})}_search(e,t,n,r=`package`){return y`<div class="risk-search"><input type="search" aria-label="${`Search ${n}`}" placeholder="${`Search by ${r}\u2026`}" .value="${this._query}" @input="${e=>{this._query=e.target.value}}"> <span class="result-count">${e===t?``:`${J.format(e)} of `}${J.format(t)} ${n}</span></div>`}_scopeBar(){let e=this._state===`running`,t=this._choices?``:`Loading…`;return y`<div class="risk-scope-bar"><div class="risk-scope" role="group" aria-label="What to scan">${Ta.map(([t,n])=>y`<button type="button" aria-pressed="${this._scope===t}" ?disabled="${e}" @click="${()=>this._pick(t)}">${n}</button>`)}</div>${this._scope===`team`?this._teamPicker(e,t):b} ${this._scope===`repo`?y`<repository-selector label="Which repository" placeholder="${t||`Choose a repository…`}" ?disabled="${e||!this._choices}" .options="${(this._choices?.repos??[]).map(e=>({value:String(e.repoId),label:e.fullName}))}" .value="${this._target||null}" @repository-change="${e=>this._pick(`repo`,e.detail.value)}"></repository-selector>`:b}</div>${this._unlisted?y`<p class="msg" role="status">${this._unlisted===`team`?`This link’s team isn’t listed. Choose a team.`:`This link’s repository isn’t connected. Choose a repository.`}</p>`:b}`}_teamPicker(e,t){let n=e=>new Set((e.repos??[]).map(e=>e.repoId)).size,r=this._shownTeams().toSorted((e,t)=>n(t)-n(e)),i=e=>e.name;return r.length>0&&r.length<=Ea?y`<div class="risk-scope" role="group" aria-label="Which team">${r.map(t=>y`<button type="button" aria-pressed="${t.id===this._target}" ?disabled="${e}" @click="${()=>this._pick(`team`,t.id)}">${i(t)}</button>`)}</div>`:y`<select aria-label="Which team" ?disabled="${e}" @change="${e=>this._pick(`team`,e.target.value)}"><option value="" ?selected="${!this._target}">${t||`Choose a team…`}</option>${r.map(e=>y`<option value="${e.id}" ?selected="${e.id===this._target}">${i(e)}</option>`)}</select>`}_metrics(){let e=this._counts(),{needed:t,dev:n,advisories:r}=e,i=e=>J.format(e),a=e=>({bar:e.map(([e,t])=>[e,t]),split:e.filter(([,e,t=e])=>t>0)}),o=t.flagged+n.flagged,s=t.stale+n.stale,c=t.wasStale+n.wasStale,{workflows:l,workflowsRead:u}=this._actions.counts();return[{label:`Repositories`,value:e.reposRead,of:e.repos,bar:[[`read`,e.reposRead]],split:[[`lockfiles`,e.lockfilesRead,e.lockfiles],[`workflows`,u,l]].filter(([,,e])=>e>0),note:e.archived>0?[`${Q(e.archived,`archived repository`,`archived repositories`)} left out.`]:[]},{label:`Packages`,value:t.told+n.told,of:t.total+n.total,...a([[`prod`,t.told,t.total],[`dev`,n.told,n.total]])},{label:`Flagged`,value:o,...a([[`prod`,t.flagged],[`dev`,n.flagged]]),tone:o>0?`high`:null},...c>0?[{label:`Stale`,value:s,scale:c,bar:[[`prod`,t.wasStale-t.stale],[`dev`,n.wasStale-n.stale]],split:a([[`prod`,t.stale],[`dev`,n.stale]]).split,note:[...s>0?[`Assessed over an hour ago; ${this._state===`running`?`to be assessed again once the rest are`:`not assessed again yet`}.`]:[],`${i(c-s)} of ${i(c)} assessed again.`]}]:[],...r.total>0?[{label:`Advisories`,value:r.total,...a([[`malware`,r.malware],[`prod`,r.needed],[`dev`,r.dev]])}]:[],...this._stasisMetrics(),...this._actionsMetrics()]}_stasisMetrics(){let{total:e,built:t,pending:n,failed:r}=this._stasisCounts();return e===0&&r===0?[]:[{label:`Stasis`,value:t,of:e,bar:[[`read`,t]],note:[...n>0?[`${Q(n,`build`)} still to be made, asked for again every 30 seconds while this page shows them.`]:[],...r>0?[`${Q(r,`build`)} failed.`]:[]]}]}_actionsMetrics(){if(this._actions.listed.size===0)return[];let{actions:e,resolved:t}=this._actions.counts(),n=this._actions.rows(`all`).filter(e=>e.severity&&e.severity!==`notice`&&e.severity!==`low`).length;return[{label:`Actions`,value:t,of:e,bar:[[`read`,t]]},{label:`Actions flagged`,value:n,bar:[],tone:n>0?`high`:null}]}_stateBadge(){if(this._state===`idle`)return b;let e=this._state===`running`&&this._parts>1?`Scanning \xB7 part ${J.format(this._parts)}`:{running:`Scanning`,stopped:`Stopped`,done:`Done`}[this._state];return y`<span class="risk-state" role="status" data-state="${this._state}">${e}</span>`}_progress(){if(this._state===`idle`)return y`<div class="risk-progress-line"><div class="risk-progress" role="status"><p class="risk-progress-idle">Not scanned yet. A scan reads each repository from GitHub and assesses each npm package it locks, which can take a while; a scan again within the hour is quicker.</p></div></div>`;let e=e=>J.format(e),t=({split:t=[],note:n=[]})=>[t.length>0?`${t.map(([t,n,r])=>`${e(n)}${r===void 0?``:`/${e(r)}`} ${t}`).join(`, `)}.`:``,...n].filter(Boolean).join(` `),n=({split:t=[],note:n=[]})=>y`${t.length>0?y`<div class="tooltip-counts">${t.map(([t,n,r])=>y`<span class="tooltip-count">${e(n)}${r===void 0?b:y`<span class="tooltip-count-of"><span class="tooltip-slash">/</span>${e(r)}</span>`}</span><span>${t}</span>`)}</div>`:b}${n.map(e=>y`<div class="tooltip-counts-note">${e}</div>`)}`;return y`<div class="risk-progress-line"><div class="risk-progress" role="status">${this._metrics().map(r=>{let{label:i,value:a,of:o,scale:s=o??a,bar:c,tone:l}=r,u=t(r);return y`<span class="${l?`risk-metric risk-${l}`:`risk-metric`}" data-tooltip="${u||b}" .tooltipContent="${u?n(r):null}"><span class="risk-metric-label">${i}</span> <span class="risk-metric-value">${e(a)}${o===void 0?b:y`<span class="risk-metric-of"><span class="risk-metric-slash">/</span>${e(o)}</span>`}${u?y`<span class="sr-only">${u}</span>`:b}</span> <span class="risk-bar" aria-hidden="true">${c.filter(([,e])=>e>0).map(([e,t])=>y`<span class="${`risk-bar-${e}`}" style="${Qe({width:`${t/s*100}%`})}"></span>`)}</span></span>`})}</div>${this._filesToggle()}</div>`}_pending(e,t){return y`<span class="risk-pending">${this._state===`running`?e:t}</span>`}_repoStatus(e,t=`lockfiles`){if(e.error)return U(e);if(e.lockfiles===null)return this._pending(`Waiting…`,`Not read`);if(t===`stasis`)return null;if(t===`lockfiles`)return e.lockfiles.size===0?y`<span class="risk-none">No npm lockfiles</span>`:null;let n=this._actions.listed.get(e.id);return n?n.error||this._actions.filesOf(e.id).length>0?null:y`<span class="risk-none">No workflows</span>`:this._pending(`Waiting…`,`Not read`)}_lockfileStatus(e){return e.error?U(e):e.packages===null?this._pending(`Reading…`,`Not read`):`${J.format(e.packages)} packages`}_lockfiles(){if(!this._filesOpen)return b;let{lockfiles:e,workflows:t}=this._filesTold(),n=[...this._hasStasis()?[[`stasis`,Z(`Stasis`,this._stasisCounts().total)]]:[],[`lockfiles`,Z(`Lockfiles`,e)],...this._actions.listed.size>0?[[`workflows`,Z(`Workflows`,t)]]:[]],r=n.some(([e])=>e===this._files)?this._files:`lockfiles`,i=[...this._repos.values()].filter(e=>r!==`stasis`||e.stasis),a=i.filter(e=>this._failed(e,r)),o=this._filesShown===`failed`&&a.length>0?a:i,s=n.map(([e],t)=>t===0?Co[e]:Co[e].toLowerCase());return y`<section id="risk-files" class="risk-files" aria-label="${s.length>1?`${s.slice(0,-1).join(`, `)} and ${s.at(-1)}`:s[0]}"><div class="risk-files-head">${n.length>1?So(`Files`,n,r,e=>{this._files=e}):y`<h2>${Z(`Lockfiles`,e)}</h2>`} ${a.length>0?this._kindToggle(`Show repositories`,{all:`All`,failed:`Couldn’t be read`},{all:i.length,failed:a.length},o===a?`failed`:`all`,e=>{this._filesShown=e}):b}</div><ul class="risk-repos">${$e(o,e=>e.id,e=>y`<li>${e.commit?y`<a class="risk-repo-name risk-name" href="${V(e.fullName,e.commit,``,`tree`)}" target="_blank" rel="noopener noreferrer" data-tooltip-truncated data-tooltip="${e.fullName}">${e.fullName}</a>`:y`<span class="risk-repo-name" data-tooltip-truncated data-tooltip="${e.fullName}">${e.fullName}</span>`} ${this._repoStatus(e,r)??y`<ul class="risk-lockfiles">${r===`workflows`?this._workflowItems(e):r===`stasis`?this._stasisItems(e):[...e.lockfiles.values()].map(t=>y`<li>${this._fileLink(e,t.path)}<span class="risk-lockfile-meta">${t.format} · ${this._lockfileStatus(t)}</span></li>`)}</ul>`}</li>`)}</ul></section>`}_filesTold(){let e=[...this._repos.values()],t=e.flatMap(e=>[...e.lockfiles?.values()??[]]),n=[...this._actions.listed.values()],r=[...this._actions.files.values()].flatMap(e=>[...e.values()]);return{lockfiles:t.length,workflows:this._actions.counts().workflows,reposFailed:e.filter(e=>e.error).length,filesFailed:t.filter(e=>e.error).length+n.filter(e=>e.error).length+r.filter(e=>e.error).length+this._stasisCounts().failed}}_filesToggle(){if(this._repos.size===0)return b;let{reposFailed:e,filesFailed:t}=this._filesTold(),n=[e>0?Q(e,`repository`,`repositories`):``,t>0?Q(t,`file`):``].filter(Boolean).join(` and `),r=n&&`${n} couldn\u2019t be read`;return y`<button type="button" class="risk-files-toggle" aria-label="${[`Progress details`,...r?[r]:[]].join(`, `)}" aria-expanded="${this._filesOpen}" aria-controls="${this._filesOpen?`risk-files`:b}" data-tooltip="${[`Progress details`,...r?[r]:[]].join(`
26
26
  `)}" @click="${()=>{this._filesOpen=!this._filesOpen}}">${wo}${r?y`<span class="n" aria-hidden="true">${J.format(e+t)}</span>`:b}</button>`}_stasisItems(e){let{stasis:t}=e;return t?t.error?y`<li><span class="mono">stasis.config.json</span><span class="risk-lockfile-meta">${U(t)}</span></li>`:[...t.configs.values()].map(t=>y`<li>${this._fileLink(e,t.path)}<span class="risk-lockfile-meta">${t.error?U(t):t.pending?y`<span class="risk-pending">Building…</span>`:`${J.format(t.dependencies.length)} packages`}</span></li>`):b}_failed(e,t){return e.error?!0:t===`lockfiles`?[...e.lockfiles?.values()??[]].some(e=>e.error):t===`stasis`?!!e.stasis?.error||[...e.stasis?.configs.values()??[]].some(e=>e.error):!!this._actions.listed.get(e.id)?.error||this._actions.filesOf(e.id).some(e=>e.error)}_fileLink(e,t){return e.commit?y`<a class="mono risk-name" href="${V(e.fullName,e.commit,t)}" target="_blank" rel="noopener noreferrer">${t}</a>`:y`<span class="mono">${t}</span>`}_workflowItems(e){let t=this._actions.listed.get(e.id);return t?t.error?y`<li><span class="mono">.github/workflows</span><span class="risk-lockfile-meta">${U(t)}</span></li>`:this._actions.filesOf(e.id).map(t=>y`<li>${this._fileLink(e,t.path)}<span class="risk-lockfile-meta">${t.kind} · ${t.error?U(t):`${J.format(t.findings.length)} findings`}</span></li>`):b}_resultsHead(e){return y`<div class="risk-results-head"><div class="collection-toolbar">${this._tabs()}${e}</div></div>`}_packageTable(){let e=this._rows(),t=[...this._packages.values()],n=this._packageKindShown(),r=Ja(Wa,this._hasStasis()),i=this._stasisReach(),a=Object.fromEntries(Object.keys(r).map(e=>[e,t.filter(t=>Fa(t,e,i)).length])),o=this._lockfileLinks(),s=t.some(e=>e.source!==`registry`);return y`<section class="risk-section" aria-label="Packages">${this._resultsHead(y`${this._kindToggle(`Which packages`,r,a,n,e=>{this._packageKind=e})} ${this._filterToggle(t.filter(e=>Fa(e,n,i)))} ${this._search(e.length,a[n],`packages`)}`)} ${n===`stasis`?this._stasisNote():b} ${this._table(e,this._filter===`flagged`&&!this._query.trim()?qa(this._state):null,y`<th>Package</th><th><span data-tooltip="${Ba}">Risk</span></th><th>Findings</th>${s?y`<th>Source</th>`:b}<th class="risk-used-column">Used in</th>`,vo,e=>this._packageRow(e,o,s,Ia(e,n,i)),`Search or filter to see others.`)}</section>`}_packageRow(e,t,n,r=e.usedIn){let i=W(e.source)?tt({view:`npm`,packageName:e.name,packageSpec:e.version}):null;return y`<tr class="${e.risk?.stale?`is-stale`:``}"><td>${$a(e,e.version,i,Va)}</td><td>${this._score(e)}</td><td>${this._findings(e)}</td>${n?y`<td><span data-tooltip="${e.from??b}">${Da[e.source]??e.source}${e.source===`mirror`&&e.from?` (${new URL(e.from).host})`:``}</span></td>`:b}<td>${mo(r,t,void 0,`lockfiles`,()=>[e.name,e.version?[e.version]:[]])}</td></tr>`}_score(e){let t=ka(e),n=t===null?b:y`<span class="${`risk-score risk-${Yi(t)}`}">${t}</span>`;return e.risk?.stale?y`${n}<span class="risk-stale" data-tooltip="${this._staleSaid(e.risk)}">stale</span>`:n}_staleSaid({stale:e,refreshFailed:t}){let n=t?`couldn\u2019t be assessed again: ${t}`:this._state===`running`?`to be assessed again once the rest are`:`not assessed again yet`;return`Assessed ${ro(e.assessedAt)}; ${n}`}_findings(e){let t=Aa(e);return t.length>0?y`<ul class="risk-findings">${t.map(t=>y`<li class="${`risk-${t.severity}`}" data-tooltip="${t.id===`malware`?ja(e).join(`