@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
@@ -0,0 +1,13 @@
1
+ // A file pretty-printed as Compare draws it, with its copy's layout blank lines: the server's
2
+ // copies (pretty-print.ts) and a delta's (npm-delta-worker.js) alike.
3
+ import { format, layoutBlankLines } from '@preventive/compare/pretty.js'
4
+
5
+ // Part of every kept copy's name; bumped when what the formatter writes for
6
+ // the same file changes, or what its check lets through, so copies written
7
+ // before are no longer read.
8
+ export const PRETTY_VERSION = 6
9
+
10
+ export async function prettyFormat(text, extension) {
11
+ const result = await format(text, extension)
12
+ return 'error' in result ? result : { text: result.code, blank: await layoutBlankLines(result.code, extension) }
13
+ }
@@ -2,7 +2,9 @@
2
2
  // one file at a time, GET /api/npm/pretty all a version's at once), and the
3
3
  // files that changed between two bundles or versions for Compare (the same
4
4
  // with `other`, or `otherVersion`), named by path and content hash, formatted
5
- // with oxfmt once and kept Brotli-encoded by that hash: a bundle's in its
5
+ // with oxfmt once, with the copy's blank lines that are its layout alone
6
+ // (@preventive/compare layoutBlankLines), which Compare leaves out where one
7
+ // side alone has them, and kept Brotli-encoded by that hash: a bundle's in its
6
8
  // cache directory (so only made from, and read by readers of, that bundle), a
7
9
  // public npm version's under `cache/npm/`; a private version's are never
8
10
  // kept. Access is the caller's to check.
@@ -10,12 +12,11 @@ import { Buffer } from 'node:buffer'
10
12
  import { Readable } from 'node:stream'
11
13
  import { promisify } from 'node:util'
12
14
  import { brotliDecompress } from 'node:zlib'
13
- import { format } from '@preventive/compare/pretty.js'
14
15
  import { computeFileHash } from '@preventive/report'
15
16
  import { FILE_HASH, computeBundleFileHashes } from '../common/bundle-metadata.js'
16
17
  import { bundleCompareFiles, bundleCompareSideScopes } from '../common/bundle-compare-inputs.js'
17
18
  import { bundlePackageDirs, bundleSourcesAsMap } from '../common/bundle-sources.js'
18
- import { MAX_PRETTY_BYTES, needsPrettyPrint, prettyExtension } from '../common/pretty-print.js'
19
+ import { MAX_PRETTY_BYTES, layoutBlankList, needsPrettyPrint, prettyExtension } from '../common/pretty-print.js'
19
20
  import { type OpenedBlob, readBytes } from './blob-store.ts'
20
21
  import { type BundleCacheStorage, readSizedBundleDetails } from './bundle-cache.ts'
21
22
  import type { BundleStore } from './bundle-store.ts'
@@ -26,11 +27,8 @@ import { keptBriefly } from './kept-briefly.ts'
26
27
  import { loadNpmFiles } from './npm-loads.ts'
27
28
  import { type NpmVersionDocument, npmFileText, pathOrder } from './npm-packages.ts'
28
29
  import { inTurns } from './queue.ts'
30
+ import { PRETTY_VERSION, type PrettyCopy, prettyFormat } from './pretty-format.js'
29
31
 
30
- // Part of every kept copy's name; bumped when what the formatter writes for
31
- // the same file changes, or what its check lets through, so copies written
32
- // before are no longer read.
33
- const PRETTY_VERSION = 5
34
32
  // Formats running at once per process, each holding its file's syntax tree,
35
33
  // and those waiting their turn past them (a version's files are formatted one
36
34
  // after another, beside other readers'), any more refused.
@@ -59,9 +57,9 @@ export class PrettyError extends Error {
59
57
  export interface PrettyRequest { path: string; hash: string; extension: string }
60
58
 
61
59
  // One of a version's files pretty-printed (npmAll), named by `source`, the
62
- // hash of the file it was formatted from: its copy's text, or why it has
63
- // none, as a PrettyError tells it.
64
- export type PrettyLine = { path: string; source: string; text: string } | { path: string; source: string; error: string; status: number }
60
+ // hash of the file it was formatted from: its copy's text and layout blank
61
+ // lines (prettyCopy), or why it has none, as a PrettyError tells it.
62
+ export type PrettyLine = { path: string; source: string; text: string; blank: number[] } | { path: string; source: string; error: string; status: number }
65
63
 
66
64
  // Which of a comparison's two its files are of: the bundle or version asked
67
65
  // about, or the `other`.
@@ -94,22 +92,25 @@ export function prettyRequest(params: URLSearchParams): PrettyRequest | null {
94
92
  }
95
93
 
96
94
  // A copy's name: its file's hash in hex, with the extension it was parsed by.
97
- const prettyFile = ({ hash, extension }: PrettyRequest) =>
95
+ export const prettyFile = ({ hash, extension }: PrettyRequest) =>
98
96
  `pretty-v${PRETTY_VERSION}/${Buffer.from(hash.slice('sha512-'.length), 'base64').toString('hex')}.${extension}.br`
99
97
 
100
98
  let activeFormats = 0
101
99
  const waitingFormats: Array<() => void> = []
102
100
 
103
- // The text formatted and Brotli-encoded, where @preventive/compare's checks
104
- // find formatting changed only its layout: refused as `unsupported` where it
105
- // has no check for the kind of file, `unformattable` or `pretty-mismatch`.
101
+ // The text formatted, where @preventive/compare's checks find formatting
102
+ // changed only its layout, its copy `{ text, blank }` (its layout blank
103
+ // lines' numbers) as JSON, Brotli-encoded:
104
+ // refused as `unsupported` where it has no check for the kind of file,
105
+ // `unformattable` or `pretty-mismatch`. Its blank lines are read in the
106
+ // same turn, as they parse and check the copy again.
106
107
  export async function prettyBody(text: string, extension: string): Promise<Buffer> {
107
108
  if (Buffer.byteLength(text) > MAX_PRETTY_BYTES) throw new PrettyError(413, 'file-too-large')
108
109
  if (activeFormats < MAX_ACTIVE_FORMATS) activeFormats++
109
110
  else if (waitingFormats.length >= MAX_WAITING_FORMATS) throw new PrettyError(429, 'pretty-busy')
110
111
  else await new Promise<void>(resolve => { waitingFormats.push(resolve) })
111
112
  let result
112
- try { result = await format(text, extension) }
113
+ try { result = await prettyFormat(text, extension) }
113
114
  finally {
114
115
  const next = waitingFormats.shift()
115
116
  if (next) next()
@@ -119,7 +120,7 @@ export async function prettyBody(text: string, extension: string): Promise<Buffe
119
120
  if (result.error === 'pretty-mismatch') console.warn(`managed: pretty-printing a .${extension} file changed more than its layout; not served`)
120
121
  throw new PrettyError(422, result.error)
121
122
  }
122
- return encodeBrotli(Buffer.from(result.code))
123
+ return encodeBrotli(Buffer.from(JSON.stringify(result)))
123
124
  }
124
125
 
125
126
  export const opened = (body: Buffer): OpenedBlob => ({ size: body.byteLength, stream: Readable.from([body]) })
@@ -127,7 +128,7 @@ export const opened = (body: Buffer): OpenedBlob => ({ size: body.byteLength, st
127
128
  // A version's file's hash, by its bytes: those of a version's files loaded
128
129
  // a little while since are the same bytes (npm-loads.ts), hashed once.
129
130
  const fileHashes = new WeakMap<Uint8Array, Promise<string>>()
130
- function npmFileHash(bytes: Uint8Array): Promise<string> {
131
+ export function npmFileHash(bytes: Uint8Array): Promise<string> {
131
132
  let hash = fileHashes.get(bytes)
132
133
  if (!hash) {
133
134
  fileHashes.set(bytes, hash = computeFileHash(bytes))
@@ -138,9 +139,18 @@ function npmFileHash(bytes: Uint8Array): Promise<string> {
138
139
 
139
140
  const decompress = promisify(brotliDecompress)
140
141
 
141
- // A pretty-printed copy's text, from its Brotli-encoded bytes.
142
+ // A pretty-printed copy's text and layout blank lines, from its Brotli-encoded
143
+ // bytes (prettyBody).
144
+ export async function prettyCopy(copy: OpenedBlob): Promise<PrettyCopy> {
145
+ const { text, blank } = JSON.parse((await decompress(await readBytes(copy))).toString()) as { text: unknown; blank: unknown }
146
+ const numbers = layoutBlankList(blank)
147
+ if (typeof text !== 'string' || !numbers) throw new Error('managed: a kept pretty-printed copy is not one')
148
+ return { text, blank: numbers }
149
+ }
150
+
151
+ // A pretty-printed copy's text alone, as a rename diff reads it.
142
152
  export async function prettyText(copy: OpenedBlob): Promise<string> {
143
- return (await decompress(await readBytes(copy))).toString()
153
+ return (await prettyCopy(copy)).text
144
154
  }
145
155
 
146
156
  // Every file of a version that needs pretty-printing (needsPrettyPrint), read
@@ -159,10 +169,10 @@ async function npmPrintable(doc: NpmVersionDocument): Promise<Array<PrettyReques
159
169
  return files.toSorted((a, b) => pathOrder(a.path, b.path))
160
170
  }
161
171
 
162
- // A file's line (PrettyLine): the text of its copy, as `copy` has it, or why
163
- // it has none.
172
+ // A file's line (PrettyLine): the text of its copy and its layout blank lines,
173
+ // as `copy` has them, or why it has none.
164
174
  async function prettyLine({ path, hash }: PrettyRequest, copy: () => Promise<OpenedBlob>): Promise<PrettyLine> {
165
- try { return { path, source: hash, text: await prettyText(await copy()) } }
175
+ try { return { path, source: hash, ...await prettyCopy(await copy()) } }
166
176
  catch (err) {
167
177
  if (!(err instanceof PrettyError)) throw err
168
178
  return { path, source: hash, error: err.message, status: err.status }
@@ -233,12 +243,12 @@ function sharing<T>(): (key: string, make: () => Promise<T>) => Promise<T> {
233
243
  }
234
244
  }
235
245
 
236
- async function keep(put: () => Promise<void>) {
246
+ export async function keep(put: () => Promise<void>) {
237
247
  try { await put() } catch (err) { console.warn('managed: pretty-print cache write failed:', err) }
238
248
  }
239
249
 
240
250
  // A copy kept, or null where none is.
241
- async function kept(open: () => Promise<OpenedBlob>): Promise<OpenedBlob | null> {
251
+ export async function kept(open: () => Promise<OpenedBlob>): Promise<OpenedBlob | null> {
242
252
  try { return await open() }
243
253
  catch (err) { if (err instanceof CacheMissError) return null; throw err }
244
254
  }
@@ -197,7 +197,7 @@ async function serveBundle(res: ServerResponse, deps: ManagedHttpDeps, bundle: M
197
197
  if (!prettyCache) { json(res, 503, { error: 'unavailable' }); return }
198
198
  const pretty = await prettyOr(res, () => prettyCache.bundle(bundle, file))
199
199
  if (pretty === undefined) return
200
- await stream(pretty, 'br', 'text/plain; charset=utf-8'); return
200
+ await stream(pretty, 'br', 'application/json'); return
201
201
  }
202
202
  if (!deps.bundleCache) { json(res, 503, { error: 'unavailable' }); return }
203
203
  if (part === 'advisories') {
@@ -10,7 +10,7 @@ import { revalidationLinks, securityLinks } from '../common/security-links.js'
10
10
  import { treeDependencyDirectory } from '../client/dependency-paths.js'
11
11
  import { liteWorkspace } from '../common/managed/finding-detail.js'
12
12
  import { managedTeamView } from '../common/managed/team-app.js'
13
- import { expandFindingValues, findingValueIndex } from '../common/managed/finding-values.js'
13
+ import { packTeamReports, unpackTeamReport } from '../common/managed/finding-values.js'
14
14
  import type { BlobStore } from './blob-store.ts'
15
15
  import type { ManagedDb, TeamReportAccessSnapshot } from './db.ts'
16
16
  import type { TeamWorkspaceSummary } from './team-app.ts'
@@ -36,28 +36,37 @@ const REPORT_CACHE_BYTES = 16 * 1024 * 1024
36
36
  // the board (`lite`), its reports' file trees apart, and its team's catalog
37
37
  // summary (team-app.ts).
38
38
  type EncodedWorkspace = { reports: Buffer; lite: Buffer; trees: Buffer; summary: TeamWorkspaceSummary }
39
+ // One as kept: without its whole reports where they would not fit
40
+ // (retainReports).
41
+ type RetainedWorkspace = Omit<EncodedWorkspace, 'reports'> & { reports?: Buffer }
39
42
  export type TeamResponsePart = 'reports' | 'lite' | 'trees'
40
43
  // The part a team's `reports` or `trees` route asks for.
41
44
  export const teamResponsePart = (route: string, url: URL): TeamResponsePart =>
42
45
  route === 'trees' ? 'trees' : url.searchParams.get('lite') === '1' ? 'lite' : 'reports'
43
- const reportCaches = new WeakMap<ManagedDb, Map<string, EncodedWorkspace>>()
44
- const encodedBytes = ({ reports, lite, trees }: EncodedWorkspace) => reports.length + lite.length + trees.length
46
+ const reportCaches = new WeakMap<ManagedDb, Map<string, RetainedWorkspace>>()
47
+ const encodedBytes = ({ reports, lite, trees }: RetainedWorkspace) => (reports?.length ?? 0) + lite.length + trees.length
45
48
  // A workspace's report reads at once. Its reports' sizes are bounded together
46
49
  // before any is read, and each is held parsed till the build ends, so more at
47
50
  // once costs only the raw bytes in flight: a cold build of a team's reports
48
51
  // is so many storage round trips one after another.
49
52
  const WORKSPACE_READS_AT_ONCE = 16
53
+ // Its whole reports, by far its largest part, are kept with the rest where
54
+ // they fit, and left out where they do not: the board's copy and the trees,
55
+ // which a team's view opens on, are kept all the same, so that opening it
56
+ // again reads none of its reports, its whole reports built again apart.
50
57
  function retainReports(db: ManagedDb, key: string, encoded: EncodedWorkspace) {
51
- if (encodedBytes(encoded) > REPORT_CACHE_BYTES) return
58
+ let kept: RetainedWorkspace = encoded
59
+ if (encodedBytes(kept) > REPORT_CACHE_BYTES) { const { reports: _reports, ...rest } = encoded; kept = rest }
60
+ if (encodedBytes(kept) > REPORT_CACHE_BYTES) return
52
61
  let cache = reportCaches.get(db)
53
62
  if (!cache) { cache = new Map(); reportCaches.set(db, cache) }
54
63
  cache.delete(key)
55
- let total = encodedBytes(encoded) + [...cache.values()].reduce((sum, value) => sum + encodedBytes(value), 0)
64
+ let total = encodedBytes(kept) + [...cache.values()].reduce((sum, value) => sum + encodedBytes(value), 0)
56
65
  for (const [oldest, value] of cache) {
57
66
  if (total <= REPORT_CACHE_BYTES && cache.size < VISIBILITY_CACHE_MAX_SNAPSHOTS) break
58
67
  cache.delete(oldest); total -= encodedBytes(value)
59
68
  }
60
- cache.set(key, encoded)
69
+ cache.set(key, kept)
61
70
  }
62
71
  function visibilityWeight(visible: Visibility): number {
63
72
  return [...visible.values()].reduce((sum, v) => sum + v.ids.size + v.sourcePaths.size, 0)
@@ -237,21 +246,23 @@ async function buildTeamWorkspace(db: ManagedDb, store: BlobStore, snapshot: Tea
237
246
  // `{ reports, links }` as a response sends them, `spent` bytes already
238
247
  // counted against the bound; `folded` and its `lens` where the board's copy
239
248
  // left out rows App mode does not show (common/managed/finding-detail.js).
240
- // Its findings' packages and repositories are sent once each, in `values`
241
- // (common/managed/finding-values.js).
249
+ // The values its reports and their findings tell again and again (their
250
+ // severity, file, model, repository and so on) are sent once each, in
251
+ // `values`, and its findings' field names once for each shape of them, in
252
+ // `keys` (common/managed/finding-values.js).
242
253
  function encodeReports(reports: readonly TeamReport[], links: readonly string[][], spent: number,
243
254
  { folded = false, lens = null }: { folded?: false | 'rows' | 'app'; lens?: unknown } = {}): Buffer {
244
255
  let outputBytes = spent + 14
245
256
  const parts = [Buffer.from('{"reports":[')]
246
- const values = findingValueIndex()
247
- for (const [index, report] of reports.entries()) {
248
- const bytes = Buffer.from(JSON.stringify({ ...report, data: values.index(report.data) }))
257
+ const packed = packTeamReports(reports)
258
+ for (const [index, report] of packed.reports.entries()) {
259
+ const bytes = Buffer.from(JSON.stringify(report))
249
260
  outputBytes += bytes.length + 1
250
261
  if (outputBytes > MAX_REPORT_QUERY_BYTES) throw new TeamReportsError(413, 'batch-too-large')
251
262
  if (index) parts.push(Buffer.from(','))
252
263
  parts.push(bytes)
253
264
  }
254
- const tail = JSON.stringify({ ...links.length > 0 ? { links } : {}, ...folded ? { folded, lens } : {}, ...values.values.length > 0 ? { values: values.values } : {} })
265
+ const tail = JSON.stringify({ ...links.length > 0 ? { links } : {}, ...folded ? { folded, lens } : {}, ...packed.values ? { values: packed.values } : {}, ...packed.keys ? { keys: packed.keys } : {} })
255
266
  const suffix = Buffer.from(tail === '{}' ? ']}' : `],${tail.slice(1)}`)
256
267
  if (outputBytes + suffix.length > MAX_REPORT_QUERY_BYTES) throw new TeamReportsError(413, 'batch-too-large')
257
268
  parts.push(suffix)
@@ -283,9 +294,8 @@ export async function loadTeamSummary(db: ManagedDb, store: BlobStore, snapshot:
283
294
  }
284
295
  export async function loadTeamReports(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<TeamReport[]> {
285
296
  // Object consumers get their own copy, including when sharing a cold load.
286
- const body = JSON.parse((await loadTeamReportsResponse(db, store, snapshot)).toString('utf8')) as { reports: TeamReport[]; values?: unknown[] }
287
- for (const report of body.reports) expandFindingValues(report.data, body.values)
288
- return body.reports
297
+ const body = JSON.parse((await loadTeamReportsResponse(db, store, snapshot)).toString('utf8')) as { reports: TeamReport[]; values?: unknown; keys?: unknown }
298
+ return body.reports.map(report => unpackTeamReport(report, body)!)
289
299
  }
290
300
  async function teamVisibility(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<Visibility> {
291
301
  // A large snapshot may deliberately remain uncached, or be evicted by
@@ -1,2 +0,0 @@
1
- import{c as e}from"./chunk-7YFJUT2P.js";import{a as t,g as n,h as r}from"./chunk-PQPKHAI5.js";import{l as i}from"./chunk-OWIBDEJJ.js";function a(e){let t=i(e),n=new Map;for(let[r,i]of Object.entries(e?.bundle?.reason??{})){let e=new Set(Array.isArray(i)?i.filter(e=>t.has(e)):[]);e.size>0&&n.set(r,e)}return{stasis:e?.kind===`stasis`,files:t,trees:n}}var o=[[`extra`,`add`],[`metro`,`bundle:metro`]];function s(e){if(e.length!==2)return e;let t=(t,n)=>e.find((r,i)=>r.trees.has(n)&&!r.trees.has(t)&&e[1-i].trees.has(t)&&!e[1-i].trees.has(n)),n=e.map(()=>new Map);for(let[r,i]of o){let a=t(r,i);a&&n[e.indexOf(a)].set(i,r)}let r=t(`metro`,`bundle:metro`);return r&&t(`run`,`bundle`)===r&&n[e.indexOf(r)].set(`bundle`,`run`),e.map((e,t)=>n[t].size===0?e:{...e,trees:new Map([...e.trees].map(([e,r])=>[n[t].get(e)??e,r])),actual:new Map([...n[t]].map(([e,t])=>[t,e]))})}function c(e,t){if(!e.stasis||e.trees.size!==1)return null;let[[n,r]]=e.trees;return r.size===e.files.size&&!t.some(t=>t!==e&&t.trees.has(n))?n:null}var l=e=>e.trees.size===0||e.trees.size===1&&[...e.trees.values()][0].size===e.files.size,u=`reasons:`,d=(e,t)=>`${u}${JSON.stringify([e,t].toSorted())}`;function f(e){if(!e.startsWith(u))return null;try{let t=JSON.parse(e.slice(u.length));return Array.isArray(t)&&t.length===2&&t.every(e=>typeof e==`string`)?t:null}catch{return null}}function p(...e){let t=s(e.map(a));if(t.length===2&&!t.some(l)){let[e,n]=t.map(e=>[...e.trees.keys()].toSorted()),r=e.filter(e=>n.includes(e)),[i,a]=[e,n].map(e=>e.filter(e=>!r.includes(e)));if(i.length>0&&a.length>0)return[...r.map(e=>({id:`reason:${e}`,label:e})),...i.flatMap(e=>a.map(t=>({id:d(e,t),label:`${e} \u2192 ${t}`})))]}let n=t.filter(e=>c(e,t)===null),r=new Set(n.flatMap(e=>[...e.trees.keys()])),i=e=>n.some(t=>t.stasis&&(t.trees.get(e)?.size??0)<t.files.size);return[...r].some(i)?[...r].toSorted().map(e=>({id:`reason:${e}`,label:e})):[]}function m(e,t,n=``){if(!n)return[``,``];let r=f(n),i=s([e,t].map(a)),o=n.startsWith(`reason:`)?n.slice(7):null;return i.map(e=>{let t=r?r.find(t=>e.trees.has(t)):c(e,i)??o;return t==null?n:`reason:${e.actual?.get(t)??t}`})}function h(e,t=``){let n=i(e);if(!t||e?.kind!==`stasis`)return n;let r=e?.bundle?.reason?.[t.replace(/^reason:/u,``)],a=new Set(Array.isArray(r)?r:[]);return new Map([...n].filter(([e])=>a.has(e)))}function g(e,t,n,r){return JSON.stringify([e,t,n,r])}function _(e,t=``){let n=new Map;if(e?.kind!==`stasis`||!e.bundle)return n;let r=t?i(e):null,a=t?h(e,t):null;for(let[t,i]of e.bundle.imports)for(let[e,o]of i)for(let[i,s]of o){let o=typeof s==`string`?[[null,s]]:s;for(let[s,c]of o){if(a&&!a.has(e)&&(r.has(e)||!a.has(c)))continue;let o=g(e,i,t,s);n.set(o,{key:o,parent:e,specifier:i,conditions:t,platform:s,target:c})}}return n}var v=(e,{lo:t,start:n},r)=>e[n+(r-t)/2];function y(e,t,{low:n,high:r},i,a){return e===-t||e-1<n||e!==t&&e+1<=r&&v(i,a,e-1)<v(i,a,e+1)?e+1:e-1}function b(e,t,n,{first:r,n:i,m:a,d:o,...s}){e.a.fill(1,0,r).fill(1,i),e.b.fill(1,0,r).fill(1,a);let c=i,l=a;for(let r=o;r>0;r--){let i=c-l,a=y(i,r,s,t,n[r]),o=v(t,n[r],a);for(let t=a>i?o:o+1;t<c;t++)e.a[t]=e.b[t-i]=1;c=o,l=c-a}for(let t=r;t<c;t++)e.a[t]=e.b[t]=1}function x(e,t,n){let r=0,i=t.length,a=e.length,o=2*(a+i);for(;r<a&&r<i&&e[r]===t[r];)r++;for(;a>r&&i>r&&e[a-1]===t[i-1];)a--,i--;let s={high:a-r,low:r-i},c=[r],l=[{lo:1,start:0}];for(let u=0;u<=s.high-s.low;u++){let d=l[u],f=Math.min(u,s.high),p=Math.max(-u,s.low+(s.low+u&1));l.push({lo:p,start:c.length});for(let m=p;m<=f;m+=2){let f=y(m,u,s,c,d),p=v(c,d,f),h=f>m?p:p+1,g=h;for(;h<a&&h-m<i&&e[h]===t[h-m];)h++;if(o+=2+h-g,c.push(h),h>=a&&h-m>=i)return b(n,c,l,{first:r,n:a,m:i,d:u,...s}),o}}throw Error(`no edit script between two lines`)}var S=/[\p{L}\p{N}_$]+|\s+|[^\p{L}\p{N}_$\s]/gu,C=2e3,w=800,T=.6;function E(e,t){if(e.length>C)return null;let n=e.match(S)??[];return n.length>w?null:{line:e,tokens:n,words:n.map(e=>(t.has(e)||t.set(e,t.size),t.get(e)))}}function D({tokens:e,line:t},n){let r=[];for(let i=0,a=0;a<e.length;i+=e[a++].length){if(n[a])continue;let o=r.at(-1);o&&/^\s*$/u.test(t.slice(o[1],i))?o[1]=i+e[a].length:r.push([i,i+e[a].length])}return r}var O=(e,t)=>e.reduce((e,[t,n])=>e+n-t,0)/Math.max(1,t.length);function k(e,t){let n={a:e.words.map(()=>0),b:t.words.map(()=>0)},r=x(e.words,t.words,n),i={a:D(e,n.a),b:D(t,n.b)};return{ranges:i,share:n.a.includes(1)?Math.min(O(i.a,e.line),O(i.b,t.line)):1,steps:r}}function A(e,t){if(e===t)return{a:[],b:[]};let n=new Map,r=E(e,n),i=E(t,n);if(r===null||i===null)return null;let{ranges:a,share:o}=k(r,i);return o<=T?a:null}var j=200,M=5e6,ee=6,te=60,ne=3;function re(e){let t=new Map;for(let n of e?.tokens??[])t.set(n,(t.get(n)??0)+1);return t}function N(e,t){let n=new Map,r=[e,t].map(e=>e.map(e=>E(e,n))),i=r.map(e=>e.map(re)),a=0,o=(e,t,n)=>{let r=0;for(let[i,o]of e)if(a+=ne,(r+=i.length*Math.max(0,o-(t.get(i)??0)))>T*n.length)return 1/0;return r/Math.max(1,n.length)},s=(n,a)=>r[0][n]===null||r[1][a]===null?1/0:Math.min(o(i[0][n],i[1][a],e[n]),o(i[1][a],i[0][n],t[a])),c=(e,t)=>{if(a+=te,s(e,t)===1/0)return 1/0;let{share:n,steps:i}=k(r[0][e],r[1][t]);return a+=i,n<=T?n:1/0},l=new Float64Array(e.length*t.length).fill(NaN);return{share:(n,r)=>{let i=n*t.length+r;return Number.isNaN(l[i])&&(l[i]=e[n]===t[r]?0:c(n,r)),l[i]},floor:s,spent:()=>a}}function P(e,t,{share:n,spent:r}){let i=Array.from({length:e+1},()=>new Float64Array(t+1)),a=(e,t)=>n(e,t)===1/0?-1/0:1e3-n(e,t)+i[e][t];for(let n=0;n<e;n++)for(let e=0;e<t;e++)if(i[n+1][e+1]=Math.max(i[n][e+1],i[n+1][e],a(n,e)),r()>M)return null;let o=[];for(let n=e,r=t;n>0&&r>0;)i[n][r]===i[n][r-1]?r--:i[n][r]===i[n-1][r]?n--:o.push([--n,--r]);return o.toReversed()}function F(e,t,{share:n,floor:r}){let i=[];for(let a=0,o=0;a<e&&o<t;a++){let e=null,s=1/0,c=Array.from({length:Math.min(t,o+ee)-o},(e,t)=>[o+t,r(a,o+t)]);for(let[t,r]of c.toSorted((e,t)=>e[1]-t[1]||e[0]-t[0])){if(r>s)break;(n(a,t)<s||n(a,t)===s&&t<e)&&([e,s]=[t,n(a,t)])}e!==null&&(i.push([a,e]),o=e+1)}return i}function I(e,t){if(e.length>j||t.length>j)return[];let n=N(e,t);return P(e.length,t.length,n)??F(e.length,t.length,n)}var L=(e,t,r)=>n(e,t,{...r,discard:!1});function R(t){if(t===null)return``;let n=t.type===`symlink`?t.target:t.data;if(typeof n==`string`)return n.includes(`\0`)?void 0:n;if(!n.includes(0))try{return e(n)}catch{return}}var z=new Set([`none`,`all`,`change`,`trailing`]);function B({horizon:e=1/0,whitespace:t=`none`,ignoreCase:n=!1}={}){if(e!==1/0&&!(Number.isSafeInteger(e)&&e>=0))throw RangeError(`horizon must be a whole number or Infinity, not ${e}`);if(!z.has(t))throw RangeError(`whitespace must be 'none', 'all', 'change' or 'trailing', not ${t}`);if(typeof n!=`boolean`)throw TypeError(`ignoreCase must be a boolean, not ${typeof n}`);return{horizon:e,whitespace:t,ignoreCase:n}}var V=e=>e.reduce((e,{a0:t,a1:n,b0:r,b1:i})=>e+n-t+i-r,0),H=e=>e===``?[]:e.split(/(?<=\n)/u),U=e=>({...e,ignoreCase:!1,whitespace:`none`}),W=e=>(e.whitespace??`none`)!==`none`||!!e.ignoreCase;function G(e,n,i,{whitespace:a,ignoreCase:o}){try{return r(e,n,i,{format:`normal`,ignoreCase:o,whitespace:a}),!0}catch(e){if(e instanceof t)return!1;throw e}}function K(e,t,n,r,i){let a=H(e),o=H(t),s=(e,t,n,r)=>({a0:e,a1:t,b0:n,b1:r,remove:a.slice(e,t),insert:o.slice(n,r)}),c=i.flatMap(({a0:e,a1:t,b0:r,b1:i})=>e===t||r===i?[s(e,t,r,i)]:L(a.slice(e,t).join(``),o.slice(r,i).join(``),n).map(t=>s(e+t.a0,e+t.a1,r+t.b0,r+t.b1))),l=V(c)<V(r)&&G(e,t,c,n)?c:r;return V(l)<V(i)?l:i}function q(e,t,n){let r=L(e,t,n);return W(n)?K(e,t,n,r,L(e,t,U(n))):r}function J(e,t,n){let r=R(e),i=R(t);if(r===void 0||i===void 0)return{binary:!0,blocks:[],insertions:null,deletions:null};let a=r===i?[]:q(r,i,n),o=0,s=0;for(let{a0:e,a1:t,b0:n,b1:r}of a)s+=r-n,o+=t-e;return{binary:!1,blocks:a,insertions:s,deletions:o}}function Y(e,t,n,r){return G(e,t,n,B(r))}var X=/[ \t\n\v\f\r]/u,Z=e=>{let t=e.split(`
2
- `);return t.at(-1)===``&&t.pop(),t};function ie(e,t){for(let n=0,r=0;;n++,r++){let i=``,a=``;for(;n<e.length&&X.test(e[n]);)i+=e[n++];for(;r<t.length&&X.test(t[r]);)a+=t[r++];if(i!==a&&new Set(i+a).size>1)return!0;if(n>=e.length||r>=t.length)return!1}}function ae(e,t,n){try{if(!Y(e,t,n,{whitespace:`all`}))return!0}catch{return!0}let r=Z(e),i=Z(t),a=0,o=0;for(let e=0;e<=n.length;e++){let t=e<n.length?n[e].a0:r.length;for(;a<t;a++,o++)if(r[a]!==i[o]&&ie(r[a],i[o]))return!0;e<n.length&&({a1:a,b1:o}=n[e])}return!1}function oe(e,t,{extension:n=!0}={}){let r=e.split(`/`),i=t.split(`/`),a=0;for(;a<r.length-1&&a<i.length-1&&r[a]===i[a];)a++;let o=0;for(;o<r.length-a-1&&o<i.length-a-1&&r.at(-1-o)===i.at(-1-o);)o++;let s={head:a?`${r.slice(0,a).join(`/`)}/`:``,from:r.slice(a,r.length-o).join(`/`),to:i.slice(a,i.length-o).join(`/`),tail:o?`/${r.slice(-o).join(`/`)}`:``},c=s.from.lastIndexOf(`.`);return n&&!s.from.includes(`/`)&&!s.to.includes(`/`)&&c>0&&s.to.lastIndexOf(`.`)===c&&s.from.slice(0,c)===s.to.slice(0,c)?{...s,head:s.head+s.from.slice(0,c),from:s.from.slice(c),to:s.to.slice(c)}:s}function Q(e,t){return e?e.base===``?`${e.other}${t}`:t.startsWith(e.base)?t.slice(e.base.length):null:t}var $=(e,t)=>`${`../`.repeat(e.base.split(`/`).length-1)}${t}`;function se({root:e,paths:t},n,r){if(!e||n===`.`)return n;for(let e of r){let r=t.get(`${n}/${e}`);if(r?.endsWith(`/${e}`))return r.slice(0,-e.length-1)}let i=Q(e,`${n}/`);return i===null?$(e,n):i.slice(0,-1)||`.`}function ce(e,t){if(!e)return{prefix:t,from:null,to:null};let n=t.startsWith(e.other)?t:``;return{prefix:n,from:`./${e.base}${n.slice(e.other.length)}`,to:`./${n||e.other}`}}export{A as a,I as b,R as c,B as d,J as e,ae as f,oe as g,Q as h,$ as i,se as j,ce as k,p as l,m,h as n,g as o,_ as p};
@@ -1 +0,0 @@
1
- function e(e,t,a){let o=new Map;for(let t of e.onlyBase)o.set(t.pkg,{base:t.bytes,other:null});for(let t of e.onlyOther)o.set(t.pkg,{base:null,other:t.bytes});for(let t of e.changed)o.set(t.pkg,{base:t.baseBytes,other:t.otherBytes});for(let t of e.unchanged??[])o.set(t.pkg,{base:t.bytes,other:t.bytes});let s=(e,t)=>[...e.get(t)??[]].toSorted(n),c=new Set([...e.onlyBase,...e.onlyOther,...e.changed].map(e=>e.pkg));for(let e of new Set([...t.keys(),...a.keys()]))r(s(t,e),s(a,e))||c.add(e);let l=[],u=[],d=[];for(let e of c){let n=o.get(e)??{base:null,other:null},c=s(a,e),f=s(t,e),p=n.base!==null||f.length>0,m=n.other!==null||c.length>0;p&&!m?d.push({pkg:e,bytes:n.base,versions:f}):m&&!p?l.push({pkg:e,bytes:n.other,versions:c}):u.push({pkg:e,baseBytes:n.base,otherBytes:n.other,delta:n.base!==null&&n.other!==null?n.other-n.base:null,baseVersions:f,otherVersions:c,direction:f.length>0&&c.length>0&&!r(f,c)?i(f,c):null})}let f=(e,t)=>e.pkg.localeCompare(t.pkg);return{removed:d.toSorted(f),added:l.toSorted(f),changed:u.toSorted(f)}}function t(e){let t=String(e).trim().split(`+`,1)[0],n=t.indexOf(`-`);return n===-1?{core:t,pre:``}:{core:t.slice(0,n),pre:t.slice(n+1)}}function n(e,n){if(e===n)return 0;let r=t(e),i=t(n),a=r.core.split(`.`),o=i.core.split(`.`);for(let t=0;t<Math.max(a.length,o.length);t++){let r=Number(a[t]??0),i=Number(o[t]??0);if(Number.isNaN(r)||Number.isNaN(i))return e<n?-1:1;if(r!==i)return r<i?-1:1}if(r.pre===i.pre)return 0;if(!r.pre)return 1;if(!i.pre)return-1;let s=r.pre.split(`.`),c=i.pre.split(`.`);for(let e=0;e<Math.max(s.length,c.length);e++){let t=s[e],n=c[e];if(t===void 0)return-1;if(n===void 0)return 1;if(t===n)continue;let r=/^\d+$/u.test(t),i=/^\d+$/u.test(n);return r&&i?Number(t)<Number(n)?-1:1:r===i?t<n?-1:1:r?-1:1}return 0}function r(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function i(e,t){let r=e.filter(e=>!t.includes(e)).toSorted(n),i=t.filter(t=>!e.includes(t)).toSorted(n),a=e.filter(e=>t.includes(e)).toSorted(n),[o,s]=r.length>0&&i.length>0?[r,i]:r.length>0?[r,a]:[a,i];if(o.length===0||s.length===0)return`changed`;let c=(e,t)=>n(e.at(-1),t[0])<0;return c(o,s)?`up`:c(s,o)?`down`:`changed`}function a(e,t){let a=[],o=[],s=[],c=new Set([...e.keys(),...t.keys()]);for(let l of c){let c=e.get(l),u=t.get(l);if(c&&u){let e=[...c].toSorted(n),t=[...u].toSorted(n);if(r(e,t))continue;a.push({pkg:l,baseVersions:e,otherVersions:t,direction:i(e,t)})}else c?s.push({pkg:l,versions:[...c].toSorted(n)}):o.push({pkg:l,versions:[...u].toSorted(n)})}let l=(e,t)=>e.pkg.localeCompare(t.pkg);return a.sort(l),o.sort(l),s.sort(l),{updated:a,added:o,removed:s,totals:{baseDeps:e.size,otherDeps:t.size}}}export{e as a,n as b,a as c};
@@ -1,3 +0,0 @@
1
- import{a as e}from"./chunk-6CCSTJWB.js";import{d as t,e as n,g as r,h as i,i as a}from"./chunk-EMNIV37E.js";import{p as o}from"./chunk-WGQ7D5DB.js";import{J as s}from"./chunk-QRKFPLA4.js";import{a as c}from"./chunk-TUII34K2.js";var l=[`dependencies`,`security`],u={dependencies:`Dependencies`,security:`Security`},d=e(),f=Object.freeze(d.models),p=d.defaultModel,m=`x-upload-encryption`,h=1,g=1,_={name:`X25519`},v=34,y=1048576,b=65536,ee=`deepview-managed-upload.v1.content-key`;function x(e,t){let n=new Uint8Array(12);return new DataView(n.buffer).setUint32(7,e),n[11]=+!!t,n}async function S(e,t,n){let r=await crypto.subtle.importKey(`raw`,e,`HKDF`,!1,[`deriveKey`]);return await crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:t,info:c(ee)},r,{name:`AES-GCM`,length:256},!1,[n])}async function C(e){let t=new Uint8Array(await e.slice(0,b).arrayBuffer());if(t.includes(0))return!1;try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(t,{stream:!0}),!0}catch{return!1}}async function w(e,t,n){let r=await C(e),[i,a]=await Promise.all([crypto.subtle.importKey(`raw`,t,_,!1,[]),crypto.subtle.generateKey(_,!1,[`deriveBits`])]),o=new Uint8Array(v);o[0]=h,o[1]=r?g:0,o.set(new Uint8Array(await crypto.subtle.exportKey(`raw`,a.publicKey)),2);let s=await S(await crypto.subtle.deriveBits({name:`X25519`,public:i},a.privateKey,256),o,`encrypt`),c=[new Blob([o])],l=new Uint8Array(y),u=0,d=0,f=async e=>{c.push(new Blob([await crypto.subtle.encrypt({name:`AES-GCM`,iv:x(d++,e)},s,l.subarray(0,u))])),u=0},p=(r?e.stream().pipeThrough(new CompressionStream(`gzip`)):e.stream()).getReader();try{for(let e=await p.read();!e.done;e=await p.read()){n?.throwIfAborted();for(let t=0;t<e.value.length;){u===y&&await f(!1);let n=Math.min(y-u,e.value.length-t);l.set(e.value.subarray(t,t+n),u),u+=n,t+=n}}}catch(e){throw await p.cancel(e).catch(()=>{}),e}return await f(!0),new Blob(c)}var T=null,E=0;function D(){return T?.user.role??null}function O(e){if(e!==null&&!i(e))throw TypeError(`Unknown managed preview role: ${e}. Expected ${r.join(`, `)}.`);E++,T=e===null?null:{user:{id:`preview:${e}`,login:e,name:e[0].toUpperCase()+e.slice(1),role:e,avatarUrl:null,lastSeenAt:Date.now(),lastActivityAt:null},csrfToken:null}}function te(e,t){let n=new URL(e,`http://managed-preview.invalid`).pathname,r=(t?.method??`GET`).toUpperCase();if(r===`POST`&&n===`/api/auth/logout`)return Response.json({ok:!0});if(r!==`GET`)throw Error(`Changes are not saved in the managed UI preview`);if(n===`/api/auth/session`)return Response.json(T);if(n===`/api/teams`)return Response.json({teams:[]});if(n.startsWith(`/api/admin/`)&&!a(T.user.role,`manage`)||[`/api/admin/users`,`/api/admin/teams`,`/api/admin/repositories`,`/api/admin/repositories/aliases`,`/api/admin/repositories/risk`].includes(n)&&T.user.role!==`admin`)return Response.json({error:`forbidden`},{status:403});if(n===`/api/admin/repositories/risk`)return new Response(`{"type":"repos","repos":[]}
2
- {"type":"done"}
3
- `,{headers:{"content-type":`application/x-ndjson`}});let i={"/api/admin/users":{users:[T.user]},"/api/admin/teams":{teams:[],users:[T.user],repos:[],permissions:l},"/api/admin/links":{shares:[]},"/api/admin/repositories":{repositories:[],total:0,connectedCount:0,installUrl:null,tokenMissing:!1},"/api/admin/repositories/aliases":{aliases:[],repos:[]},"/api/admin/repositories/resolve":{location:null},"/api/admin/reports":{reports:[],repos:[],maxBytes:26214400},"/api/admin/bundles":{bundles:[],repos:[],maxBytes:209715200},"/api/admin/history":{history:[],total:0,page:1,limit:100,filters:{repos:[],users:[]}},"/api/admin/scan/models":{models:f,defaultModel:p},"/api/admin/scan-results":{bundles:[],results:[]},"/api/auth/profile":{profile:{login:T.user.login,name:T.user.name,githubName:T.user.name,nameAccount:null,avatarAccount:null,accounts:[]}}};return Object.hasOwn(i,n)?Response.json(i[n]):Response.json({error:`not-found`},{status:404})}var k=3145728,ne=new Set([`/api/admin/reports`,`/api/admin/bundles`,`/api/admin/deduplication`]);async function A(e,t){let n=await t(`/api/admin/uploads/key`,{credentials:`same-origin`,signal:e.signal});if(n.status===404||n.status===405)return e;if(!n.ok)return n;let r=(await n.json())?.key;if(typeof r!=`string`)throw TypeError(`The server sent an invalid upload key`);let i=new Headers(e.headers);return i.set(m,`1`),{...e,headers:i,body:await w(e.body,Uint8Array.fromBase64(r,{alphabet:`base64url`}),e.signal)}}async function j(e,t,n){let r=null;if(e!==`/api/admin/deduplication`&&t.body.size>k){let i=await n(`/api/config`,{credentials:`same-origin`,signal:t.signal});if(!i.ok)return i;let a=(await i.json()).managed,o=a?.uploadMaxBytes?.[e.endsWith(`/reports`)?`reports`:`bundles`];if(Number.isSafeInteger(o)&&o>0&&t.body.size>o)return Response.json({error:`too-large`},{status:413});let s=a?.uploadChunkBytes;Number.isSafeInteger(s)&&s>0&&s<=k&&(r=s)}let i=await A(t,n);return i instanceof Response?i:r==null||i.body.size<=k?await n(e,i):await N(e,i,n,r)}var M=3;async function N(e,t,n,r){let i=t.body,a=crypto.randomUUID(),o=e.endsWith(`/reports`)?`reports`:`bundles`,s=Math.ceil(i.size/r),c=new Headers(t.headers);c.set(`content-type`,`application/octet-stream`);let l=0,u=!1;try{let d=null,f=!1,p=(await Promise.allSettled(Array.from({length:Math.min(M,s)},async()=>{for(;!f&&l<s;){let e=l++;try{let s=await n(`/api/admin/uploads/${o}/${a}/${e}`,{...t,headers:c,body:i.slice(e*r,(e+1)*r)});s.ok||(d??=s,f=!0)}catch(e){throw f=!0,e}}}))).find(e=>e.status===`rejected`);if(p)throw p.reason;if(d)return d;let m=new Headers(t.headers);m.set(`x-upload-id`,a),m.set(`x-upload-parts`,String(s)),m.set(`x-upload-size`,String(i.size));let h=await n(e,{...t,headers:m,body:``});return u=h.ok,h}finally{if(!u&&l>0){let e=new Headers(t.headers);e.set(`x-upload-parts`,String(l)),await n(`/api/admin/uploads/${o}/${a}`,{...t,method:`DELETE`,headers:e,body:void 0,signal:AbortSignal.timeout(1e4)}).catch(()=>{})}}}async function P(e){await e.json().then(e=>e?.error,()=>null)===`view-only`&&globalThis.document?.dispatchEvent(new CustomEvent(`managed-view-only`))}async function F(e,n){if(n?.signal?.throwIfAborted(),T)return te(e,n);let r=E;async function i(e,n){if(r!==E)throw new DOMException(`Managed session changed`,`AbortError`);let i=t();if(i){if(new URL(e,globalThis.location.origin).origin!==globalThis.location.origin)throw Error(`Public workspace requests must be same-origin`);let t=new Headers(n?.headers);t.set(`x-deepview-share`,i.token),n={...n,headers:t,credentials:`omit`,redirect:`error`}}let a=await fetch(e,{...n,cache:`no-store`});if(r!==E)throw new DOMException(`Managed session changed`,`AbortError`);return a.status===403&&![`GET`,`HEAD`].includes((n?.method??`GET`).toUpperCase())&&P(a.clone()),a}return n?.method===`POST`&&ne.has(e)&&n.body instanceof Blob?await j(e,n,i):await i(e,n)}var I=(e,t)=>[...new Set([...e?.keys()??[],...t.keys()])].filter(n=>e?.get(n)!==t.get(n)),L=e=>new Map([...Map.groupBy(e,([e])=>e)].map(([e,t])=>[e,JSON.stringify(t.map(([,e])=>e).toSorted())])),R=new class{constructor(e=()=>{}){this.resources=new Map,this.session=null,this.teamCatalog=null,this.reportCatalog=null,this.bundleCatalog=null,this.generation=0,this.sessionController=new AbortController,this.notify=e}setSession(e){(this.session?.id!==e?.id||this.session?.role!==e?.role)&&this.reset(),this.session=e}reset(){this.generation++,this.sessionController.abort(),this.sessionController=new AbortController,this.invalidate(),this.session=null,this.teamCatalog=null,this.reportCatalog=null,this.bundleCatalog=null}setReportCatalog(e){let t=new Map(e.map(e=>[e.id,JSON.stringify([e.cacheKey??null,e.reports.map(e=>[e.id,e.cacheKey??null,e.visible!==!1]).toSorted(),(e.bundles??[]).map(e=>[e.id,e.filename,e.repoFullName,e.repoDirectory??``]).toSorted()])])),n=new Set(I(this.teamCatalog,t).map(e=>`team:${e}`));for(let e of this.resources.keys())if(e.startsWith(`reports:content:team:`)){let[n]=e.slice(21).split(`:`);t.has(n)&&this.teamCatalog?.get(n)===t.get(n)||this.invalidate([e])}this.teamCatalog=t;let r=L(e.flatMap(e=>e.reports.map(t=>[t.id,JSON.stringify([e.id,t.cacheKey??null])]))),i=new Set([...n,...I(this.reportCatalog,r)]);this.reportCatalog=r;for(let e of this.resources.keys()){if(!e.startsWith(`reports:content:`)||e.startsWith(`reports:content:team:`))continue;let t=e.slice(16);(!r.has(t)||i.has(t))&&(this.invalidate([e]),i.add(t))}let a=L(e.flatMap(e=>(e.bundles??[]).map(t=>[t.id,JSON.stringify([e.id,e.cacheKey??null,t.filename,t.repoFullName,t.repoDirectory??``])]))),o=I(this.bundleCatalog,a);for(let e of o)i.add(`bundle:${e}`),this.invalidate([`bundle-metadata:${e}`]);let s=o.length>0;this.bundleCatalog=a;for(let e of this.resources.keys()){if(!e.startsWith(`report-sources:`)&&!e.startsWith(`finding-history:`))continue;let[,t,r]=e.split(`:`);(t?n.has(`team:${t}`):s||i.has(r))&&this.invalidate([e])}return i}read(e){return this.resources.get(e)?.data}invalidate(e){for(let[t,n]of this.resources)e&&!e.some(e=>t===e||t.startsWith(`${e}:`))||(n.controller?.abort(),this.resources.delete(t))}async mutate(e,t){let n=this.generation,r;try{r=await e()}catch(e){throw n===this.generation&&e?.name!==`AbortError`&&this.notify(`Couldn't save changes: ${e?.message??e}`),e}if(n!==this.generation)throw new DOMException(`Managed session changed`,`AbortError`);return this.invalidate(t),r}async load(e,t,n,{signal:r,apply:i=()=>{},retryInvalidated:a=!1}={}){let o=this.generation;for(;;){r?.throwIfAborted();let s=this.resources.get(e);if(s||(s={},this.resources.set(e,s)),s.data!==void 0&&i(s.data),!s.pending){let e=s.controller=new AbortController;s.pending=(async()=>{try{let t=await n(e.signal);return e.signal.throwIfAborted(),s.data=t,t}catch(n){throw!e.signal.aborted&&n?.name!==`AbortError`&&this.notify(`Couldn't refresh ${t}: ${n?.message??n}`),n}})().finally(()=>{s.pending=null})}try{let t=await s.pending;if(r?.throwIfAborted(),this.resources.get(e)!==s)throw new DOMException(`Managed data changed`,`AbortError`);return i(t),t}catch(t){if(!a||t?.name!==`AbortError`||r?.aborted||o!==this.generation||this.resources.get(e)===s)throw t}}}}(e=>{document.dispatchEvent(new CustomEvent(`managed-notice`,{detail:{message:e}}))});function z(e){R.setSession(e)}function B(e){return R.setReportCatalog(e)}function V(){R.reset()}var H=[`package`,`repo`],U=e=>Array.isArray(e?.findings)?`findings`:Array.isArray(e?.groups)?`groups`:null;function W(e,t){let n=U(e);if(!n||!Array.isArray(t))return e;for(let r of e[n].flat())if(r&&typeof r==`object`)for(let e of H)Number.isInteger(r[e])&&(r[e]=t[r[e]]);return e}async function G(e,t=null,n={}){let r;try{r=await F(e,{credentials:`same-origin`,headers:{accept:`application/json`},...n})}catch{return t}if(r.status===401||r.status===403)return null;if(!r.ok)return t;try{return await r.json()}catch{return t}}async function K({fallback:e=null,sent:r}={}){let i=t()||D()!==null?void 0:await r;if(i===null)return null;let a=q(i);if(a!==void 0)return a;let o;try{let r=t(),i=await F(r?n(r):`/api/auth/session`,{credentials:`same-origin`,headers:{accept:`application/json`}});if(i.status===401||i.status===403)return null;if(!i.ok)return e;o=await i.json()}catch{return e}let s=q(o);return s===void 0?e:s}function q(e){let n=e?.user;if(n===null)return null;if(n!==void 0&&typeof n.login==`string`)return{id:n.id,login:n.login,name:typeof n.name==`string`?n.name:null,avatarUrl:typeof n.avatarUrl==`string`?n.avatarUrl:null,role:typeof n.role==`string`?n.role:`none`,csrfToken:typeof e.csrfToken==`string`?e.csrfToken:null,...t()?{publicShare:!0}:{},...typeof e.viewer?.login==`string`?{viewer:{id:e.viewer.id,login:e.viewer.login,name:typeof e.viewer.name==`string`?e.viewer.name:null}}:{},...!t()&&e.dependencyReview===!0?{dependencyReview:!0}:{}}}function J(e){let t=t=>Number.isSafeInteger(e?.[t])&&e[t]>=0;return e?.appMode===!1?{appMode:!1,...t(`appReports`)&&{appReports:e.appReports},...t(`findings`)&&{findings:e.findings}}:e?.appMode===!0&&t(`appFindings`)?{appMode:!0,appFindings:e.appFindings}:null}function Y(e){if(typeof e?.sha!=`string`||typeof e.github!=`string`||!Array.isArray(e.tags))return null;let t=e.details,n=e=>typeof e==`string`?e:null,r=e=>Number.isSafeInteger(e)?e:null;return{sha:e.sha,github:e.github,tags:e.tags.filter(e=>typeof e==`string`),details:typeof t?.subject==`string`?{subject:t.subject,authorName:n(t.authorName),authorLogin:n(t.authorLogin),authoredAt:r(t.authoredAt),committedAt:r(t.committedAt)}:null}}async function re({fallback:e=[],signal:r,onRevision:i}={}){let a=t(),o=a?await G(n(a),null,{signal:r}):null,s=a?{teams:o?.team?[o.team]:[]}:await G(`/api/teams`,{teams:e},{signal:r}),c=s?.teams;return Array.isArray(c)?(i?.(typeof s.revision==`string`?s.revision:null),c.filter(e=>e!=null&&typeof e.id==`string`&&typeof e.name==`string`).map(e=>({id:e.id,slug:e.slug,name:e.name,...!a&&e.dependencyReview===!0?{dependencyReview:!0}:{},...e.permissions?{permissions:{dependencies:e.permissions.dependencies===!0,security:e.permissions.security===!0}}:{},...typeof e.cacheKey==`string`?{cacheKey:e.cacheKey}:{},...J(e.app)?{app:J(e.app)}:{},repos:Array.isArray(e.repos)?e.repos.filter(e=>Number.isSafeInteger(e?.repoId)&&e.repoId>0&&typeof e.fullName==`string`).map(e=>({repoId:e.repoId,fullName:e.fullName,path:typeof e.path==`string`&&e.path?e.path:null})):[],reports:Array.isArray(e.reports)?e.reports.filter(e=>e!=null&&typeof e.id==`string`&&typeof e.filename==`string`).map(e=>({id:e.id,slug:e.slug,filename:e.filename,visible:e.visible!==!1,...e.analyzer===null||typeof e.analyzer==`string`?{analyzer:e.analyzer}:{},repoFullName:typeof e.repoFullName==`string`?e.repoFullName:``,repoDirectory:typeof e.repoDirectory==`string`?e.repoDirectory:``,...typeof e.cacheKey==`string`?{cacheKey:e.cacheKey}:{}})):[],bundles:Array.isArray(e.bundles)?e.bundles.filter(e=>e!=null&&typeof e.id==`string`&&typeof e.filename==`string`).map(e=>({id:e.id,slug:e.slug,integrity:e.integrity,byteSize:e.byteSize,repoId:e.repoId,filename:e.filename,kind:e.kind,visible:e.visible!==!1,summary:e.summary??null,summaryRetryAt:Number.isSafeInteger(e.summaryRetryAt)&&e.summaryRetryAt>0?e.summaryRetryAt:null,repoDirectory:typeof e.repoDirectory==`string`?e.repoDirectory:``,repoFullName:typeof e.repoFullName==`string`?e.repoFullName:``,commitInfo:Y(e.commitInfo)})):[]}))):s==null?[]:e}function X(e){return e?.links===void 0?[]:Array.isArray(e.links)&&e.links.every(e=>Array.isArray(e)&&e.length>=2&&e.every(e=>typeof e==`string`))?e.links:null}function Z(e,t=null){return s(e?.data)===null||typeof e.repo?.directory!=`string`||e.repo.github!==null&&typeof e.repo.github!=`string`||X(e)===null?null:{data:W(e.data,t),repo:e.repo,...e.links?{links:e.links}:{}}}async function ie(e,{signal:t}={}){return Z(await G(`/api/reports/${encodeURIComponent(e)}`,null,{signal:t}))}async function ae(e,{signal:t}={}){let n=[...new Set(e)];if(n.length===0)return[];let r=await G(`/api/reports/query`,null,{method:`POST`,signal:t,headers:{accept:`application/json`,"content-type":`application/json`},body:JSON.stringify({ids:n})});if(!Array.isArray(r?.reports)||r.reports.length!==n.length)return null;let i=new Map;for(let e of r.reports){let t=Z(e);if(!t||!n.includes(e.id)||i.has(e.id))return null;i.set(e.id,t)}let a=X(r);return a===null?null:e.map(e=>({...i.get(e),...a.length>0?{links:a}:{}}))}async function oe(e,{signal:t,reportId:n=null,lite:r=!1}={}){let i=new URLSearchParams(n===null?{}:{reportId:n});r&&i.set(`lite`,`1`);let a=await G(`/api/teams/${encodeURIComponent(e)}/reports${i.size>0?`?${i}`:``}`,null,{signal:t});if(!Array.isArray(a?.reports))return null;let o=[],s=new Set;for(let e of a.reports){let t=Z(e,a.values);if(!t||typeof e.id!=`string`||typeof e.filename!=`string`||s.has(e.id))return null;s.add(e.id),o.push({id:e.id,filename:e.filename,...t,...e.opensAsApp===!0?{opensAsApp:!0}:{}})}let c=X(a);return c===null?null:(Object.defineProperties(o,{links:{value:c},...[`rows`,`app`].includes(a.folded)?{folded:{value:a.folded},lens:{value:a.lens??null}}:{}}),o)}function Q(e){return e?`?team=${encodeURIComponent(e)}`:``}async function se(e,{reportId:t,...n}={}){let r=t==null?``:`?reportId=${encodeURIComponent(t)}`,i=await G(`/api/teams/${encodeURIComponent(e)}/annotations${r}`,null,n),{reports:a,entries:o,comments:s,issues:c={}}=i??{};if(!a||typeof a!=`object`||Array.isArray(a)||!o||typeof o!=`object`||Array.isArray(o)||!Array.isArray(s)||!c||typeof c!=`object`||Array.isArray(c)||Object.values(a).some(e=>!Array.isArray(e)||e.some(e=>typeof e!=`string`))||s.some(e=>!e||typeof e.findingId!=`string`))return null;let l=new Map;for(let[e,t]of s.entries()){let n=t.findingId,r=l.get(n)??[];r.push(e),l.set(n,r)}let u=new Map,d=new Map,f=typeof i.revision==`string`?i.revision:null;return Object.assign(e=>{if(!Object.hasOwn(a,e))return null;if(d.has(e))return d.get(e);let t=JSON.stringify(a[e]),n=u.get(t);if(!n){let r=[...new Set(a[e])],i=r.flatMap(e=>l.get(e)??[]);n={entries:Object.fromEntries(r.filter(e=>Object.hasOwn(o,e)).map(e=>[e,o[e]])),comments:i.toSorted((e,t)=>e-t).map(e=>s[e]),issues:Object.fromEntries(r.filter(e=>Object.hasOwn(c,e)).map(e=>[e,c[e]]))},u.set(t,n)}return d.set(e,n),n},{revision:f})}async function ce(e,t,n){let r=(await G(`/api/reports/${encodeURIComponent(e)}/triage${Q(t)}`,null,n))?.entries;return typeof r==`object`&&r&&!Array.isArray(r)?r:null}async function le(e,n,r=null){if(t())return[];let i=r===null?``:`?reportId=${encodeURIComponent(r)}`,a=await G(`/api/teams/${encodeURIComponent(e)}/fixes${i}`,null,{signal:n});return Array.isArray(a?.fixes)?a.fixes:null}async function ue(e,t,n){let r=await G(`/api/reports/${encodeURIComponent(e)}/comments${Q(t)}`,null,n);return Array.isArray(r?.comments)?r.comments:null}async function de(e,{findingId:t,body:n,commentId:r=null,version:i},a,o){let s=r==null?``:`/${encodeURIComponent(r)}`;try{let c=await F(`/api/reports/${encodeURIComponent(e)}/comments${s}${Q(o)}`,{method:r==null?`POST`:`PATCH`,credentials:`same-origin`,headers:{"content-type":`application/json`,...a?{"x-csrf-token":a}:{}},body:JSON.stringify(r==null?{findingId:t,body:n}:{body:n,version:i})});return{status:c.status,comment:c.ok?(await c.json()).comment:null}}catch{return{status:0,comment:null}}}async function fe(e,t,n,r,i){try{return(await F(`/api/reports/${encodeURIComponent(e)}/comments/${encodeURIComponent(t)}${Q(i)}`,{method:`DELETE`,credentials:`same-origin`,headers:{"content-type":`application/json`,...r?{"x-csrf-token":r}:{}},body:JSON.stringify({version:n})})).status}catch{return 0}}async function pe(e,t,n,r){try{return(await F(`/api/reports/${encodeURIComponent(e)}/triage${Q(r)}`,{method:`POST`,credentials:`same-origin`,headers:{"content-type":`application/json`,...n?{"x-csrf-token":n}:{}},body:JSON.stringify({entries:t})})).status}catch{return 0}}function $(e){e&&(location.href=e)}async function me(e){if(t())location.href=`/`;else{try{await F(`/api/auth/logout`,{method:`POST`,credentials:`same-origin`,headers:e?{"x-csrf-token":e}:{}})}catch{}location.reload()}}async function he(e,t){let n=await F(`/api/auth/view-as`,{method:`POST`,credentials:`same-origin`,headers:{"content-type":`application/json`,...t?{"x-csrf-token":t}:{}},body:JSON.stringify({userId:e})});if(!n.ok)throw Error(`HTTP ${n.status}`);location.assign(`/`)}async function ge(e){try{await F(`/api/auth/view-as`,{method:`DELETE`,credentials:`same-origin`,headers:e?{"x-csrf-token":e}:{}})}catch{}location.assign(o[`admin-users`])}async function _e(e){let t=await F(`/api/teams/${encodeURIComponent(e)}/share`,{credentials:`same-origin`});if(!t.ok)throw Error(`Could not load public links (${t.status})`);return(await t.json()).shares}async function ve(e,t,{id:n,revoke:r=!1,dependencies:i=!1,security:a=!1}={}){let o=n?`/${encodeURIComponent(n)}`:``,s=await F(`/api/teams/${encodeURIComponent(e)}/share${o}`,{method:r?`DELETE`:n?`PATCH`:`POST`,credentials:`same-origin`,headers:{"x-csrf-token":t,"content-type":`application/json`},...r?{}:{body:JSON.stringify({dependencies:i,security:a})}});if(!s.ok)throw Error(`Could not ${r?`revoke`:n?`update`:`create`} public link (${s.status})`);return s.json()}async function ye(e,t){let n=await F(`/api/bundles/${encodeURIComponent(e)}/download`,{credentials:`same-origin`});if(!n.ok)throw Error(`Could not download bundle (${n.status})`);let r=URL.createObjectURL(await n.blob()),i=document.createElement(`a`);i.href=r,i.download=t,i.click(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}export{u as a,D as b,O as c,F as d,R as e,z as f,B as g,V as h,K as i,re as j,ie as k,ae as l,oe as m,Q as n,se as o,ce as p,le as q,ue as r,de as s,fe as t,pe as u,$ as v,me as w,he as x,ge as y,_e as z,ve as A,ye as B};
@@ -1 +0,0 @@
1
- import{j as e}from"./chunk-QRKFPLA4.js";var t=new Set([`overview`,`graph`,`treemap`,`compare`,`advisories`,`issues`,`code`,`search`,`terminal`]),n=/^\d+$/u;function r(e){for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(n<32||n===127)return!0}return!1}var i=512;function a(e){return typeof e==`string`&&e.length>0&&e.length<=i&&!r(e)}function o(e){return a(e)&&!n.test(e)}function s(e){return e===`completed`||e===`not_planned`||e===`duplicate`?e:`unknown`}function c(e){let[t,n,r]=e.split(`/`);return r===void 0&&t!==void 0&&n!==void 0&&t.length<=39&&/^[a-zA-Z\d](?:-?[a-zA-Z\d])*$/u.test(t)&&n.length<=100&&n!==`.`&&n!==`..`&&/^[a-zA-Z\d._-]+$/u.test(n)}function l(e,t){if(typeof e!=`string`||e.length>2048)return null;let n;try{n=new URL(e)}catch{return null}if(n.href!==e||n.origin!==`https://github.com`||n.username||n.password)return null;let r=t.exec(n.pathname);if(!r)return null;let i=`${r[1]}/${r[2]}`,a=Number(r[3]);return!c(i)||!Number.isSafeInteger(a)||a<=0?null:{repo:i,number:a}}function u(e){return l(e,/^\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:\/(?:files|commits|checks))?\/?$/u)}function d(e){return l(e,/^\/([^/]+)\/([^/]+)\/issues\/(\d+)\/?$/u)}function f(e){let t=u(e);if(t)return{...t,kind:`pull`};let n=d(e);return n?{...n,kind:`issue`}:null}function p(e){return`${e.repo.toLowerCase()}#${e.kind}:${e.number}`}var m=/^(?=.{1,214}$)(?:@[\w.-]+\/[\w-]|[\dA-Za-z])[\w.-]*$/u,h=/^(?=.{1,256}$)[\dA-Za-z][\w.+-]*$/u,ee=/^@[\da-z~-][\w.~-]*$/u,g=/^[\da-f]{64}$/u;function _(e){return typeof e==`string`&&m.test(e)}function v(e){return typeof e==`string`&&h.test(e)}function y(e){return typeof e==`string`&&g.test(e)}function b(e){return typeof e==`string`&&e.length>0&&e.length<=1024&&!/[\p{Cc}\\]/u.test(e)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function te(e){if(typeof e!=`string`)return null;let t=e.trim().toLowerCase(),n=t.startsWith(`@`)?t:`@${t}`;return n.length<=214&&ee.test(n)?n:null}var x=Object.freeze({all:`all`,team:`team`,repo:`repository`}),S=(e,t)=>e===`team`?typeof t==`string`&&/^[A-Za-z0-9_-]+$/u.test(t):e===`repo`&&Number.isSafeInteger(t)&&t>0;function ne(e){let t=e.riskScope??`team`,n=e.riskTarget??null;return!Object.hasOwn(x,t)||n!=null&&!S(t,n)?null:`/manage/risk/${x[t]}${n==null?``:`/${n}`}`}function C(e){if(e===`/manage/risk/team`||e===`/manage/repositories/risk`)return{view:`manage-repo-risk`};if(!e.startsWith(`/manage/risk/`))return;let t=/^\/manage\/risk\/(?:(all)|(team)\/([A-Za-z0-9_-]+)|repository(?:\/([1-9]\d*))?)$/u.exec(e);if(!t)return null;if(t[1])return{view:`manage-repo-risk`,riskScope:`all`};let[n,r]=t[2]?[`team`,t[3]]:[`repo`,t[4]==null?null:Number(t[4])];return r!=null&&!S(n,r)?null:{view:`manage-repo-risk`,riskScope:n,...r==null?{}:{riskTarget:r}}}var w=[[`whitespace`,`hideWhitespace`],[`type-only`,`hideTypes`]],T=[[`on`,`indented`],[`folded`,`folded`]];function E(e){let t=w.filter(([,t])=>e[t]===!0).map(([e])=>e),n=T.find(([,t])=>t===e.pretty)?.[0];return[...t.length>0?[`hide=${t.join(`,`)}`]:[],...n?[`pretty=${n}`]:[]]}function D(e){let t=new Set(e.getAll(`hide`).flatMap(e=>e.split(`,`))),n=T.find(([t])=>t===e.get(`pretty`))?.[1];return{...Object.fromEntries(w.filter(([e])=>t.has(e)).map(([,e])=>[e,!0])),...n?{pretty:n}:{}}}var O=e=>typeof e==`string`&&e.length>0&&e.length<=256&&!/[\p{Cc}]/u.test(e);function re(t){let n=t.get(`repo`),r=new Set((t.get(`severity`)??``).split(`,`)),i=e.filter(e=>r.has(e)),a={...O(n)?{repo:n}:{},...i.length>0?{severities:i}:{}};return Object.keys(a).length>0?{filters:a}:{}}function ie(t){let n=e.filter(e=>t?.severities?.includes(e)),r=[...O(t?.repo)?[`repo=${encodeURIComponent(t.repo).replaceAll(`%2F`,`/`)}`]:[],...n.length>0?[`severity=${n.join(`,`)}`]:[]];return r.length>0?`?${r.join(`&`)}`:``}var k=new Set([`code`,`diff`]),A=e=>k.has(e)?`code`:`overview`,j=e=>k.has(e)?{compareMode:`code`}:{},M=e=>k.has(e)?`/code`:``,N=Object.freeze({manage:`/manage`,"manage-bundles":`/manage/bundle`,"manage-scans":`/manage/scans`,"manage-reports":`/manage/report`,"manage-repos":`/manage/repositories`,"manage-repo-risk":`/manage/risk`,"admin-users":`/manage/users`,"manage-teams":`/manage/team`,"manage-import":`/manage/import`,"manage-links":`/manage/links`,"manage-deduplication":`/manage/deduplication`,"manage-history":`/manage/history`}),P=new Set([`workspace-reports`,`workspace-bundles`,`workspace-repositories`,`workspace-dependencies`,`workspace-risk`]),F=new Set([`pulls`,`versions`,`branch`,`reviews`]),I=e=>e.view===`workspace-dependencies`&&e.dependencyTab!=null?{dependencyTab:e.dependencyTab}:{};function L(e){if(!o(e)||e===`.`||e===`..`)return null;try{return`/finding/${encodeURIComponent(e)}`}catch{return null}}function ae(e){if(!e)return null;if(e.view===`home`)return`/`;if(e.view===`reviews`)return`/my/reviews`;if(e.view===`profile`)return`/my/profile`;if(e.view===`npm`)return B(e);if(e.view===`repository-code`)return se(e);if(P.has(e.view)){let t=I(e).dependencyTab??`pulls`;return!/^[A-Za-z0-9_-]+$/u.test(e.teamSlug??``)||!F.has(t)?null:`/team/${e.teamSlug}/${e.view.slice(10)}${t===`pulls`?``:`/${t}`}`}if(e.view===`bundles`){if(!/^[A-Za-z0-9_-]+$/u.test(e.bundleSlug??``)||[e.teamSlug,e.compareSlug].some(e=>e!=null&&!/^[A-Za-z0-9_-]+$/u.test(e)))return null;let n=e.bundleTab??`overview`;if(!t.has(n))return null;let r=e.teamSlug?`/team/${e.teamSlug}`:`/manage`,i=n===`code`&&Z(e.file)?`/${e.file}`:``,a=i&&Z(e.line)?`#L${e.line}${Z(e.endLine)&&e.endLine>e.line?`-L${e.endLine}`:``}`:``,o=n===`compare`&&e.compareSlug!=null?`/${e.compareSlug}${M(e.compareMode)}`:``;return`${r}/bundle/${e.bundleSlug}${n===`overview`?``:`/${n}`}${i}${o}${a}`}if(e.view===`manage-repo-risk`)return ne(e);if(Object.hasOwn(N,e.view)){let t=N[e.view];return e.view===`manage-deduplication`&&e.linkId?`${t}?report=${encodeURIComponent(e.linkId)}`:e.view===`manage-bundles`&&Number.isSafeInteger(e.createRepoId)&&e.createRepoId>0?`${t}?createRepo=${e.createRepoId}`:e.view===`manage-scans`&&e.scanMode===`link`?`${t}?mode=link`:e.view===`manage-scans`&&e.bundleId?`${t}?bundle=${encodeURIComponent(e.bundleId)}${e.scanMode===`dependencies`?`&mode=dependencies`:``}`:e.view===`manage-history`&&e.actor?`${t}?actor=${encodeURIComponent(e.actor)}`:t}if(![`findings`,`files`].includes(e.view)||!e.teamSlug||[e.teamSlug,e.reportSlug].some(e=>e!=null&&!/^[A-Za-z0-9_-]+$/u.test(e)))return null;let n=`/team/${encodeURIComponent(e.teamSlug)}`,r=e.reportSlug?`/report/${encodeURIComponent(e.reportSlug)}`:``;if(e.finding){let t=L(e.finding.id);return e.view===`findings`&&t?`${n}${r}${t}`:null}return e.view===`files`?`${n}${r}/files`:`${n}${r}${r?``:ie(e.filters)}`}var R=new Set([`overview`,`code`,`search`,`compare`,`review`,`treemap`]),z=e=>y(e?.hash)&&(e.repoId==null?e.commit==null&&e.path==null:(J(e.repoId)||typeof e.repoId==`string`&&c(e.repoId))&&q.test(e.commit??``)&&(e.path==null||b(e.path)));function B(e){if(e.packageName==null)return`/npm`;let t=e.bundleTab??`overview`;if(!_(e.packageName)||e.packageSpec!=null&&!v(e.packageSpec)||!R.has(t)||e.compareSpec!=null&&!v(e.compareSpec))return null;if(t===`review`){if(e.reviewPackage!=null&&!_(e.reviewPackage)||e.reviewSpec!=null&&!v(e.reviewSpec)||e.patch!=null&&!z(e.patch)||e.basePatch!=null&&(!y(e.basePatch)||e.reviewPackage==null))return null;let t=e.reviewPackage==null?``:`/${e.reviewPackage}${e.reviewSpec==null?``:`@${e.reviewSpec}`}`,{patch:n}=e,r=[...n==null?[]:[`patch=${n.hash}`],...n?.repoId==null?[]:[`repo=${n.repoId}&commit=${n.commit}`],...n?.path==null?[]:[`path=${n.path.split(`/`).map(encodeURIComponent).join(`/`)}`],...e.basePatch==null?[]:[`basePatch=${e.basePatch}`],...E(e)].join(`&`);return`/npm/${e.packageName}${e.packageSpec==null?``:`@${e.packageSpec}`}/review${t}${r?`?${r}`:``}`}let n=t===`code`&&Z(e.file)?`/${e.file}`:``,r=n&&Z(e.line)?`#L${e.line}${Z(e.endLine)&&e.endLine>e.line?`-L${e.endLine}`:``}`:``,i=t===`compare`&&e.compareSpec!=null?`/${e.compareSpec}${M(e.compareMode)}`:``;return`/npm/${e.packageName}${e.packageSpec==null?``:`@${e.packageSpec}`}${t===`overview`?``:`/${t}`}${n}${i}${r}`}function V(e,t,n){let r=/^\/npm\/((?:@[^/@]+\/)?[^/@]+)(?:@([^/]+))?\/review(?:\/((?:@[^/@]+\/)?[^/@]+)(?:@([^/]+))?)?$/u.exec(e);if(r){if(!_(r[1])||r[2]!=null&&!v(r[2])||r[3]!=null&&!_(r[3])||r[4]!=null&&!v(r[4]))return null;let e=r[3]&&/^\d+\.\d+\.\d+(?:[-+].*)?$/u.test(r[3])&&r[4]==null,t=[`repo`,`commit`,`path`].some(e=>n.has(e))?{repoId:/^[1-9]\d*$/u.test(n.get(`repo`)??``)?Number(n.get(`repo`)):n.get(`repo`),commit:n.get(`commit`)}:{},i=n.has(`patch`)?{hash:n.get(`patch`),...t,...n.has(`path`)?{path:n.get(`path`)}:{}}:null,a=n.get(`basePatch`);return i&&!z(i)||a!==null&&(!y(a)||!r[3])?null:{view:`npm`,packageName:r[1],packageSpec:r[2]??null,bundleTab:`review`,...r[3]?{reviewPackage:e?r[1]:r[3],reviewSpec:e?r[3]:r[4]??null}:{},...i?{patch:i}:{},...a?{basePatch:a}:{},...D(n)}}let i=/^\/npm(?:\/((?:@[^/@]+\/)?[^/@]+)(?:@([^/]+))?(?:\/(code|search|compare|treemap)(?:\/([^/]+)(?:\/([a-z]+))?)?)?)?$/u.exec(e);if(!i)return;if(i[1]==null)return{view:`npm`};if(!_(i[1])||i[2]!=null&&!v(i[2]))return null;let a={view:`npm`,packageName:i[1],packageSpec:i[2]??null,bundleTab:i[3]??`overview`};if(i[4]==null)return a;if(a.bundleTab===`compare`)return v(i[4])&&(i[5]==null||k.has(i[5]))?{...a,compareSpec:i[4],...j(i[5])}:null;if(a.bundleTab!==`code`)return null;let o=Number(i[4]);return!i[5]&&/^[1-9]\d*$/u.test(i[4])&&Number.isSafeInteger(o)?{...a,file:o,...Q(t)}:null}var H=new Set([`code`,`search`,`treemap`,`compare`,`commits`,`issues`,`pulls`,`agents`,`pulse`,`replay`]),U=new Set([`commits`,`issues`,`pulls`,`agents`,`pulse`,`replay`]),W=new Map([[`issues`,new Set([`closed`])],[`pulls`,new Set([`closed`])],[`pulse`,new Set([`week`,`quarter`,`year`])],[`replay`,new Set([`100`,`1000`])]]),G=/^[a-z][a-z\d-]{0,31}$/u,K=(e,t)=>e===`agents`?typeof t==`string`&&G.test(t)&&t!==`all`:W.get(e)?.has(t)===!0,q=/^[a-f\d]{40}$/u,oe=500,J=e=>Number.isSafeInteger(e)&&e>0;function Y(e){return typeof e==`string`&&(e===``||e.length<=oe&&!/[\p{Cc}\\]/u.test(e)&&e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`&&e===e.trim()))}function se(e){let t=e.bundleTab??`code`,n=e.path??``;if(!J(e.repoId)||e.commit!=null&&!q.test(e.commit)||!Y(n)||!H.has(t)||e.compareCommit!=null&&!q.test(e.compareCommit))return null;let r=n?`?path=${n.split(`/`).map(encodeURIComponent).join(`/`)}`:``;if(e.commit==null)return`/repo/${e.repoId}${r}`;let i=t===`code`&&Z(e.file)?`/code/${e.file}`:t===`code`?``:`/${t}`,a=t===`compare`&&e.compareCommit!=null?`/${e.compareCommit}${M(e.compareMode)}`:``,o=K(t,e.subtab)?`/${e.subtab}`:``,s=t===`code`&&Z(e.file)&&Z(e.line)?`#L${e.line}${Z(e.endLine)&&e.endLine>e.line?`-L${e.endLine}`:``}`:``;return`/repo/${e.repoId}/${e.commit}${i}${a}${o}${r}${s}`}function X(e){let t=/^\/(?:repo|manage\/code)\/([1-9]\d*)(?:\/([a-f\d]{40})(?:\/(code|search|treemap|compare|commits|history|issues|pulls|agents|pulse|replay)(?:\/([^/]+)(?:\/([a-z]+))?)?)?)?$/u.exec(e.pathname.replace(/\/$/u,``));if(!t)return;let n=Number(t[1]),r=e.searchParams.get(`path`)??``,i=t[3]===`history`?`commits`:t[3]??`code`;if(!J(n)||!Y(r))return null;let a={view:`repository-code`,repoId:n,commit:t[2]??null,path:r,bundleTab:i};if(t[4]==null)return a;if(i===`compare`)return q.test(t[4])&&(t[5]==null||k.has(t[5]))?{...a,compareCommit:t[4],...j(t[5])}:null;if(U.has(i))return t[5]==null&&K(i,t[4])?{...a,subtab:t[4]}:null;let o=Number(t[4]);return i===`code`&&t[5]==null&&/^[1-9]\d*$/u.test(t[4])&&Number.isSafeInteger(o)?{...a,file:o,...Q(e.hash)}:null}function Z(e){return Number.isSafeInteger(e)&&e>0}function Q(e){let t=/^#L([1-9]\d*)(?:-L([1-9]\d*))?$/u.exec(e),[n,r]=t?[Number(t[1]),Number(t[2]??t[1])]:[];return!Z(n)||!Z(r)?{}:n===r?{line:n}:{line:Math.min(n,r),endLine:Math.max(n,r)}}function ce(e){let n=e.pathname.replace(/\/$/u,``)||`/`;if(n===`/`||n===`/index.html`)return{view:`home`};if(n===`/my/reviews`)return{view:`reviews`};if(n===`/my/profile`){let t=e.searchParams.get(`link-error`);return{view:`profile`,...t&&/^[a-z-]{1,64}$/u.test(t)?{linkError:t}:{}}}let r=Object.keys(N).find(e=>N[e]===n);if(r){let t=Number(e.searchParams.get(`createRepo`));return{view:r,...r===`manage-deduplication`&&e.searchParams.get(`report`)?{linkId:e.searchParams.get(`report`)}:{},...r===`manage-bundles`&&Number.isSafeInteger(t)&&t>0?{createRepoId:t}:{},...r===`manage-history`&&e.searchParams.get(`actor`)?{actor:e.searchParams.get(`actor`)}:{},...r===`manage-scans`?e.searchParams.get(`mode`)===`link`?{scanMode:`link`}:e.searchParams.get(`bundle`)?{bundleId:e.searchParams.get(`bundle`),...e.searchParams.get(`mode`)===`dependencies`?{scanMode:`dependencies`}:{}}:{}:{}}}let a=/^(?:\/team\/([A-Za-z0-9_-]+)|\/manage)\/bundle\/([A-Za-z0-9_-]+)(?:\/([a-z]+)(?:\/([A-Za-z0-9_-]+)(?:\/([a-z]+))?)?)?$/u.exec(n);if(a){let n=a[3]??`overview`;if(!t.has(n))return null;let r={view:`bundles`,teamSlug:a[1]??null,bundleSlug:a[2],bundleTab:n};if(a[4]==null)return r;if(n===`compare`)return a[5]==null||k.has(a[5])?{...r,compareSlug:a[4],...j(a[5])}:null;let i=Number(a[4]);return n!==`code`||a[5]||!/^[1-9]\d*$/u.test(a[4])||!Number.isSafeInteger(i)?null:{...r,file:i,...Q(e.hash)}}let o=V(n,e.hash,e.searchParams);if(o!==void 0)return o;let s=X(e);if(s!==void 0)return s;let c=/^\/team\/([A-Za-z0-9_-]+)\/(reports|bundles|repositories|dependencies|risk)$/u.exec(n);if(c)return{view:`workspace-${c[2]}`,teamSlug:c[1]};let l=/^\/team\/([A-Za-z0-9_-]+)\/dependencies\/([a-z]+)$/u.exec(n);if(l)return F.has(l[2])?{view:`workspace-dependencies`,teamSlug:l[1],dependencyTab:l[2]}:null;let u=/^\/team\/([^/]+)(?:\/report\/([^/]+))?(?:\/(files)|\/finding\/([^/]+))?$/u.exec(n);if(!u)return C(n)??null;try{let t=decodeURIComponent(u[1]),n=u[2]?decodeURIComponent(u[2]):null;if([t,n].some(e=>e!=null&&!/^[A-Za-z0-9_-]+$/u.test(e))||u[4]?.length>i*9)return null;let r=u[4]?decodeURIComponent(u[4]):null;return r!=null&&!L(r)?null:u[3]?{view:`files`,teamSlug:t,reportSlug:n}:r==null?{view:`findings`,teamSlug:t,reportSlug:n,...n==null?re(e.searchParams):{}}:{view:`findings`,teamSlug:t,reportSlug:n,finding:{id:r}}}catch{return null}}function $(e,t,n=[]){if(P.has(e.view)){let n=t.filter(t=>t.slug===e.teamSlug);return n.length===1?{view:e.view,teamId:n[0].id,...I(e)}:null}if(e.view===`bundles`){let{teamSlug:r,bundleSlug:i,compareSlug:a,compareMode:o,...s}=e,c=r==null?[]:t.filter(e=>e.slug===r);if(r!=null&&c.length!==1)return null;let l=c[0],u=r==null?n:t.flatMap(e=>e.bundles??[]),d=e=>new Set(u.filter(t=>t.slug===e).map(e=>e.id)),f=d(i),p=(l?.bundles??n).find(e=>e.slug===i);if(!i||!p||f.size!==1)return null;let m=a==null?null:d(a),h=m?.size===1?{compareId:[...m][0],...j(o)}:{};return{...s,teamId:l?.id??null,bundleId:p.id,...h}}if(![`findings`,`files`].includes(e.view))return e;let{teamSlug:r,reportSlug:i,...a}=e,o=t.filter(e=>e.slug===r),s=r&&o.length===1?o[0]:null,c=new Set(t.flatMap(e=>e.reports??[]).filter(e=>e.slug===i).map(e=>e.id)),l=i!=null&&c.size===1?[...c][0]:null;return a.finding?{...a,teamId:s?.id??null,reportId:l,teamOnly:i==null}:s?i==null?{...a,teamId:s.id,reportId:null}:(s.reports??[]).some(e=>e.id===l)?{...a,teamId:s.id,reportId:l}:null:null}function le(e,t,n=[]){if(P.has(e.view)){let n=t.find(t=>t.id===e.teamId),r={view:e.view,teamSlug:n?.slug,...I(e)};return n?.slug&&$(r,t)?r:null}if(e.view===`bundles`){let{teamId:r,bundleId:i,compareId:a,compareMode:o,...s}=e,c=t.find(e=>e.id===r);if(r!=null&&!c?.slug)return null;let l=(c?.bundles??n).find(e=>e.id===i);if(!l?.slug)return null;let u=a==null?null:(r==null?n:t.flatMap(e=>e.bundles??[])).find(e=>e.id===a),d={...s,teamSlug:c?.slug??null,bundleSlug:l.slug,...u?.slug?{compareSlug:u.slug,...j(o)}:{}},f=$(d,t,n);if(!f)return null;if(d.compareSlug!=null&&f.compareId!==a){let{compareSlug:e,compareMode:t,...n}=d;return n}return d}if(![`findings`,`files`].includes(e.view))return e;let{teamId:r,reportId:i,...a}=e,o=t.find(e=>e.id===r),s=i==null?null:o?.reports?.find(e=>e.id===i);if(!o?.slug||i!=null&&!s?.slug)return null;let c={...a,teamSlug:o.slug,reportSlug:s?.slug??null},l=$(c,t);return l?.teamId===o.id&&l.reportId===(s?.id??null)?c:null}export{t as a,i as b,o as c,s as d,u as e,d as f,f as g,p as h,_ as i,v as j,y as k,b as l,te as m,A as n,j as o,N as p,F as q,ae as r,R as s,H as t,U as u,K as v,ce as w,$ as x,le as y};