@preventive/triage 1.0.0-alpha.71 → 1.0.0-alpha.73

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 (145) hide show
  1. package/common/bundle-sources.d.ts +2 -0
  2. package/common/bundle-sources.js +19 -2
  3. package/common/finding-duplicates.js +5 -0
  4. package/common/finding-filters.js +45 -4
  5. package/common/line-diff.d.ts +2 -2
  6. package/common/line-diff.js +20 -8
  7. package/common/managed/finding-detail.js +1 -1
  8. package/common/managed/review-view-routes.js +23 -0
  9. package/common/managed/risk-routes.js +30 -0
  10. package/common/managed/routes.js +11 -6
  11. package/common/managed/team-app.d.ts +8 -6
  12. package/common/managed/team-app.js +15 -3
  13. package/common/stasis-files.d.ts +5 -0
  14. package/common/stasis-files.js +20 -0
  15. package/common/stasis-tgz.d.ts +6 -0
  16. package/common/stasis-tgz.js +27 -0
  17. package/common/workspace-app.js +20 -0
  18. package/out/activity.js +2 -4
  19. package/out/{chunk-2F3CYNPZ.js → chunk-2IHCVA3Y.js} +1 -1
  20. package/out/{chunk-HAZKDK4M.js → chunk-2V6Q4ZOZ.js} +1 -1
  21. package/out/{chunk-RRBIJL2B.js → chunk-4IW3VD3H.js} +1 -1
  22. package/out/chunk-4YZOXAXR.js +2 -0
  23. package/out/chunk-5NUDNLJA.js +6 -0
  24. package/out/chunk-5YP7P5KA.js +1 -0
  25. package/out/chunk-6VOB5WXX.js +2 -0
  26. package/out/chunk-74JZTGTO.js +11 -0
  27. package/out/chunk-7YFJUT2P.js +1 -0
  28. package/out/chunk-A4BBBHQU.js +1 -0
  29. package/out/{chunk-4ISO5F7Y.js → chunk-ADMVRLNP.js} +1 -1
  30. package/out/chunk-BIWPZT4E.js +52 -0
  31. package/out/{chunk-HETCVNO4.js → chunk-BLPHP4U3.js} +1 -1
  32. package/out/{chunk-Y5ZHFNBD.js → chunk-BXQCCW7F.js} +1 -1
  33. package/out/{chunk-JFL7WLRV.js → chunk-CU3FPB3P.js} +1 -1
  34. package/out/chunk-CXVBTUK3.js +4 -0
  35. package/out/{chunk-M37X4LCF.js → chunk-EXQQ5VQJ.js} +1 -1
  36. package/out/{chunk-NXATZJQ2.js → chunk-GSNSP3EF.js} +1 -1
  37. package/out/chunk-GV5U7OLP.js +40 -0
  38. package/out/{chunk-JOXLZXMI.js → chunk-GX5UXWT4.js} +1 -1
  39. package/out/{chunk-YF4M5OCI.js → chunk-I6UQQKAH.js} +1 -1
  40. package/out/{chunk-UCP3JRE2.js → chunk-LVW7WWV4.js} +1 -1
  41. package/out/chunk-NEFCZAIY.js +11 -0
  42. package/out/{chunk-TOXMUOIW.js → chunk-OQS2USZM.js} +1 -1
  43. package/out/chunk-PQPKHAI5.js +15 -0
  44. package/out/chunk-PX5DLFSD.js +1 -0
  45. package/out/chunk-QBFT2DDR.js +1 -0
  46. package/out/{chunk-GZ46SSTF.js → chunk-RGNF4OH6.js} +1 -1
  47. package/out/chunk-RLLA4GHZ.js +1 -0
  48. package/out/chunk-ROHACH7V.js +3 -0
  49. package/out/chunk-ROWUGPID.js +1 -0
  50. package/out/{chunk-QMVOEBWC.js → chunk-S2ZIKK45.js} +1 -1
  51. package/out/chunk-SSPDMA6D.js +1 -0
  52. package/out/chunk-TD7RVUTT.js +2 -0
  53. package/out/{chunk-4XIH7YTX.js → chunk-UH6NZBSU.js} +1 -1
  54. package/out/{chunk-M3Y6SLC4.js → chunk-UJP4PQJA.js} +1 -1
  55. package/out/{chunk-PAD2JHZT.js → chunk-UJSJMXEG.js} +1 -1
  56. package/out/{chunk-E3LFSUDJ.js → chunk-VYYUMYVW.js} +1 -1
  57. package/out/{chunk-VRX2APNA.js → chunk-XVKDPU4D.js} +1 -1
  58. package/out/chunk-Y2XGV3RC.js +8 -0
  59. package/out/chunk-YCEMQETS.js +255 -0
  60. package/out/client-managed-import.js +3 -3
  61. package/out/client-managed.js +30 -27
  62. package/out/compare.js +16 -25
  63. package/out/dialogs.js +38 -38
  64. package/out/graph.js +14 -14
  65. package/out/index.html +32 -52
  66. package/out/scan.js +2 -2
  67. package/out/terminal.js +239 -240
  68. package/out/view.css +1 -1
  69. package/out/view.js +15 -15
  70. package/package.json +21 -13
  71. package/risk/actions/resolve.js +56 -19
  72. package/risk/actions/uses.js +27 -9
  73. package/risk/actions/workflow.js +75 -2
  74. package/risk/files/characters.js +11 -0
  75. package/risk/files/hosts.js +4 -4
  76. package/risk/files/readability.js +5 -2
  77. package/risk/files/runs-code.js +12 -25
  78. package/risk/files/script.js +141 -19
  79. package/risk/files/source-map-link.js +43 -0
  80. package/risk/index.d.ts +24 -7
  81. package/risk/index.js +1 -0
  82. package/risk/npm/assess.js +1 -1
  83. package/risk/npm/compare.js +9 -30
  84. package/risk/npm/diff.js +1 -1
  85. package/risk/npm/held.js +6 -2
  86. package/risk/npm/registry.js +5 -2
  87. package/risk/npm/tarball.js +79 -22
  88. package/server-managed/bundle-advisories.ts +12 -36
  89. package/server-managed/bundle-build-worker.js +29 -11
  90. package/server-managed/bundle-build.ts +4 -3
  91. package/server-managed/bundle-cache.ts +53 -13
  92. package/server-managed/bundle.ts +45 -13
  93. package/server-managed/comparison.ts +3 -3
  94. package/server-managed/db-methods.ts +54 -17
  95. package/server-managed/db-neon.ts +9 -2
  96. package/server-managed/db-schema.ts +12 -2
  97. package/server-managed/db.ts +4 -1
  98. package/server-managed/dependency-reviews.ts +8 -5
  99. package/server-managed/github-errors.ts +22 -0
  100. package/server-managed/github-requests.ts +4 -2
  101. package/server-managed/http.ts +336 -76
  102. package/server-managed/management.ts +10 -4
  103. package/server-managed/npm-delta.ts +17 -2
  104. package/server-managed/npm-kept.ts +6 -0
  105. package/server-managed/npm-packages.ts +30 -29
  106. package/server-managed/npm-patch.ts +9 -9
  107. package/server-managed/package-entry-points.ts +54 -6
  108. package/server-managed/pull-dependencies.ts +4 -1
  109. package/server-managed/rename-diff-worker.js +11 -7
  110. package/server-managed/rename-diff.ts +5 -4
  111. package/server-managed/report-opening.ts +77 -0
  112. package/server-managed/report-sources.ts +2 -1
  113. package/server-managed/repository-aliases.ts +34 -0
  114. package/server-managed/repository-browser.ts +87 -32
  115. package/server-managed/repository-code.ts +6 -3
  116. package/server-managed/repository-dependency-reviews.ts +21 -0
  117. package/server-managed/repository-issues.ts +15 -9
  118. package/server-managed/repository-risk-read.ts +50 -4
  119. package/server-managed/repository-risk.ts +9 -2
  120. package/server-managed/stasis-config.ts +97 -5
  121. package/server-managed/stasis-dependencies.ts +7 -4
  122. package/server-managed/team-reports.ts +5 -3
  123. package/server-managed/type-only-proof.js +26 -4
  124. package/server-managed/upstream-cache.ts +18 -12
  125. package/server-managed/workspace-shares.ts +4 -4
  126. package/out/chunk-2HGKTQ5Q.js +0 -52
  127. package/out/chunk-45HTR22K.js +0 -4
  128. package/out/chunk-4RS3NDOG.js +0 -1
  129. package/out/chunk-7GJNLCXF.js +0 -15
  130. package/out/chunk-CGRIZ5M5.js +0 -1
  131. package/out/chunk-CQIT5UNK.js +0 -1
  132. package/out/chunk-D6NVKGGG.js +0 -10
  133. package/out/chunk-DTAR2BB6.js +0 -247
  134. package/out/chunk-MPXVKVPF.js +0 -3
  135. package/out/chunk-NB4JBTKK.js +0 -2
  136. package/out/chunk-QPGM3DTI.js +0 -42
  137. package/out/chunk-VFWMQ3LG.js +0 -2
  138. package/out/chunk-VG5RH6KN.js +0 -2
  139. package/out/chunk-WFDXHPT2.js +0 -12
  140. package/out/chunk-WMFDQS2L.js +0 -11
  141. package/out/chunk-WREU7JAG.js +0 -1
  142. /package/out/{chunk-JMG5DXII.js → chunk-7HP2VYIC.js} +0 -0
  143. /package/out/{chunk-HOB3YPS5.js → chunk-K4XJHM2T.js} +0 -0
  144. /package/out/{chunk-4EMM6UCD.js → chunk-QI66YA4F.js} +0 -0
  145. /package/out/{chunk-G3LY2FV4.js → chunk-WCDYSIKG.js} +0 -0
@@ -19,10 +19,13 @@ export async function sessionAdmin(db: ManagedSql, sessionId: string): Promise<{
19
19
  }
20
20
 
21
21
  export type ContentMutation = { type: 'delete' } | { type: 'repo'; repoId: number | null; directory: string } | { type: 'visibility'; visible: boolean }
22
+ // A report's alone: whether it opens on Confirmed whatever Confirmed hides,
23
+ // switched on only where its content offers it (report-opening.ts).
24
+ export type ReportMutation = ContentMutation | { type: 'opening'; confirmedDefault: boolean }
22
25
  type RemovalRepo = Pick<ManagedRepo, 'repoId' | 'fullName' | 'addedAt'>
23
26
  type RemovalAnnotations = { reports: string; ids: string[] }
24
27
  export interface ManagementStore {
25
- mutateReport(sessionId: string, id: string, change: ContentMutation): Promise<{ report: ReportRecord; user: StoredUser }>
28
+ mutateReport(sessionId: string, id: string, change: ReportMutation): Promise<{ report: ReportRecord; user: StoredUser }>
26
29
  mutateBundle(sessionId: string, id: string, change: ContentMutation): Promise<{ bundle: ManagedBundle; user: StoredUser }>
27
30
  // A repeated upload/build of stored bytes (see reuseBundle). Renames need the
28
31
  // access other bundle mutations need; a server build labels the row anyway.
@@ -33,7 +36,7 @@ export interface ManagementStore {
33
36
  }
34
37
  type ManagementDb = Pick<ManagedDb, 'sessionWithUser' | 'getReport' | 'getBundle' | 'listReports' | 'listReportsForRepo'
35
38
  | 'listBundlesForRepo' | 'listAllRepos' | 'listSelectedRepos' | 'userCanReadReport' | 'userCanReadBundle' | 'userCanReadRepoPath'
36
- | 'deleteReport' | 'setReportRepo' | 'setReportVisible' | 'deleteBundle' | 'setBundleRepo' | 'setBundleVisible' | 'reuseBundle'
39
+ | 'deleteReport' | 'setReportRepo' | 'setReportVisible' | 'setReportConfirmedDefault' | 'deleteBundle' | 'setBundleRepo' | 'setBundleVisible' | 'reuseBundle'
37
40
  | 'deleteReportsForRepo' | 'deleteBundlesForRepo' | 'deleteRepo' | 'deleteTriage' | 'recordActivity'>
38
41
 
39
42
  // Only immutable bytes/format and repository membership affect the overlap
@@ -52,21 +55,24 @@ export function managementMethods(db: ManagementDb): ManagementStore {
52
55
  if (!roleAtLeast(s.user.role, role)) throw new ManagedMutationError(403, 'forbidden')
53
56
  return s.user
54
57
  }
55
- async function destination(user: { id: string; role: string }, change: ContentMutation) {
58
+ async function destination(user: { id: string; role: string }, change: ReportMutation) {
56
59
  if (change.type !== 'repo' || change.repoId === null) return
57
60
  if (!(await db.listSelectedRepos()).some(repo => repo.repoId === change.repoId)) throw new ManagedMutationError(400, 'bad-repo')
58
61
  if (user.role !== 'admin' && !await db.userCanReadRepoPath(user.id, change.repoId, change.directory)) throw new ManagedMutationError(403, 'repo-forbidden')
59
62
  }
60
63
  return {
61
- async mutateReport(sessionId: string, id: string, change: ContentMutation) {
64
+ async mutateReport(sessionId: string, id: string, change: ReportMutation) {
62
65
  const user = await authorize(sessionId, 'manage')
63
66
  const report = await db.getReport(id)
64
67
  if (!report || (user.role !== 'admin' && report.uploadedBy !== user.id && !await db.userCanReadReport(user.id, id))) throw new ManagedMutationError(404, 'no-report')
65
68
  if (user.role !== 'admin' && report.repoId !== null && !await db.userCanReadReport(user.id, id)) throw new ManagedMutationError(403, 'repo-forbidden')
66
69
  if (change.type === 'repo' && report.repoEmbedded) throw new ManagedMutationError(409, 'repo-in-report')
70
+ // Off is always allowed, even of one whose content no longer offers it.
71
+ if (change.type === 'opening' && change.confirmedDefault && report.confirmedOffered !== true) throw new ManagedMutationError(409, 'not-offered')
67
72
  if (change.type !== 'visibility') await destination(user, change)
68
73
  if (change.type === 'delete') await db.deleteReport(id)
69
74
  else if (change.type === 'visibility') await db.setReportVisible(id, change.visible)
75
+ else if (change.type === 'opening') await db.setReportConfirmedDefault(id, change.confirmedDefault)
70
76
  else await db.setReportRepo(id, change.repoId, change.directory)
71
77
  return { report, user }
72
78
  },
@@ -17,7 +17,7 @@
17
17
  // it (`kept`), what a version holds never changing. Access is the caller's
18
18
  // to check.
19
19
  import { createHash } from 'node:crypto'
20
- import type { KeptStore } from './npm-kept.ts'
20
+ import { type KeptStore, VERSION_DELTA_KEPT_MS } from './npm-kept.ts'
21
21
  import { type Lru, lru } from './lru.ts'
22
22
  import { NpmPackageError, type NpmPackageFile, npmFileText } from './npm-packages.ts'
23
23
  import { workerTurns } from './worker-turns.ts'
@@ -62,7 +62,7 @@ function texts(files: NpmPackageFile[] | null) {
62
62
  let length = 0
63
63
  const binaries: NpmPackageFile[] = []
64
64
  const read = (files ?? []).flatMap(file => {
65
- const text = npmFileText(file.bytes)
65
+ const text = file.link === undefined ? npmFileText(file.bytes) : null
66
66
  if (text === null) { binaries.push(file); return [] }
67
67
  length += text.length
68
68
  return [[file.path, text] as [string, string]]
@@ -104,6 +104,21 @@ type Side = { integrity: string; files: () => Promise<NpmPackageFile[]> }
104
104
  // A delta's key: the integrities of the version it is against, or none, and
105
105
  // of the version.
106
106
  export const deltaKey = (base: string | null, other: string) => `${base ?? '(empty)'}\0${other}`
107
+ // The same of two public versions by their names and versions (`(empty)`
108
+ // for none), as npm never gives one other files: its key in
109
+ // npmVersionDeltaStore.
110
+ export const versionDeltaKey = (name: string, version: string, otherName: string, otherVersion: string) =>
111
+ `${name}@${version}\0${otherVersion === '(empty)' ? '(empty)' : `${otherName}@${otherVersion}`}`
112
+ // Those of `keys` (versionDeltaKey) kept, by key, as of `now`: one kept past
113
+ // VERSION_DELTA_KEPT_MS not, though no write has pruned it yet.
114
+ export async function keptVersionDeltas(keys: string[], kept: KeptStore<NpmDelta>, now = Date.now()): Promise<Map<string, NpmDelta>> {
115
+ const found = new Map<string, NpmDelta>()
116
+ for (const [key, row] of keys.length > 0 ? await kept.readMany([...new Set(keys)]) : []) {
117
+ const known = now - row.at < VERSION_DELTA_KEPT_MS ? deltaOf(row.value) : null
118
+ if (known) found.set(key, known)
119
+ }
120
+ return found
121
+ }
107
122
 
108
123
  // The delta of `other` (its integrity, and how to read its files) against
109
124
  // `base`, or none, as held, else shared with one asked before it, else
@@ -215,6 +215,12 @@ export const pullDependencyStore = <T>(db: UpstreamCacheStore, debug = false): K
215
215
  // The lines a version changes against another, or none (npm-delta.ts), by
216
216
  // both sides' integrities, each kept HISTORY_PAGE_KEPT_MS.
217
217
  export const npmDeltaStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'npm/deltas', HISTORY_PAGE_KEPT_MS, debug)
218
+ // The same, of public versions alone, by their names and versions
219
+ // (npm-delta.ts versionDeltaKey), which npm never gives other files: read
220
+ // without their integrities, so without asking npm, or keeping what it tells
221
+ // of them, for them. Each read for VERSION_DELTA_KEPT_MS alone, pruned or not.
222
+ export const VERSION_DELTA_KEPT_MS = 30 * 24 * 60 * 60_000
223
+ export const npmVersionDeltaStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'npm/version-deltas', VERSION_DELTA_KEPT_MS, debug)
218
224
  // The versions a repository's lockfiles locked at the commit its dependencies
219
225
  // are reviewed since (pull-dependency-reviews.ts reviewBaseline), by the
220
226
  // commit, which never change: kept as its history's pages are, never stored
@@ -17,6 +17,7 @@ import { resolve } from 'node:path'
17
17
  import { ArchiveError, type Entry, unpack } from '@preventive/archive/tar.js'
18
18
  import { isExactVersion } from '@preventive/upstream/semver.js'
19
19
  import { isNpmPackageName, isNpmPackageSpec, npmPackageScope } from '../common/managed/npm-packages.js'
20
+ import { NPM_SYMLINKS_ABOVE, npmTarLayout } from '../risk/index.js'
20
21
  import type { Role } from '../common/managed/roles.ts'
21
22
  import { npmManifest, npmVersionFields, plainObject, stringRecord } from './npm-manifest.ts'
22
23
  import { keepJson, readKeptJson, upstreamCachePath } from './upstream-cache.ts'
@@ -379,7 +380,8 @@ export function npmPublishTime(doc: Pick<NpmVersionDocument, 'name' | 'version'
379
380
  }
380
381
  }
381
382
 
382
- export interface NpmPackageFile { path: string; bytes: Uint8Array }
383
+ // A symlink's `link` is its target as stored, its bytes that target's: no text, whatever they spell.
384
+ export interface NpmPackageFile { path: string; bytes: Uint8Array; link?: string }
383
385
 
384
386
  // Paths in the order a package's files are read in (readNpmTar), and
385
387
  // Compare's: by their UTF-16 code units, as a plain sort orders them.
@@ -389,16 +391,21 @@ export const pathOrder = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
389
391
  // it, and the entries, files and bytes it may hold, a package's unless given.
390
392
  export interface TarReading { symlinksAbove?: number; maxEntries?: number; maxFiles?: number; maxBytes?: number }
391
393
 
392
- // The regular files of a tar stream, by package path: npm drops the first
393
- // component (`package/`, or whatever the archive used), and a file at the top
394
- // is not extracted. The stream is read by @preventive/archive, which refuses
395
- // one malformed, a name or a symlink that would climb out of it -- a symlink
396
- // past `symlinksAbove` levels above it, none unless given -- and a name
397
- // repeated as another entry, and gives up past `maxEntries` before reading
398
- // on; a file under another top directory at the same path replaces an
399
- // earlier one, as extraction would. Directories, links and devices hold no
400
- // file content and are skipped.
401
- export function readNpmTar(tar: Uint8Array, { symlinksAbove = 0, maxEntries = MAX_NPM_TAR_ENTRIES, maxFiles = MAX_NPM_PACKAGE_FILES,
394
+ // The regular files of a tar stream, by package path, as npm and pnpm install
395
+ // them (risk's npmTarLayout): each name as stored past its first component,
396
+ // whatever the archive used (`package/`, a release's own directory, `.`), and
397
+ // a file under no directory at its name, as pnpm installs it. The stream is
398
+ // read by @preventive/archive, which refuses one malformed, a name that would
399
+ // climb out of it, an absolute symlink or one past `symlinksAbove` levels
400
+ // above it, any unless given, and a name repeated as another entry, and
401
+ // gives up past `maxEntries` before reading on. Every file is read, whether
402
+ // or not an installer installs it, a hard link as its target's bytes, a
403
+ // symlink for where it points. Where
404
+ // the files conflict (two that differ at one path, as under two top
405
+ // directories, a file within another), it is refused as `tarball-conflict`,
406
+ // never read as one installer does. Directories and devices hold no file
407
+ // content and are skipped.
408
+ export function readNpmTar(tar: Uint8Array, { symlinksAbove = NPM_SYMLINKS_ABOVE, maxEntries = MAX_NPM_TAR_ENTRIES, maxFiles = MAX_NPM_PACKAGE_FILES,
402
409
  maxBytes = MAX_NPM_PACKAGE_BYTES }: TarReading = {}): NpmPackageFile[] {
403
410
  let entries: Entry[]
404
411
  try { entries = unpack(tar, { maxEntries, symlinksAbove }) }
@@ -406,17 +413,8 @@ export function readNpmTar(tar: Uint8Array, { symlinksAbove = 0, maxEntries = MA
406
413
  if (err instanceof ArchiveError) throw err.limited ? new NpmPackageError(413, 'package-too-large') : new NpmPackageError(422, 'bad-tarball')
407
414
  throw err
408
415
  }
409
- const files = new Map<string, Uint8Array>()
410
- let total = 0
411
- for (const { name, type, data } of entries) {
412
- const slash = name.indexOf('/')
413
- if ((type !== 'file' && type !== 'contiguous-file') || slash === -1) continue
414
- const path = name.slice(slash + 1)
415
- total += data.length - (files.get(path)?.length ?? 0)
416
- files.set(path, data)
417
- if (files.size > maxFiles || total > maxBytes) throw new NpmPackageError(413, 'package-too-large')
418
- }
419
- return [...files].map(([path, bytes]) => ({ path, bytes })).toSorted((a, b) => pathOrder(a.path, b.path))
416
+ const files = npmTarLayout(entries, { maxFiles, maxBytes }, (code) => { throw new NpmPackageError(code === 'package-too-large' ? 413 : 422, code) })
417
+ return [...files].map(([path, file]) => ({ path, ...file })).toSorted((a, b) => pathOrder(a.path, b.path))
420
418
  }
421
419
 
422
420
  const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
@@ -444,15 +442,18 @@ const ROW_LENGTH = 80
444
442
 
445
443
  // The files as the viewer gets them: `[path, bytes, text]`, text null for a
446
444
  // file that is not UTF-8, which instead carries its bytes' sha256, so a
447
- // comparison of two versions tells a changed one from an unchanged one. They
448
- // may take `maxLength` characters of JSON, a package's unless given.
449
- export function npmFileRows(files: NpmPackageFile[], maxLength = MAX_NPM_JSON_LENGTH): ([string, number, string] | [string, number, null, string])[] {
445
+ // comparison of two versions tells a changed one from an unchanged one; a
446
+ // symlink so too, its target last. They may take `maxLength` characters of
447
+ // JSON, a package's unless given.
448
+ export function npmFileRows(files: NpmPackageFile[], maxLength = MAX_NPM_JSON_LENGTH): ([string, number, string] | [string, number, null, string, string?])[] {
450
449
  let length = 0
451
- return files.map(({ path, bytes }) => {
452
- const text = npmFileText(bytes)
453
- length += ROW_LENGTH + jsonLength(path) + (text === null ? 0 : jsonLength(text))
450
+ return files.map(({ path, bytes, link }) => {
451
+ const text = link === undefined ? npmFileText(bytes) : null
452
+ length += ROW_LENGTH + jsonLength(path) + jsonLength(text ?? link ?? '')
454
453
  if (length > maxLength) throw new NpmPackageError(413, 'package-too-large')
455
- return text === null ? [path, bytes.byteLength, null, `sha256-${createHash('sha256').update(bytes).digest('base64')}`] : [path, bytes.byteLength, text]
454
+ const digest = () => `sha256-${createHash('sha256').update(bytes).digest('base64')}`
455
+ if (text !== null) return [path, bytes.byteLength, text]
456
+ return link === undefined ? [path, bytes.byteLength, null, digest()] : [path, bytes.byteLength, null, digest(), link]
456
457
  })
457
458
  }
458
459
 
@@ -262,23 +262,23 @@ function applied(text: string, hunks: PatchHunk[]): string {
262
262
  // A version's `files` with `patch` applied, in the order of their paths, as
263
263
  // its tarball's are read; a file it changes the text of must be text. One it
264
264
  // creates holds its first hunk's first lines, in place of any there, as
265
- // patch-package writes it.
265
+ // patch-package writes it. A symlink, which pnpm never installs, is none to patch.
266
266
  export function patchedFiles(files: NpmPackageFile[], patch: PatchedFile[]): NpmPackageFile[] {
267
- const byPath = new Map(files.map(file => [file.path, file.bytes]))
267
+ const byPath = new Map(files.map(file => [file.path, file]))
268
268
  const encoder = new TextEncoder()
269
269
  for (const file of patch) {
270
270
  if (file.created) {
271
271
  const first = file.hunks[0]?.parts[0]
272
- byPath.set(file.path, encoder.encode(first ? `${first.lines.join('\n')}${first.unended ? '' : '\n'}` : ''))
272
+ byPath.set(file.path, { path: file.path, bytes: encoder.encode(first ? `${first.lines.join('\n')}${first.unended ? '' : '\n'}` : '') })
273
273
  continue
274
274
  }
275
275
  const source = file.from ?? file.path
276
- const bytes = byPath.get(source)
277
- if (!bytes) throw doesNotApply()
276
+ const was = byPath.get(source)
277
+ if (!was || was.link !== undefined) throw doesNotApply()
278
278
  if (file.deleted) { byPath.delete(source); continue }
279
- let next = bytes
279
+ let next = was.bytes
280
280
  if (file.hunks.length > 0) {
281
- const text = npmFileText(bytes)
281
+ const text = npmFileText(was.bytes)
282
282
  if (text === null) throw doesNotApply()
283
283
  next = encoder.encode(applied(text, file.hunks))
284
284
  }
@@ -286,9 +286,9 @@ export function patchedFiles(files: NpmPackageFile[], patch: PatchedFile[]): Npm
286
286
  if (byPath.has(file.path)) throw doesNotApply()
287
287
  byPath.delete(source)
288
288
  }
289
- byPath.set(file.path, next)
289
+ byPath.set(file.path, { path: file.path, bytes: next })
290
290
  }
291
- return [...byPath].map(([path, bytes]) => ({ path, bytes })).toSorted((a, b) => pathOrder(a.path, b.path))
291
+ return [...byPath.values()].toSorted((a, b) => pathOrder(a.path, b.path))
292
292
  }
293
293
 
294
294
  // About the bytes a patch read takes: the characters of its paths and of the
@@ -1,10 +1,13 @@
1
1
  import { Buffer } from 'node:buffer'
2
2
  import { buildableEntry } from './bundle-build.ts'
3
3
  import { normalizeTeamPath } from './repo-path.ts'
4
- import { MAX_STASIS_CONFIG_BYTES, parseStasisConfig } from './stasis-config.ts'
4
+ import { type ConfigListing, MAX_STASIS_CONFIG_BYTES, configEntries, parseStasisConfig } from './stasis-config.ts'
5
5
 
6
6
  export const MAX_PACKAGE_BYTES = 256 * 1024
7
7
  const MAX_ENTRY_POINTS = 100
8
+ // The directories a stasis.config.json's patterns are matched in, at most,
9
+ // its own among them: past these, a pattern matches none of what is below.
10
+ const MAX_PATTERN_LISTINGS = 20
8
11
 
9
12
  // Declared paths, not a Node resolver: never guess defaults, expand export
10
13
  // patterns, or execute package code. Keep every suggestion in its package.
@@ -35,11 +38,54 @@ export function packageEntryPoints(manifest: unknown, directory: string): string
35
38
  return [...paths]
36
39
  }
37
40
 
41
+ type ListingEntry = { name?: unknown; path?: unknown; type?: unknown; sha?: unknown; submodule_git_url?: unknown }
42
+ type ListedName = { name: string; directory: boolean; sha: string | null }
43
+
44
+ const listingEntries = (listing: unknown): ListingEntry[] =>
45
+ Array.isArray(listing) ? listing.filter((entry): entry is ListingEntry => !!entry && typeof entry === 'object') : []
46
+ const listedName = (name: unknown, directory: boolean, sha: unknown): ListedName[] =>
47
+ typeof name !== 'string' || !name || name.includes('/') || name === '.' || name === '..' ? []
48
+ : [{ name, directory, sha: typeof sha === 'string' && /^[a-f\d]{40}$/iu.test(sha) ? sha : null }]
49
+
50
+ // The names of `directory` as its contents list them: each a directory's,
51
+ // with its tree, or a file's (a symlink's too). A submodule's are none.
52
+ const contentsNames = (listing: unknown, directory: string) => listingEntries(listing).flatMap(entry =>
53
+ entry.path !== (directory ? `${directory}/${String(entry.name)}` : entry.name) || entry.submodule_git_url ? []
54
+ : entry.type === 'dir' || ['file', 'symlink'].includes(entry.type as string) ? listedName(entry.name, entry.type === 'dir', entry.sha) : [])
55
+
56
+ // The names a tree lists, as contentsNames gives them.
57
+ const treeNames = (tree: unknown) => listingEntries(tree).flatMap(entry =>
58
+ entry.type === 'tree' || entry.type === 'blob' ? listedName(entry.path, entry.type === 'tree', entry.sha) : [])
59
+
60
+ // The directories under a stasis.config.json's, as its patterns are matched
61
+ // in them: its own as `listing`, its contents, names it, each below as the
62
+ // tree its parent's names, read once, at most MAX_PATTERN_LISTINGS of them.
63
+ // One past those, or whose tree can't be read, lists none.
64
+ function patternListings(directory: string, listing: unknown, read: (suffix: string) => Promise<unknown>): (path: string) => Promise<ConfigListing | null> {
65
+ const listed = new Map<string, Promise<ListedName[] | null>>([['', Promise.resolve(contentsNames(listing, directory))]])
66
+ const list = (path: string): Promise<ListedName[] | null> => {
67
+ const known = listed.get(path)
68
+ if (known) return known
69
+ const parent = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''
70
+ const name = path.slice(parent ? parent.length + 1 : 0)
71
+ const reading = listed.size >= MAX_PATTERN_LISTINGS ? Promise.resolve(null) : list(parent).then(async names => {
72
+ const tree = names?.find(entry => entry.name === name && entry.directory)?.sha
73
+ return tree ? treeNames((await read(`/git/trees/${tree}`) as { tree?: unknown } | null)?.tree) : null
74
+ }).catch(() => null)
75
+ listed.set(path, reading)
76
+ return reading
77
+ }
78
+ return list
79
+ }
80
+
38
81
  // The entries a stasis.config.json in `directory` lists, as repository paths:
39
- // the ones a server build takes, which it builds with their options there.
40
- export function configEntryPoints(text: string, directory: string): string[] {
82
+ // the ones a server build takes, which it builds with their options there. A
83
+ // pattern's are the files it matches, as `list` lists the directories below
84
+ // the file's ('' for its own).
85
+ export async function configEntryPoints(text: string, directory: string, list: (path: string) => Promise<ConfigListing | null> = () => Promise.resolve(null)): Promise<string[]> {
86
+ const config = parseStasisConfig(text, directory)
41
87
  const paths: string[] = []
42
- for (const key of parseStasisConfig(text, directory) ?? []) {
88
+ for (const key of config ? await configEntries(config, list) : []) {
43
89
  const path = directory ? `${directory}/${key}` : key
44
90
  if (buildableEntry(path) && paths.length < MAX_ENTRY_POINTS) paths.push(path)
45
91
  }
@@ -69,10 +115,12 @@ export async function readPackageEntryPoints(sha: string, directory: string, rea
69
115
 
70
116
  // A stasis.config.json whose entries Stasis can't tell lists none here;
71
117
  // building them reports why (config-invalid), as it does options Stasis refuses.
72
- export async function readConfigEntryPoints(sha: string, directory: string, read: (suffix: string) => Promise<unknown>): Promise<string[]> {
118
+ // Its patterns are matched in `listing`, the contents of its directory, and
119
+ // the trees below it.
120
+ export async function readConfigEntryPoints(sha: string, directory: string, read: (suffix: string) => Promise<unknown>, listing: unknown = []): Promise<string[]> {
73
121
  try {
74
122
  const text = await readBlobText(sha, read, MAX_STASIS_CONFIG_BYTES)
75
- return text === null ? [] : configEntryPoints(text, directory)
123
+ return text === null ? [] : await configEntryPoints(text, directory, patternListings(directory, listing, read))
76
124
  } catch {
77
125
  return []
78
126
  }
@@ -98,8 +98,11 @@ export type AddedPackage = LockedPackage & { was?: string[]; base?: { name: stri
98
98
  // (`lockfile-unsupported`, Bun's) or GitHub having none at a commit compared.
99
99
  // A stasis.config.json a review holds to is told as one too, by its own path
100
100
  // (stasis-dependencies.ts stasisDirectory), or as `stasis-pending` or `stasis-failed`.
101
- export type DirectoryDependencies = { paths: string[] } & ({ added: AddedPackage[]; more: number; locked: LockedPackage[]; moreLocked: number }
101
+ export type DirectoryDependencies = { paths: string[]; builds?: StasisBuild[] } & ({ added: AddedPackage[]; more: number; locked: LockedPackage[]; moreLocked: number }
102
102
  | { error: string; detail?: string })
103
+ // A Stasis build a stasis.config.json's directory reads (stasis-dependencies.ts
104
+ // stasisDirectory): of the commit, and whether it is made, or failed, as kept.
105
+ export interface StasisBuild { commit: string; built: boolean }
103
106
  // What a pull request's lockfiles add: the commits compared (`base`, its
104
107
  // merge base, and `head`); each directory's, of those it changes a lockfile
105
108
  // in; and `cut` where it changes more files than GitHub lists, or lockfiles
@@ -2,16 +2,19 @@
2
2
  // server's event loop by @preventive/compare's renamedDiffs: the old side given
3
3
  // the new side's names, not formatted again (each line where the old side's was),
4
4
  // diffed with whitespace changes shown and hidden, and the blocks checked to
5
- // take it to the new side. `{ before, blocks, reason, reads, marks,
5
+ // take it to the new side. `{ before, blocks, reason, reads, assumed, marks,
6
6
  // ignoringWhitespace }`: the old side as diffed, the change blocks, why the
7
7
  // old side is as it was where its names could not be given safely, the
8
8
  // properties through which either side reads names (a view marks renamed
9
9
  // lines rather than hiding them where any are read, as a rename may then
10
- // change what the code does), and the blocks of the diff of the files as they
11
- // are that differ in renamed names alone; `ignoringWhitespace` the blocks and
12
- // those marked with whitespace changes hidden, as diff -b hides them. Blocks
13
- // that would not take the old side to the new are thrown, and so answer
14
- // nothing.
10
+ // change what the code does), what a name renamed at a script's top level
11
+ // was taken as its own for (`module`, the other side being one; `minified`,
12
+ // a minifier having renamed them all), which it is not where the script runs
13
+ // as a classic one, its top level's names globals, and the blocks of the diff
14
+ // of the files as they are that differ in renamed names alone;
15
+ // `ignoringWhitespace` the blocks and those marked with whitespace changes
16
+ // hidden, as diff -b hides them. Blocks that would not take the old side to
17
+ // the new are thrown, and so answer nothing.
15
18
  import { parentPort, workerData } from 'node:worker_threads'
16
19
  import { renamedDiffs } from '@preventive/compare/names.js'
17
20
 
@@ -20,7 +23,8 @@ const diff = await renamedDiffs(before, after, { extension, otherExtension, whit
20
23
  // A check that should never fail did, or a step gave way: told, the file shown with its names.
21
24
  for (const warning of diff.warnings) console.warn(`managed: rename diff: ${warning}`)
22
25
  const [shown, hidden] = diff.diffs
23
- const answer = { before: diff.before, blocks: shown.blocks, reason: diff.reason, reads: diff.reads, marks: shown.marks, ignoringWhitespace: { blocks: hidden.blocks, marks: hidden.marks } }
26
+ const answer = { before: diff.before, blocks: shown.blocks, reason: diff.reason, reads: diff.reads, assumed: diff.assumed, marks: shown.marks,
27
+ ignoringWhitespace: { blocks: hidden.blocks, marks: hidden.marks } }
24
28
  // Node worker messages have no browser target origin.
25
29
  // oxlint-disable-next-line unicorn/require-post-message-target-origin
26
30
  parentPort.postMessage(answer)
@@ -4,7 +4,7 @@
4
4
  // has them (pretty-print.ts), then diffed by @preventive/compare's
5
5
  // renamedDiffs in a worker, off the event loop and two at a time per process,
6
6
  // with whitespace changes shown and hidden both. Answered as Brotli-encoded
7
- // JSON, `{ before, blocks, reason, reads, marks, ignoringWhitespace }`
7
+ // JSON, `{ before, blocks, reason, reads, assumed, marks, ignoringWhitespace }`
8
8
  // (rename-diff-worker.js), the two files' hashes, `hash` and `otherHash`, and
9
9
  // those of the two copies diffed, `prettyHash` and `otherPrettyHash`, which
10
10
  // the viewer checks are those it asked about and draws: one file's asked for
@@ -49,7 +49,7 @@ const KEPT_DIFFS = 32
49
49
  // `blocks` and `marks` with whitespace changes shown, `ignoringWhitespace`'s
50
50
  // hidden as diff -b hides them.
51
51
  export interface RenameDiff {
52
- before: string; blocks: ChangeBlock[]; reason: string | null; reads: string[]; marks: ChangeBlock[]
52
+ before: string; blocks: ChangeBlock[]; reason: string | null; reads: string[]; assumed: string[]; marks: ChangeBlock[]
53
53
  ignoringWhitespace: { blocks: ChangeBlock[]; marks: ChangeBlock[] }
54
54
  }
55
55
 
@@ -77,8 +77,9 @@ const pending = new Map<string, Promise<Buffer>>()
77
77
  // changes shown and hidden: checked again here, apart from the worker, as an
78
78
  // answer that is not would hide a change.
79
79
  function answers(diff: unknown, original: string, after: string): diff is RenameDiff {
80
- const { before, blocks, reason, reads, marks, ignoringWhitespace } = (diff ?? {}) as Partial<RenameDiff>
81
- return typeof before === 'string' && (reason === null || typeof reason === 'string') && Array.isArray(reads) && reads.every(read => typeof read === 'string')
80
+ const { before, blocks, reason, reads, assumed, marks, ignoringWhitespace } = (diff ?? {}) as Partial<RenameDiff>
81
+ const strings = (list: unknown) => Array.isArray(list) && list.every(item => typeof item === 'string')
82
+ return typeof before === 'string' && (reason === null || typeof reason === 'string') && strings(reads) && strings(assumed)
82
83
  && blocksHold(before, after, blocks, false) && marksFit(original, after, marks)
83
84
  && blocksHold(before, after, ignoringWhitespace?.blocks, true) && marksFit(original, after, ignoringWhitespace?.marks)
84
85
  }
@@ -0,0 +1,77 @@
1
+ // Whether a stored report may be switched to open on Confirmed (Manage →
2
+ // Reports), told of its content alone: where its pass leaves Confirmed rows of
3
+ // its own but it is no App view on its own, by the stricter rule App mode
4
+ // keeps (common/workspace-app.js confirmedDefaultOffered). A switched report's
5
+ // findings count as covered wherever Confirmed would hide them
6
+ // (common/finding-filters.js confirmedCoverage), both for the outcome a view
7
+ // opens on and for its team's App mode.
8
+ //
9
+ // Read as a report is uploaded, and kept (managed_report confirmed_offered):
10
+ // its bytes never change. One uploaded before the column is read as the
11
+ // reports page lists it, a bounded share of them each time, or as its switch
12
+ // is asked for.
13
+ import { backfillFindingIds, reportEntries } from '@preventive/report'
14
+ import { readManagedReport } from '../common/managed/report-content.ts'
15
+ import { managedReportConfirmedDefaultOffered } from '../common/managed/team-app.js'
16
+ import type { BlobStore } from './blob-store.ts'
17
+ import type { ManagedDb } from './db.ts'
18
+ import { eachOf } from './queue.ts'
19
+
20
+ // Of a report's parsed content, its findings' IDs backfilled first as a team's
21
+ // are (team-reports.ts), which it changes in place. A report whose rows cannot
22
+ // be read this way has no switch to offer.
23
+ export async function confirmedDefaultOffered(filename: string, data: unknown): Promise<boolean> {
24
+ try {
25
+ const findings = (reportEntries(data) ?? []).flatMap(entry => Array.isArray(entry) ? entry : [entry])
26
+ .filter((finding): finding is Record<string, unknown> => finding !== null && typeof finding === 'object' && !Array.isArray(finding))
27
+ await backfillFindingIds(findings)
28
+ return managedReportConfirmedDefaultOffered(filename, data)
29
+ } catch (error) {
30
+ console.warn('managed: reading a report for its opening failed:', error)
31
+ return false
32
+ }
33
+ }
34
+
35
+ // Of a stored report, read of its blob: null where its bytes cannot be read
36
+ // now, so a later read tries again.
37
+ async function readStored(store: BlobStore, report: { id: string; filename: string }): Promise<boolean | null> {
38
+ const bytes = await store.get(report.id).catch(() => null)
39
+ if (!bytes) return null
40
+ const { data } = readManagedReport(bytes.toString('utf8'), report.filename)
41
+ return data == null ? false : confirmedDefaultOffered(report.filename, data)
42
+ }
43
+
44
+ // The same, kept.
45
+ export async function readConfirmedOffered(db: ManagedDb, store: BlobStore, report: { id: string; filename: string }): Promise<boolean | null> {
46
+ const offered = await readStored(store, report)
47
+ if (offered !== null) await db.setReportsConfirmedOffered([{ id: report.id, offered }])
48
+ return offered
49
+ }
50
+
51
+ // At most this many bytes of reports not read yet are read for one listing,
52
+ // two at a time, and kept in one write; the rest wait for the next.
53
+ const LISTING_READ_BYTES = 64 * 1024 * 1024
54
+ const LISTING_READS_AT_ONCE = 2
55
+
56
+ // The listed reports, those not read for their opening yet read, as many as
57
+ // fit the bound: the first always, however large.
58
+ export async function withConfirmedOffered<T extends { id: string; filename: string; byteSize: number; confirmedOffered: boolean | null }>(
59
+ db: ManagedDb, store: BlobStore, reports: readonly T[]): Promise<T[]> {
60
+ let budget = LISTING_READ_BYTES
61
+ const unread = reports.filter(report => {
62
+ if (report.confirmedOffered !== null || budget <= 0) return false
63
+ budget -= report.byteSize
64
+ return true
65
+ })
66
+ if (unread.length === 0) return [...reports]
67
+ const read = new Map<string, boolean>()
68
+ await eachOf(unread, LISTING_READS_AT_ONCE, async report => {
69
+ const offered = await readStored(store, report).catch((error: unknown) => {
70
+ console.warn('managed: reading a report for its opening failed:', error)
71
+ return null
72
+ })
73
+ if (offered !== null) read.set(report.id, offered)
74
+ })
75
+ if (read.size > 0) await db.setReportsConfirmedOffered([...read].map(([id, offered]) => ({ id, offered })))
76
+ return reports.map(report => read.has(report.id) ? { ...report, confirmedOffered: read.get(report.id)! } : report)
77
+ }
@@ -15,6 +15,7 @@ import type { BlobStore } from './blob-store.ts'
15
15
  import type { BundleStore } from './bundle-store.ts'
16
16
  import type { ManagedBundle, ManagedDb, ReportRecord } from './db.ts'
17
17
  import { inTurns } from './queue.ts'
18
+ import { ourRepositoryNames } from './repository-aliases.ts'
18
19
 
19
20
  const compress = promisify(gzip)
20
21
  const reportFormat = (filename: string) => extname(filename).toLowerCase()
@@ -88,7 +89,7 @@ async function lendSourcemapEdges(details: BundleDetails, bundle: ManagedBundle,
88
89
  // The repositories that are ours, so that a finding's `repo` none of them is
89
90
  // left out (common/finding-repo.js isStrayRepo).
90
91
  async function oursFor(db: ManagedDb, repo: { github: string | null }): Promise<Set<string>> {
91
- return ourRepoSlugs([...(await db.listSelectedRepos()).map(selected => selected.fullName), repo.github])
92
+ return ourRepoSlugs([...await ourRepositoryNames(db), repo.github])
92
93
  }
93
94
 
94
95
  // Immutable report hashes share a derivative across duplicate uploads. Bundle
@@ -22,6 +22,15 @@ export interface RepositoryAliasStore {
22
22
  saveRepositoryAlias(sessionId: string, id: string | null, input: unknown): Promise<RepositoryAlias>
23
23
  deleteRepositoryAlias(sessionId: string, id: string): Promise<void>
24
24
  getRepositoryImportLocation(github: string, directory: string, filePrefix?: string): Promise<{ repoId: number | null; directory: string }>
25
+ // Connected repository `repo.repoId`, which GitHub renamed or transferred
26
+ // since it was named `from`, named as GitHub names it now (`fullName`,
27
+ // `htmlUrl`), and `from` an alias of the whole of it, as reports and
28
+ // bundles made before name it: where GitHub still sends `from` to it
29
+ // (`redirected`) and nothing here has that name, no repository connected
30
+ // (active or not) nor an alias of a whole repository. Resolves whether it
31
+ // was renamed here: false where it is no longer named `from`, as where
32
+ // another request renamed it first.
33
+ renameRepository(repo: { repoId: number; fullName: string; htmlUrl: string }, from: string, redirected: boolean): Promise<boolean>
25
34
  }
26
35
 
27
36
  // Keep expensive inventory reads outside database transactions and skip them
@@ -36,6 +45,16 @@ export async function resolveRepositoryImportLocation(db: ManagedDb, github: str
36
45
  return db.getRepositoryImportLocation(github, directory, filePrefix)
37
46
  }
38
47
 
48
+ // The names our repositories go by: each active one's as connected, and each
49
+ // alias's of one of them, as reports from before a rename name it
50
+ // (renameRepository). For a finding's `repo` to tell ours by
51
+ // (common/finding-repo.js ourRepoSlugs).
52
+ export async function ourRepositoryNames(db: Pick<ManagedDb, 'listSelectedRepos' | 'listRepositoryAliases'>): Promise<string[]> {
53
+ const [repos, aliases] = await Promise.all([db.listSelectedRepos(), db.listRepositoryAliases()])
54
+ const active = new Set(repos.map(repo => repo.repoId))
55
+ return [...repos.map(repo => repo.fullName), ...aliases.filter(alias => active.has(alias.repoId)).map(alias => alias.oldRepo)]
56
+ }
57
+
39
58
  function parseAlias(input: unknown): RepositoryAliasInput {
40
59
  if (!input || typeof input !== 'object') throw new ManagedMutationError(400, 'bad-alias')
41
60
  const { oldRepo, oldPath, repoId, newPath } = input as RepositoryAliasInput
@@ -72,6 +91,21 @@ export function repositoryAliasMethods(db: ManagedSql): RepositoryAliasStore {
72
91
  await sessionAdmin(db, sessionId)
73
92
  if (!(await db.prepare('DELETE FROM managed_repository_alias WHERE id = ?').run(id)).changes) throw new ManagedMutationError(404, 'no-alias')
74
93
  },
94
+ async renameRepository(repo, from, redirected) {
95
+ if (!Number((await db.prepare('UPDATE managed_selected_repo SET full_name = ?, html_url = ?, updated_at = ? WHERE repo_id = ? AND full_name = ?')
96
+ .run(repo.fullName, repo.htmlUrl, Date.now(), repo.repoId, from)).changes)) return false
97
+ // Normalized as an administrator's is (parseAlias); none where only the
98
+ // name's case changed, which aliases never tell apart.
99
+ const old = reportRepoGithub({ repo: { github: from } })?.toLowerCase()
100
+ if (!redirected || !old || old === repo.fullName.toLowerCase()) return true
101
+ const taken = await db.prepare(`SELECT 1 AS taken FROM managed_selected_repo WHERE LOWER(full_name) = ?
102
+ UNION ALL SELECT 1 AS taken FROM managed_repository_alias WHERE old_repo = ? AND old_path = ''`).get(old, old)
103
+ if (!taken) {
104
+ await db.prepare(`INSERT INTO managed_repository_alias (id, old_repo, old_path, repo_id, new_path) VALUES (?, ?, '', ?, '')`)
105
+ .run(randomUUID(), old, repo.repoId)
106
+ }
107
+ return true
108
+ },
75
109
  async getRepositoryImportLocation(github, directory, filePrefix = '') {
76
110
  const alias = matchRepositoryAlias(github, directory, await listRepositoryAliases(), filePrefix)
77
111
  const normalized = normalizeTeamPath(alias?.directory ?? directory)