@preventive/triage 1.0.0-alpha.65 → 1.0.0-alpha.67

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 (64) hide show
  1. package/common/bundle-imports.js +20 -0
  2. package/common/bundle-metadata.js +1 -1
  3. package/common/bundle-reasons.d.ts +4 -0
  4. package/common/bundle-reasons.js +38 -1
  5. package/common/bundle-sources.d.ts +1 -0
  6. package/common/bundle-sources.js +22 -0
  7. package/common/managed/npm-packages.js +3 -3
  8. package/common/managed/routes.js +23 -11
  9. package/common/managed/stasis-config.ts +7 -0
  10. package/out/activity.js +4 -4
  11. package/out/chunk-5F5FPI75.js +3 -0
  12. package/out/chunk-6ATPGDDI.js +1 -0
  13. package/out/chunk-6YGH7BJG.js +42 -0
  14. package/out/{chunk-ISXL3KOS.js → chunk-A5A3LEMV.js} +1 -1
  15. package/out/chunk-CGRIZ5M5.js +1 -0
  16. package/out/chunk-FUHRMY7R.js +247 -0
  17. package/out/{chunk-J2FWBXFV.js → chunk-LBJVV6UB.js} +1 -1
  18. package/out/chunk-LDO42LAC.js +1 -0
  19. package/out/{chunk-24AKGEH3.js → chunk-NB4JBTKK.js} +1 -1
  20. package/out/{chunk-IZ6MYRYB.js → chunk-R3WUYD4F.js} +1 -1
  21. package/out/chunk-U5C2TNNQ.js +52 -0
  22. package/out/chunk-VG5RH6KN.js +2 -0
  23. package/out/{chunk-XCWGOW63.js → chunk-VR3NRE5V.js} +1 -1
  24. package/out/chunk-WFDXHPT2.js +12 -0
  25. package/out/client-managed-import.js +2 -2
  26. package/out/client-managed.js +19 -19
  27. package/out/compare.js +15 -15
  28. package/out/dialogs.js +38 -38
  29. package/out/graph.js +8 -8
  30. package/out/index.html +9 -9
  31. package/out/scan.js +2 -2
  32. package/out/view.css +1 -1
  33. package/out/view.js +15 -15
  34. package/package.json +11 -8
  35. package/server-managed/activity.ts +21 -12
  36. package/server-managed/bundle-build-diagnostics.d.ts +1 -1
  37. package/server-managed/bundle-build-worker.js +84 -15
  38. package/server-managed/bundle-build.ts +95 -19
  39. package/server-managed/bundle-cache.ts +28 -6
  40. package/server-managed/bundle-dependency-reviews.ts +38 -22
  41. package/server-managed/commit-lockfiles.ts +2 -1
  42. package/server-managed/db-neon.ts +1 -1
  43. package/server-managed/dependency-review-comments.ts +31 -12
  44. package/server-managed/http.ts +127 -59
  45. package/server-managed/locked-packages.ts +34 -14
  46. package/server-managed/lockfile-scope.ts +10 -1
  47. package/server-managed/npm-kept.ts +10 -0
  48. package/server-managed/npm-patch.ts +127 -50
  49. package/server-managed/public-workspace.ts +3 -2
  50. package/server-managed/pull-dependencies.ts +55 -37
  51. package/server-managed/pull-dependency-reviews.ts +15 -11
  52. package/server-managed/report-sources.ts +6 -3
  53. package/server-managed/repository-issues.ts +14 -11
  54. package/server-managed/stasis-dependencies.ts +153 -0
  55. package/out/chunk-65PLAG3I.js +0 -12
  56. package/out/chunk-D34CUNO5.js +0 -247
  57. package/out/chunk-DCBXCBLL.js +0 -52
  58. package/out/chunk-F3UI65ZI.js +0 -42
  59. package/out/chunk-FAG6E5RC.js +0 -3
  60. package/out/chunk-PTFQKLKO.js +0 -1
  61. package/out/chunk-QVKFY4FA.js +0 -1
  62. package/out/chunk-SYXT3SFP.js +0 -2
  63. package/out/chunk-WL3SPQB4.js +0 -1
  64. /package/out/{chunk-WCPJDAYA.js → chunk-D6NVKGGG.js} +0 -0
@@ -7,6 +7,7 @@ import { LockfileError, parseNpmLockfile } from '@preventive/lockfile/npm.js'
7
7
  import { parsePnpmLockfile } from '@preventive/lockfile/pnpm.js'
8
8
  import { parseYarn1Lockfile } from '@preventive/lockfile/yarn1.js'
9
9
  import type { LockfileFormat } from '@preventive/upstream/github.js'
10
+ import { isPatchHash } from '../common/managed/npm-packages.js'
10
11
  import type { ReviewedLockfile } from './reviewed-dependencies.ts'
11
12
 
12
13
  export interface LockedPackage {
@@ -27,18 +28,27 @@ export interface LockedPackage {
27
28
  // Where its reviews ask: the sha1 Yarn 1 writes after a tarball's `#`, in
28
29
  // hex (`shasum`); the hash of the patch pnpm applies to it
29
30
  // (`patchHash`, its patchedDependencies'), and the patch's file, where the
30
- // lockfile names one (`patchPath`, pnpm 9's and 10's): from the lockfile's
31
+ // lockfile names one (`patchPath`, pnpm 10's): from the lockfile's
31
32
  // directory as read, from the repository's root once that is known
32
- // (patchedIn); and the lockfile's format.
33
+ // (patchedIn), with that directory then (`patchDir`, '' the root), whence
34
+ // a patch its lockfile names by its hash alone, as pnpm 11 and later do,
35
+ // is found, its file told as one named is (npm-patch.ts withPatchFiles);
36
+ // and the lockfile's format.
33
37
  shasum?: string
34
38
  patchHash?: string
35
39
  patchPath?: string
40
+ patchDir?: string
36
41
  lockfile?: ReviewedLockfile
37
42
  // Where only the importers' devDependencies reach it, as npm's `dev` flag
38
43
  // says, and an install of no devDependencies leaves it out: in npm's and
39
44
  // pnpm's lockfiles. Yarn 1's says nothing of it, which only the
40
45
  // package.json files do, and none of its are.
41
46
  dev?: true
47
+ // A version a Stasis build holds that no lockfile read locks, which can't
48
+ // be reviewed (`unlocked`); and a lockfile's that the stasis.config.json
49
+ // beside it reaches not (`unreached`, stasis-dependencies.ts withReach).
50
+ unlocked?: true
51
+ unreached?: true
42
52
  }
43
53
 
44
54
  // A package as each reader resolves one, its name the one it is published
@@ -51,13 +61,14 @@ interface ReadPackage { name: string; version: string | undefined; resolution: R
51
61
  patchPath?: string | undefined }
52
62
 
53
63
  // The packages of a lockfile of `format`, as its reader resolves them, a
54
- // patched one of pnpm's with its patch's file where the lockfile names it.
64
+ // patched one of pnpm's with its patch's file where the lockfile names it,
65
+ // but one pnpm 9 names by an md5, which reviews don't read (isPatchHash).
55
66
  // Versions go unchecked against ranges, as only what is locked is asked for.
56
67
  function packagesOf(format: LockfileFormat, text: string): ReadPackage[] {
57
68
  if (format === 'npm') return Object.values(parseNpmLockfile(text, { checkVersions: false }).packages)
58
69
  if (format === 'pnpm') {
59
70
  const { lockfile, env } = parsePnpmLockfile(text)
60
- const files = new Map(Object.values(lockfile?.patchedDependencies ?? {}).flatMap(({ hash, path }) => path ? [[hash, path] as const] : []))
71
+ const files = new Map(Object.values(lockfile?.patchedDependencies ?? {}).flatMap(({ hash, path }) => path && isPatchHash(hash) ? [[hash, path] as const] : []))
61
72
  return [...Object.values(env?.packages ?? {}), ...Object.values(lockfile?.packages ?? {})]
62
73
  .map(pkg => pkg.patchHash !== undefined && files.has(pkg.patchHash) ? { ...pkg, patchPath: files.get(pkg.patchHash) } : pkg)
63
74
  }
@@ -126,18 +137,27 @@ export function lockedPackages(format: LockfileFormat, text: string, { review =
126
137
  return [...found.values()]
127
138
  }
128
139
 
129
- // `pkg` as a lockfile at `path` locks it, read with its patch's file from
130
- // the lockfile's directory (LockedPackage `patchPath`): that file from the
131
- // repository's root, none where it names one outside it.
132
- export function patchedIn<T extends LockedPackage>(path: string, pkg: T): T {
133
- if (pkg.patchPath === undefined) return pkg
134
- const { patchPath, ...rest } = pkg
135
- const parts = path.split('/').slice(0, -1)
136
- for (const part of patchPath.split('/')) {
137
- if (part === '..') { if (parts.pop() === undefined) return rest as T }
140
+ // `path`, from directory `dir` ('' the repository's root), from the root;
141
+ // null where it leads outside the repository, or names nothing.
142
+ export function pathFrom(dir: string, path: string): string | null {
143
+ const parts = dir === '' ? [] : dir.split('/')
144
+ for (const part of path.split('/')) {
145
+ if (part === '..') { if (parts.pop() === undefined) return null }
138
146
  else if (part !== '.' && part !== '') parts.push(part)
139
147
  }
140
- return parts.length > 0 ? { ...rest, patchPath: parts.join('/') } as T : rest as T
148
+ return parts.length > 0 ? parts.join('/') : null
149
+ }
150
+
151
+ // `pkg` as a lockfile at `path` locks it, a patched one with the lockfile's
152
+ // directory (LockedPackage `patchDir`); and, read with its patch's file
153
+ // from that directory (`patchPath`), with that file from the repository's
154
+ // root, none where it names one outside it.
155
+ export function patchedIn<T extends LockedPackage>(path: string, pkg: T): T {
156
+ if (pkg.patchHash === undefined) return pkg
157
+ const { patchPath, ...rest } = pkg
158
+ const patchDir = path.slice(0, Math.max(path.lastIndexOf('/'), 0))
159
+ const file = patchPath === undefined ? null : pathFrom(patchDir, patchPath)
160
+ return { ...rest, patchDir, ...file === null ? {} : { patchPath: file } } as T
141
161
  }
142
162
 
143
163
  // Whether a lockfile at `path` is a test's fixture or example: under a
@@ -6,6 +6,11 @@
6
6
  // request's lockfiles (pull-dependencies.ts) is reviewed where one of its
7
7
  // lockfiles is held to; one none of whose are, not at all (`excluded`), nor
8
8
  // failing the review where it couldn't be read.
9
+ // Among those it names alone (`include`), a stasis.config.json too: it
10
+ // holds its review to the versions its entries reach (stasis-dependencies.ts).
11
+ import { isStasisConfig } from '../common/managed/stasis-config.ts'
12
+
13
+ export { isStasisConfig }
9
14
  export interface LockfileScope { mode: 'exclude' | 'include'; paths: string[] }
10
15
  export const EVERY_LOCKFILE: LockfileScope = { mode: 'exclude', paths: [] }
11
16
  const MAX_SCOPED_LOCKFILES = 100
@@ -22,10 +27,11 @@ function namedPath(path: unknown): path is string {
22
27
  }
23
28
 
24
29
  // A scope as a request sends it, each path once, in order; null for one
25
- // that isn't one.
30
+ // that isn't one, as one leaving a stasis.config.json out isn't.
26
31
  export function scopeOf(value: unknown): LockfileScope | null {
27
32
  const { mode, paths } = (value ?? {}) as { mode?: unknown; paths?: unknown }
28
33
  if ((mode !== 'exclude' && mode !== 'include') || !Array.isArray(paths) || paths.length > MAX_SCOPED_LOCKFILES || !paths.every(namedPath)) return null
34
+ if (mode === 'exclude' && (paths as string[]).some(isStasisConfig)) return null
29
35
  return { mode, paths: [...new Set(paths as string[])].toSorted() }
30
36
  }
31
37
 
@@ -47,3 +53,6 @@ export function heldTo(scope: LockfileScope, path: string) {
47
53
  // Whether a directory of lockfiles at `paths` is reviewed: where one is
48
54
  // held to, or it names none.
49
55
  export const reviewedIn = (scope: LockfileScope, paths: string[]) => paths.length === 0 || paths.some(path => heldTo(scope, path))
56
+ // The stasis.config.json files `scope` holds to, by their paths: those it
57
+ // names alone.
58
+ export const stasisConfigs = (scope: LockfileScope) => scope.mode === 'include' ? scope.paths.filter(isStasisConfig) : []
@@ -24,6 +24,7 @@
24
24
  import { createHash } from 'node:crypto'
25
25
  import { plainObject } from './npm-manifest.ts'
26
26
  import { type NpmPublishTimeStore, type NpmVersionStore, VERSION_KEPT_MS } from './npm-packages.ts'
27
+ import type { KeptPatch } from './npm-patch.ts'
27
28
  import type { UpstreamCacheStore } from './upstream-cache.ts'
28
29
 
29
30
  // A value kept by key, as JSON, `at` when it was.
@@ -228,7 +229,16 @@ export const reviewBaselineStore = (db: UpstreamCacheStore, debug = false): Kept
228
229
  // what their reviews are held to.
229
230
  export const lockfileReadStore = <T>(db: UpstreamCacheStore, type: 'listings' | 'lockfiles', debug = false): KeptStore<T> =>
230
231
  keptStore<T>(db, `repository/review-${type}`, HISTORY_PAGE_KEPT_MS, debug)
232
+ // The pnpm patches a repository's dependency reviews read (npm-patch.ts), by
233
+ // the repository and each's hash, a sha256, which names its text wherever
234
+ // and whenever it is read: kept for good.
235
+ export const patchStore = (db: UpstreamCacheStore, debug = false): KeptStore<KeptPatch> => keptStore<KeptPatch>(db, 'repository/patches', Infinity, debug)
231
236
  // A bundle's validations (bundle-validation.ts), by the bundle, where it is,
232
237
  // what its reader could check and the rules they were made by: kept a month
233
238
  // after they were made, as what they check never changes.
234
239
  export const bundleValidationStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'bundles/validations', HISTORY_PAGE_KEPT_MS, debug)
240
+ // What a repository's stasis.config.json has Stasis reach at a commit
241
+ // (stasis-dependencies.ts): the versions, never the lockfile, by the
242
+ // repository, the commit and the file's path, kept as its history's pages are.
243
+ export const stasisDependencyStore = (db: UpstreamCacheStore, debug = false): KeptStore<unknown> =>
244
+ keptStore<unknown>(db, 'repository/stasis-dependencies', HISTORY_PAGE_KEPT_MS, debug)
@@ -1,10 +1,12 @@
1
1
  // A pnpm patch of an npm package version (patchedDependencies), as its
2
2
  // dependency review reads it (pull-dependency-reviews.ts): its file, which a
3
- // lockfile names (locked-packages.ts `patchPath`), read of a repository at a
4
- // commit, and held to the hash the lockfile names it by, as pnpm hashes it,
5
- // a sha256 in hex from pnpm 10 and an md5 in base32 before, of its text with
6
- // its CRLFs read as LFs; and applied to the version's files as pnpm applies
7
- // it as it installs it (patch-package's applyPatch, which pnpm 9, 10 and 11
3
+ // lockfile names (locked-packages.ts `patchPath`), or which is found where it
4
+ // names it by its hash alone (withPatchFiles), read of a repository at a
5
+ // commit, and held to the hash the lockfile names it by, as pnpm 10 and
6
+ // later hash it, a sha256 in hex of its text with its CRLFs read as LFs
7
+ // (one pnpm 9 names by an md5 isn't read), by which it is kept for good,
8
+ // read of GitHub once; and applied to the version's files as pnpm applies
9
+ // it as it installs it (patch-package's applyPatch, which pnpm 10 and 11
8
10
  // bundle): each file it deletes, creates, renames or changes, a change's
9
11
  // hunks each found in the file as it was, where its header says, else as
10
12
  // many as FUZZ lines either side, its lines the same but for the space they
@@ -14,53 +16,51 @@
14
16
  // file's mode is left out, as the files it reads have none.
15
17
  import { Buffer } from 'node:buffer'
16
18
  import { createHash } from 'node:crypto'
19
+ import { YamlError, parseYaml } from '@preventive/lockfile/yaml.js'
20
+ import { isGithubRepoName } from '../common/github-pr.ts'
17
21
  import { isPatchHash, isPatchPath } from '../common/managed/npm-packages.js'
18
- import { SHA } from './github-values.ts'
22
+ import { GithubApiError } from './github-errors.ts'
23
+ import { SHA, isId } from './github-values.ts'
24
+ import { type LockedPackage, pathFrom } from './locked-packages.ts'
19
25
  import { type Lru, lru } from './lru.ts'
26
+ import type { KeptStore } from './npm-kept.ts'
27
+ import { plainObject } from './npm-manifest.ts'
20
28
  import { NpmPackageError, type NpmPackageFile, npmFileText, pathOrder } from './npm-packages.ts'
21
- import { type GithubAsked, repositoryFile } from './pull-dependencies.ts'
29
+ import { type GithubAsked, type PullDependencies, repositoryFile } from './pull-dependencies.ts'
30
+ import { eachOf } from './queue.ts'
22
31
 
23
32
  // Where a patch is read: its file in a repository (by its id) at a commit,
24
- // from the repository's root; and the patch, by its hash besides.
33
+ // from the repository's root; and the patch, by its hash besides. A request
34
+ // names its repository by its id, or by its name (`owner/name`) in its place
35
+ // (http.ts wholeRepositoryAccess).
25
36
  export interface PatchSource { repoId: number; commit: string; path: string }
26
37
  export interface NpmPatch extends PatchSource { hash: string }
38
+ export type RequestedPatch = Omit<NpmPatch, 'repoId'> & { repoId: number | string }
27
39
 
28
40
  // The most a patch's file may hold, and how many lines either side of where a
29
- // hunk says its lines are they are looked for.
41
+ // hunk says its lines are they are looked for; and how many patches an
42
+ // answer looks for, those past them left for the next, and how many at once.
30
43
  const MAX_PATCH_BYTES = 8 * 1024 * 1024
31
44
  const FUZZ = 20
32
-
45
+ const MAX_FOUND = 100
46
+ const FIND_AT_ONCE = 4
33
47
 
34
48
  // The patch a request names, by its hash (`hash`), its repository's id
35
- // (`repoId`, a number or its digits), the commit and its file's path; null
36
- // where it names none of where it is, and 'invalid' where it names one
37
- // otherwise.
38
- export function requestedPatch({ hash, repoId, commit, path }: { hash: unknown; repoId: unknown; commit: unknown; path: unknown }): NpmPatch | null | 'invalid' {
49
+ // (`repoId`, a number or its digits) or name, the commit and its file's
50
+ // path; null where it names none of where it is, and 'invalid' where it
51
+ // names one otherwise.
52
+ export function requestedPatch({ hash, repoId, commit, path }: { hash: unknown; repoId: unknown; commit: unknown; path: unknown }): RequestedPatch | null | 'invalid' {
39
53
  if ([repoId, commit, path].every(field => field == null)) return null
40
54
  const id = typeof repoId === 'string' && /^[1-9]\d{0,15}$/u.test(repoId) ? Number(repoId) : repoId
41
- if (!isPatchHash(hash) || !Number.isSafeInteger(id) || (id as number) <= 0 || typeof commit !== 'string' || !SHA.test(commit)
55
+ if (!isPatchHash(hash) || !(isId(id) || typeof id === 'string' && isGithubRepoName(id)) || typeof commit !== 'string' || !SHA.test(commit)
42
56
  || !isPatchPath(path)) return 'invalid'
43
- return { hash, repoId: id as number, commit, path }
44
- }
45
-
46
- // RFC 4648's base32 of `bytes`, in lowercase and unpadded, as pnpm 9 spells
47
- // an md5.
48
- const BASE32 = 'abcdefghijklmnopqrstuvwxyz234567'
49
- function base32(bytes: Uint8Array) {
50
- let bits = 0, spelled = '', value = 0
51
- for (const byte of bytes) {
52
- value = ((value << 8) | byte) & 0xfff
53
- bits += 8
54
- for (; bits >= 5; bits -= 5) spelled += BASE32[(value >>> (bits - 5)) & 31]
55
- }
56
- return bits > 0 ? spelled + BASE32[(value << (5 - bits)) & 31] : spelled
57
+ return { hash, repoId: id, commit, path }
57
58
  }
58
59
 
59
- // Whether `text` is the patch `hash` names: of its text with its CRLFs as
60
- // LFs, as pnpm reads it, or as it is.
60
+ // Whether `text` is the patch `hash` names, its sha256 in hex: of its text
61
+ // with its CRLFs as LFs, as pnpm reads it, or as it is.
61
62
  export function isPatchOf(text: string, hash: string): boolean {
62
- return [...new Set([text.replaceAll('\r\n', '\n'), text])].some(read => hash.length === 64
63
- ? createHash('sha256').update(read).digest('hex') === hash : base32(createHash('md5').update(read).digest()) === hash)
63
+ return [...new Set([text.replaceAll('\r\n', '\n'), text])].some(read => createHash('sha256').update(read).digest('hex') === hash)
64
64
  }
65
65
 
66
66
  // A change a patch makes to a file at `path` of the package: deleting it,
@@ -293,25 +293,102 @@ const held = (lines: string[]) => lines.reduce((sum, line) => sum + LINE_COST +
293
293
  export const patchWeight = (files: PatchedFile[]) => files.reduce((sum, file) => sum + HUNK_COST + file.path.length + (file.from?.length ?? 0)
294
294
  + file.hunks.reduce((bytes, hunk) => bytes + HUNK_COST + hunk.parts.reduce((parts, part) => parts + held(part.lines), 0), 0), 1)
295
295
 
296
- // Patches read lately, by their source and hash, as what a commit holds never
297
- // changes: as many as MAX_KEPT_PATCHES of the bytes they take (patchWeight).
296
+ // What is kept of a patch, for good, by its repository and hash (patchKey):
297
+ // where it was read, and its text, which its hash names wherever it is.
298
+ // Kept by its repository too, as only one who reads all of that is given it.
299
+ export interface KeptPatch { commit: string; path: string; text: string }
300
+ export const patchKey = (repoId: number, hash: string) => `${repoId}\0${hash}`
301
+
302
+ // Patches read lately, with where each was read, by their keys, as many as
303
+ // MAX_KEPT_PATCHES of the bytes they take (patchWeight); and the path each
304
+ // found or kept is at (`located`): '' by its key and a commit for one not
305
+ // found there, lest each telling look again, none for one not looked for.
298
306
  const MAX_KEPT_PATCHES = 64 * 1024 * 1024
299
- const patches: Lru<PatchedFile[]> = lru(MAX_KEPT_PATCHES, patchWeight)
307
+ export interface ReadPatch { source: PatchSource; files: PatchedFile[] }
308
+ const patches: Lru<ReadPatch> = lru(MAX_KEPT_PATCHES, read => patchWeight(read.files))
309
+ const located: Lru<string> = lru(100_000)
300
310
 
301
- // The patch `patch` names, read as kept, else of repository `fullName` with
302
- // `token`, held to its hash and read (parsePatch), and kept; `asked` told
303
- // where GitHub was. Its file missing there, or other than its hash says, or
304
- // past MAX_PATCH_BYTES, fails.
305
- export async function readPatch(fullName: string, token: string, patch: NpmPatch, asked?: GithubAsked): Promise<PatchedFile[]> {
306
- const key = `${patch.repoId}\0${patch.commit}\0${patch.path}\0${patch.hash}`
311
+ // The patch `patch` names, and where it was read (`source`): as kept by its
312
+ // repository and hash, in this instance, else beyond it (`kept`, held to its
313
+ // hash again), wherever the request says it is; else read of repository
314
+ // `fullName` with `token` at the commit and path it names, held to its
315
+ // hash, and kept for good; `asked` told where GitHub was. Its file missing
316
+ // there, or other than its hash says, or past MAX_PATCH_BYTES, fails, as
317
+ // does one that isn't read as git writes a diff (parsePatch).
318
+ export async function readPatch(fullName: string, token: string, patch: NpmPatch, kept: KeptStore<KeptPatch>, asked?: GithubAsked): Promise<ReadPatch> {
319
+ const key = patchKey(patch.repoId, patch.hash)
307
320
  const known = patches.get(key)
308
321
  if (known) return known
309
- if (asked) asked.github = true
310
- const text = await repositoryFile(fullName, token, patch.path, patch.commit)
311
- if (text === null) throw new NpmPackageError(404, 'patch-not-found')
312
- if (Buffer.byteLength(text) > MAX_PATCH_BYTES) throw new NpmPackageError(413, 'patch-too-large')
313
- if (!isPatchOf(text, patch.hash)) throw new NpmPackageError(409, 'patch-mismatch')
314
- const files = parsePatch(text)
315
- patches.set(key, files)
316
- return files
322
+ let stored = (await kept.read(key))?.value
323
+ if (typeof stored?.text !== 'string' || !isPatchOf(stored.text, patch.hash)) {
324
+ if (asked) asked.github = true
325
+ const text = await repositoryFile(fullName, token, patch.path, patch.commit)
326
+ if (text === null) throw new NpmPackageError(404, 'patch-not-found')
327
+ if (Buffer.byteLength(text) > MAX_PATCH_BYTES) throw new NpmPackageError(413, 'patch-too-large')
328
+ if (!isPatchOf(text, patch.hash)) throw new NpmPackageError(409, 'patch-mismatch')
329
+ stored = { commit: patch.commit, path: patch.path, text }
330
+ await kept.write(key, stored, Date.now())
331
+ }
332
+ const read = { source: { repoId: patch.repoId, commit: stored.commit, path: stored.path }, files: parsePatch(stored.text) }
333
+ patches.set(key, read)
334
+ return read
335
+ }
336
+
337
+ // The files a pnpm-workspace.yaml (`workspace`, its text, null for none)
338
+ // names its patches by, as pnpm 11 and later read their patchedDependencies
339
+ // there alone, by a version or a package; none where its reader refuses it.
340
+ function patchedBy(workspace: string | null): Record<string, unknown> {
341
+ let settings: unknown
342
+ try { settings = workspace === null ? null : parseYaml(workspace, { workflow: true }) } catch (err) {
343
+ if (!(err instanceof YamlError)) throw err
344
+ }
345
+ const patched = plainObject(settings) ? settings['patchedDependencies'] : null
346
+ return plainObject(patched) ? patched : {}
347
+ }
348
+
349
+ // A version pnpm patches by a patch its lockfile names by its hash alone
350
+ // (pnpm 11's and later), a sha256, with its lockfile's directory.
351
+ type Unnamed = LockedPackage & { patchHash: string; patchDir: string; version: string }
352
+ const unnamed = (pkg: LockedPackage): pkg is Unnamed => pkg.patchPath === undefined && pkg.patchDir !== undefined && pkg.version !== null && isPatchHash(pkg.patchHash)
353
+
354
+ // `told`, each such version of its with its patch's file (`patchPath`), as
355
+ // a lockfile naming one tells it: as kept by its repository and hash, else
356
+ // the file the pnpm-workspace.yaml beside its lockfile names of it
357
+ // (patchedBy: its version's, else its package's) at `told.head`, held to
358
+ // its hash and kept for good, so each is found once, as many an answer as
359
+ // MAX_FOUND; one not found left with none. `asked` told where GitHub was.
360
+ // A file GitHub has no text of, or past MAX_PATCH_BYTES, is none; any other
361
+ // failure of GitHub's is the whole answer's, as a lockfile's is.
362
+ export async function withPatchFiles<T extends PullDependencies>(told: T, repoId: number, fullName: string, token: string, kept: KeptStore<KeptPatch>,
363
+ asked?: GithubAsked): Promise<T> {
364
+ const wanted = new Map<string, Unnamed>()
365
+ for (const dir of told.lockfiles) {
366
+ for (const pkg of 'error' in dir ? [] : [...dir.added, ...dir.locked]) if (unnamed(pkg)) wanted.set(patchKey(repoId, pkg.patchHash), pkg)
367
+ }
368
+ if (wanted.size === 0) return told
369
+ const at = (key: string) => located.get(key) ?? located.get(`${key}\0${told.head}`)
370
+ const unknown = [...wanted.keys()].filter(key => at(key) === undefined)
371
+ for (const [key, { value }] of unknown.length > 0 ? await kept.readMany(unknown) : []) if (typeof value?.path === 'string') located.set(key, value.path)
372
+ const files = new Map<string, Promise<string | null>>()
373
+ const read = (path: string) => files.get(path) ?? files.set(path, repositoryFile(fullName, token, path, told.head).then(
374
+ text => text !== null && Buffer.byteLength(text) > MAX_PATCH_BYTES ? null : text,
375
+ (err: unknown) => { if (err instanceof GithubApiError && err.message === 'github-malformed') return null; throw err })).get(path)!
376
+ const workspaces = new Map<string, Promise<Record<string, unknown>>>()
377
+ const namedIn = (dir: string) => workspaces.get(dir) ?? workspaces.set(dir, read(pathFrom(dir, 'pnpm-workspace.yaml')!).then(patchedBy)).get(dir)!
378
+ await eachOf(unknown.filter(key => at(key) === undefined).slice(0, MAX_FOUND), FIND_AT_ONCE, async key => {
379
+ const pkg = wanted.get(key)!
380
+ if (asked) asked.github = true
381
+ const patched = await namedIn(pkg.patchDir)
382
+ const file = patched[`${pkg.name}@${pkg.version}`] ?? patched[pkg.name]
383
+ const path = typeof file === 'string' ? pathFrom(pkg.patchDir, file) : null
384
+ const text = path === null ? null : await read(path)
385
+ if (path === null || text === null || !isPatchOf(text, pkg.patchHash)) { located.set(`${key}\0${told.head}`, ''); return }
386
+ await kept.write(key, { commit: told.head, path, text }, Date.now())
387
+ located.set(key, path)
388
+ })
389
+ const named = <P extends LockedPackage>(pkg: P): P => {
390
+ const patchPath = unnamed(pkg) && at(patchKey(repoId, pkg.patchHash))
391
+ return patchPath ? { ...pkg, patchPath } : pkg
392
+ }
393
+ return { ...told, lockfiles: told.lockfiles.map(dir => 'error' in dir ? dir : { ...dir, added: dir.added.map(named), locked: dir.locked.map(named) }) }
317
394
  }
@@ -202,10 +202,11 @@ async function serveBundle(res: ServerResponse, deps: ManagedHttpDeps, bundle: M
202
202
  if (!deps.bundleCache) { json(res, 503, { error: 'unavailable' }); return }
203
203
  if (part === 'advisories') {
204
204
  if (bundle.kind !== 'stasis') { json(res, 422, { error: 'unsupported-bundle' }); return }
205
- const inventory = await deps.bundleCache.advisoryInventory(bundle, url.searchParams.get('reason') ?? '')
205
+ const entry = url.searchParams.get('entry') ?? ''
206
+ const inventory = await deps.bundleCache.advisoryInventory(bundle, url.searchParams.get('reason') ?? '', entry)
206
207
  await recheck()
207
208
  if (inventory === null) { json(res, 413, { error: 'payload-too-large' }); return }
208
- if (inventory === undefined) { json(res, 400, { error: 'unknown-reason' }); return }
209
+ if (inventory === undefined) { json(res, 400, { error: entry ? 'unknown-entry' : 'unknown-reason' }); return }
209
210
  if (Buffer.byteLength(JSON.stringify(inventory)) > MAX_PACKAGE_INVENTORY_BYTES) { json(res, 413, { error: 'payload-too-large' }); return }
210
211
  const signal = AbortSignal.timeout(ADVISORIES_TIMEOUT_MS)
211
212
  const repoAdvisories = url.searchParams.get('repoAdvisories') === 'true'
@@ -29,9 +29,11 @@
29
29
  import { createClient } from '@preventive/upstream/github.js'
30
30
  import { GithubApiError, upstreamGithub } from './github-errors.ts'
31
31
  import { USER_AGENT, githubJson, repoApi } from './github-requests.ts'
32
+ import { branchName } from './bundle-build.ts'
32
33
  import { SHA } from './github-values.ts'
33
34
  import { compareVersions, isExactVersion } from '@preventive/upstream/semver.js'
34
35
  import { type LockedPackage, isTestFixture, lockedPackages, patchedIn } from './locked-packages.ts'
36
+ import { isStasisConfig } from './lockfile-scope.ts'
35
37
  import { type Lru, lru } from './lru.ts'
36
38
  import { eachOf } from './queue.ts'
37
39
  import { type ChangedFile, commitChanges } from './repository-changes.ts'
@@ -53,8 +55,9 @@ const READ_PARALLEL = 4
53
55
  // The rules what is told was told by, kept with it (http.ts
54
56
  // pullDependencyKept), and the lockfiles read for it (lockfileKept): one
55
57
  // told or read by others is told or read again, as those read before pnpm's
56
- // patches' files were.
57
- export const PULL_DEPENDENCIES_READ = 4
58
+ // patches' files were, and those told before their lockfiles' directories,
59
+ // or read with the files of patches pnpm 9 names by an md5.
60
+ export const PULL_DEPENDENCIES_READ = 5
58
61
 
59
62
  type Format = 'npm' | 'pnpm' | 'yarn' | 'bun'
60
63
 
@@ -73,11 +76,11 @@ export function lockfileFormat(path: string): Format | null {
73
76
  return name === 'yarn.lock' ? 'yarn' : null
74
77
  }
75
78
 
76
- // Whether a pull request changing `paths` changes a lockfile read here: null
77
- // where none of them is one but they are fewer than it changes
78
- // (`changed`), which it may yet.
79
+ // Whether a pull request changing `paths` changes a lockfile read here, or
80
+ // a stasis.config.json, which a review may hold to: null where none of them
81
+ // is one but they are fewer than it changes (`changed`), which it may yet.
79
82
  export function touchesLockfile(paths: string[], changed: number): boolean | null {
80
- if (paths.some(path => lockfileFormat(path) !== null)) return true
83
+ if (paths.some(path => lockfileFormat(path) !== null || isStasisConfig(path))) return true
81
84
  return changed > paths.length ? null : false
82
85
  }
83
86
 
@@ -93,6 +96,8 @@ export type AddedPackage = LockedPackage & { was?: string[] }
93
96
  // `moreLocked`); or why they couldn't be told, a lockfile's reader refusing one
94
97
  // (`lockfile-unreadable`, with what it said), one of a format not read
95
98
  // (`lockfile-unsupported`, Bun's) or GitHub having none at a commit compared.
99
+ // A stasis.config.json a review holds to is told as one too, by its own path
100
+ // (stasis-dependencies.ts stasisDirectory), or as `stasis-pending` or `stasis-failed`.
96
101
  export type DirectoryDependencies = { paths: string[] } & ({ added: AddedPackage[]; more: number; locked: LockedPackage[]; moreLocked: number }
97
102
  | { error: string; detail?: string })
98
103
  // What a pull request's lockfiles add: the commits compared (`base`, its
@@ -141,15 +146,23 @@ const readKey = (ref: string, { path, format, sha }: { path: string; format: For
141
146
 
142
147
  // The pull request's base's and head's commits, as GitHub has them now: its
143
148
  // base's moving on as it does, its head's with each push, both kept once it
144
- // is merged or closed.
145
- export interface PullCommits { base: string; head: string }
149
+ // is merged or closed. With the branches they are of, where told: its base's
150
+ // (`baseRef`), whose history holds its merge base, and its head's
151
+ // (`headRef`) where that is the repository's own, not a fork's.
152
+ export interface PullRefs { baseRef?: string; headRef?: string }
153
+ export interface PullCommits extends PullRefs { base: string; head: string }
154
+ // Those of `base` and `head` that are a branch's name.
155
+ export const pullRefs = (base: unknown, head: unknown): PullRefs => ({ ...branchName(base) ? { baseRef: base } : {}, ...branchName(head) ? { headRef: head } : {} })
146
156
  async function pullCommits(fullName: string, token: string, number: number, fetchImpl: typeof fetch): Promise<PullCommits> {
147
157
  const pull = await githubJson(`${repoApi(fullName)}/pulls/${number}`, token, fetchImpl) as
148
- { number?: unknown; base?: { sha?: unknown; repo?: { full_name?: unknown } | null }; head?: { sha?: unknown } } | null
158
+ { number?: unknown; base?: { sha?: unknown; ref?: unknown; repo?: { full_name?: unknown } | null }
159
+ head?: { sha?: unknown; ref?: unknown; repo?: { full_name?: unknown } | null } } | null
149
160
  const base = pull?.base?.sha, head = pull?.head?.sha, repo = pull?.base?.repo?.full_name
150
161
  if (pull?.number !== number || typeof base !== 'string' || !SHA.test(base) || typeof head !== 'string' || !SHA.test(head)
151
162
  || typeof repo !== 'string' || repo.toLowerCase() !== fullName.toLowerCase()) throw new GithubApiError(502, 'github-malformed')
152
- return { base, head }
163
+ const from = pull.head?.repo?.full_name
164
+ const own = typeof from === 'string' && from.toLowerCase() === repo.toLowerCase()
165
+ return { base, head, ...pullRefs(pull.base?.ref, own ? pull.head?.ref : undefined) }
153
166
  }
154
167
 
155
168
  // The pull request's merge base and the files it changes from it: as GitHub
@@ -263,38 +276,42 @@ const byName = (a: AddedPackage, b: AddedPackage) => a.name < b.name ? -1 : a.na
263
276
  export const lockedAs = (pkg: LockedPackage) => `${pkg.source}\0${pkg.name}@${pkg.version ?? ''}\0${pkg.from ?? ''}\0${pkg.patchHash ?? ''}`
264
277
  export const lockedWith = (pkg: LockedPackage) => `${lockedAs(pkg)}\0${pkg.integrity ?? ''}\0${pkg.shasum ?? ''}\0${pkg.lockfile ?? ''}`
265
278
 
266
- // What a directory's lockfiles add, from each read before and after: the
267
- // package versions after none before has, each once, by name and version,
268
- // each with the versions of its name before, those past MAX_ADDED counted
269
- // (`more`), not told but reviewed as they are; and every one after, each
270
- // integrity it is locked with (`locked`), as many as MAX_LOCKED, each patch's
271
- // file from the repository's root (patchedIn); or the first failure among
272
- // them.
279
+ // What a directory's lockfiles add, from each read before and after
280
+ // (addedBetween), each patch's file from the repository's root, and its
281
+ // lockfile's directory (patchedIn); or the first failure among them.
273
282
  function addedIn(paths: string[], before: LockfileRead[], after: LockfileRead[]): DirectoryDependencies {
274
283
  const failed = [...before, ...after].find(read => 'error' in read)
275
284
  if (failed) return { paths, error: failed.error, ...failed.detail ? { detail: failed.detail } : {} }
285
+ const packages = (reads: LockfileRead[]) => reads.flatMap(read => 'packages' in read ? read.packages : [])
286
+ return addedBetween(paths, packages(before), packages(after).map(pkg => patchedIn(paths[0]!, pkg)))
287
+ }
288
+
289
+ // What the versions locked `after` add to those locked `before`, as a
290
+ // directory's lockfiles' at `paths`: the package versions after none before
291
+ // has, each once, by name and version, each with the versions of its name
292
+ // before, those past MAX_ADDED counted (`more`), not told but reviewed as
293
+ // they are; and every one after, each integrity it is locked with
294
+ // (`locked`), as many as MAX_LOCKED.
295
+ export function addedBetween(paths: string[], before: LockedPackage[], after: LockedPackage[]): DirectoryDependencies {
276
296
  const known = new Set<string>()
277
297
  const versions = new Map<string, Set<string>>()
278
- for (const pkg of before.flatMap(read => 'packages' in read ? read.packages : [])) {
298
+ for (const pkg of before) {
279
299
  known.add(lockedAs(pkg))
280
300
  const of = versions.get(pkg.name) ?? versions.set(pkg.name, new Set()).get(pkg.name)!
281
301
  if (pkg.version) of.add(pkg.version)
282
302
  }
283
303
  const added = new Map<string, AddedPackage>()
284
304
  const locked = new Map<string, LockedPackage>()
285
- for (const read of after) {
286
- for (const found of 'packages' in read ? read.packages : []) {
287
- const pkg = patchedIn(paths[0]!, found)
288
- const key = lockedAs(pkg)
289
- const held = locked.get(lockedWith(pkg))
290
- if (!held) locked.set(lockedWith(pkg), { ...pkg })
291
- else if (held.dev && !pkg.dev) delete held.dev
292
- if (known.has(key)) continue
293
- const had = added.get(key)
294
- const was = versions.get(pkg.name)
295
- if (!had) added.set(key, { ...pkg, ...was ? { was: [...was].toSorted(byVersion) } : {} })
296
- else if (had.dev && !pkg.dev) delete had.dev
297
- }
305
+ for (const pkg of after) {
306
+ const key = lockedAs(pkg)
307
+ const held = locked.get(lockedWith(pkg))
308
+ if (!held) locked.set(lockedWith(pkg), { ...pkg })
309
+ else if (held.dev && !pkg.dev) delete held.dev
310
+ if (known.has(key)) continue
311
+ const had = added.get(key)
312
+ const was = versions.get(pkg.name)
313
+ if (!had) added.set(key, { ...pkg, ...was ? { was: [...was].toSorted(byVersion) } : {} })
314
+ else if (had.dev && !pkg.dev) delete had.dev
298
315
  }
299
316
  const all = [...added.values()].toSorted(byName)
300
317
  return { paths, added: all.slice(0, MAX_LOCKED), more: Math.max(0, all.length - MAX_ADDED),
@@ -311,14 +328,15 @@ export async function pullDependencies(fullName: string, token: string, number:
311
328
  // The same, with the commits it is kept by (`commits`), its base's and
312
329
  // head's, by which `kept` reads it: those `given`, as a page of its
313
330
  // repository's open pull requests read them (repository-issues.ts), else as
314
- // GitHub has them now. Commits given that its own list of its files is no
315
- // longer of are read as GitHub has them now.
331
+ // GitHub has them now; and the branches they are of, where told (PullRefs).
332
+ // Commits given that its own list of its files is no longer of are read as
333
+ // GitHub has them now.
316
334
  export async function pullDependenciesAt(fullName: string, token: string, number: number, kept: PullDependencyStore,
317
- fetchImpl: typeof fetch = globalThis.fetch, given?: PullCommits): Promise<{ commits: string; told: PullDependencies }> {
318
- const { base, head } = given ?? await pullCommits(fullName, token, number, fetchImpl)
335
+ fetchImpl: typeof fetch = globalThis.fetch, given?: PullCommits): Promise<PullRefs & { commits: string; told: PullDependencies }> {
336
+ const { base, head, ...refs } = given ?? await pullCommits(fullName, token, number, fetchImpl)
319
337
  const key = `${base}...${head}`
320
338
  const held = await kept.read(key)
321
- if (held) return { commits: key, told: held }
339
+ if (held) return { ...refs, commits: key, told: held }
322
340
  const current = async () => {
323
341
  const now = given && await pullCommits(fullName, token, number, fetchImpl)
324
342
  return !now || (now.base === base && now.head === head)
@@ -336,5 +354,5 @@ export async function pullDependenciesAt(fullName: string, token: string, number
336
354
  })
337
355
  const told = { base: mergeBase, head, lockfiles, cut: filesCut || cut, ...cut && !filesCut && omitted.length <= MAX_OMITTED ? { omitted } : {} }
338
356
  await kept.write(key, told)
339
- return { commits: key, told }
357
+ return { ...refs, commits: key, told }
340
358
  }