@preventive/triage 1.0.0-alpha.68 → 1.0.0-alpha.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.68",
3
+ "version": "1.0.0-alpha.69",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -11,10 +11,10 @@
11
11
  import type { DependencyReview, DependencyReviewStore } from './dependency-reviews.ts'
12
12
  import type { LockedPackage } from './locked-packages.ts'
13
13
  import type { PullDependencies } from './pull-dependencies.ts'
14
- import { askedOf, comparedWith, reviewsByVersion, reviewsOf } from './pull-dependency-reviews.ts'
14
+ import { askedOf, basesOf, comparedWith, reviewsByVersion, reviewsOf } from './pull-dependency-reviews.ts'
15
15
  import { eachOf } from './queue.ts'
16
16
  import type { PublishedReview, RepoReviewState } from './repository-dependency-reviews.ts'
17
- import { type DependencyReviewEntry, type ReviewedDependencies, askReviewed } from './reviewed-dependencies.ts'
17
+ import { type DependencyReviewEntry, type ReviewedBase, type ReviewedDependencies, askReviewed } from './reviewed-dependencies.ts'
18
18
 
19
19
  const FORMAT_AT_ONCE = 8
20
20
  // The longest comment told, past which none is.
@@ -70,17 +70,18 @@ export function withFormatted<T extends DependencyReview>(reviewed: ReviewedDepe
70
70
  // ids, each with the versions it is of, as its lockfiles lock each: of its
71
71
  // version, of an integrity it is locked with and of its patch, whole,
72
72
  // compared with another package's version, or compared with a version it was
73
- // (pull-dependency-reviews.ts reviewsOf, comparedWith), or, `any`, with any
74
- // version of its package.
73
+ // or the base the host names it (`bases`; pull-dependency-reviews.ts reviewsOf,
74
+ // comparedWith, basesOf), or, `any`, with any version of its package.
75
75
  interface Own { review: PublishedReview; pkgs: LockedPackage[] }
76
- function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string, any: boolean): Map<string, Own> {
76
+ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string, any: boolean, bases: Map<string, ReviewedBase>): Map<string, Own> {
77
77
  // Theirs by the version they are of, each version probed once.
78
78
  const theirs = reviewsByVersion(reviews.filter(review => review.id !== undefined && review.reviewer === user))
79
79
  const mine = new Map<string, Own>()
80
80
  if (theirs.size === 0) return mine
81
81
  for (const pkg of told.lockfiles.flatMap(dir => 'added' in dir ? dir.added : [])) {
82
+ const against = any ? 'any' : basesOf(pkg, bases.get(askedOf(pkg)[0]) ?? null)
82
83
  for (const review of reviewsOf(pkg, theirs)) {
83
- if (comparedWith(review, pkg, any ? 'any' : pkg.was ?? [])) (mine.get(review.id!) ?? mine.set(review.id!, { review, pkgs: [] }).get(review.id!)!).pkgs.push(pkg)
84
+ if (comparedWith(review, pkg, against)) (mine.get(review.id!) ?? mine.set(review.id!, { review, pkgs: [] }).get(review.id!)!).pkgs.push(pkg)
84
85
  }
85
86
  }
86
87
  return mine
@@ -99,9 +100,10 @@ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: str
99
100
  // reviews of comments (`parseComments`), what a review was compared with is
100
101
  // its to weigh, so one compared with any version is given.
101
102
  export async function formattedPull(reviewed: ReviewedDependencies | null, db: Pick<DependencyReviewStore, 'listOwnDependencyReviewsById'>, user: string,
102
- told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = []): Promise<string | null> {
103
+ told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = [],
104
+ bases: Map<string, ReviewedBase> = new Map()): Promise<string | null> {
103
105
  if (!reviewed?.formatDependencyReviews || !state) return null
104
- const mine = ownOfPull(told, state.reviews, user, reviewed.parseComments !== undefined)
106
+ const mine = ownOfPull(told, state.reviews, user, reviewed.parseComments !== undefined, bases)
105
107
  if (mine.size === 0) return null
106
108
  const { passed } = await askReviewed(reviewed.lookup, new Map([...mine.values()].flatMap(({ pkgs }) => pkgs.map(askedOf))))
107
109
  const there = reviewsByVersion(commented.filter(review => review.reviewer === user))
@@ -240,7 +240,7 @@ import { AGENTS_READ_VERSION, type AuthoredCommit, type BranchTip, type BranchTi
240
240
  import { DEPENDENCIES_LABEL, ISSUES_CURSOR, ISSUES_READ_VERSION, OPEN_PULLS_READ, OPEN_PULLS_SIZES, repositoryIssues, repositoryItem, repositoryLabel, repositoryOpenPulls } from './repository-issues.ts'
241
241
  import { type DirectoryDependencies, type GithubAsked, type ListedLockfile, type LockfileRead, type LockfileStore, MAX_LOCKED, PULL_DEPENDENCIES_READ, type PullCommits,
242
242
  type PullDependencies,
243
- type PullDependencyStore, type PullRefs, lockfileFormat, pullDependenciesAt, pullRefs } from './pull-dependencies.ts'
243
+ type PullDependencyStore, type PullRefs, lockfileFormat, pullDependenciesAt, pullKey, pullRefs } from './pull-dependencies.ts'
244
244
  import { eachOf } from './queue.ts'
245
245
  import { lockedAt, lockedIn, lockfilesAt } from './commit-lockfiles.ts'
246
246
  import { MAX_REQUIRED_REVIEWS, type PublishedReview, type RepoDependencyReview } from './repository-dependency-reviews.ts'
@@ -249,7 +249,7 @@ import { type StasisDependencyReader, stasisDependencyReader, stasisDirectory, w
249
249
  import { type BundledVersion, bundleDependencies, installsBundle } from './bundle-dependency-reviews.ts'
250
250
  import { type CommentReviews, type ReviewBaselineStore, baselineFor, heldDependencies, reviewedDependencies, reviewedPackages } from './pull-dependency-reviews.ts'
251
251
  import { formattedPull, withFormatted } from './dependency-review-comments.ts'
252
- import type { ReviewedDependencies } from './reviewed-dependencies.ts'
252
+ import type { ReviewedBase, ReviewedDependencies } from './reviewed-dependencies.ts'
253
253
  import { commentReviews } from './pull-comment-reviews.ts'
254
254
  import { PULSE_WEEKS, PULSE_YEAR_VERSION, type PulseNarrowing, type PulseStats, StatsPending, commitStats, defaultHead, periodStats, pulseSince,
255
255
  repositoryActivity, repositoryLines,
@@ -2606,26 +2606,33 @@ async function pullDependencyAnswer(deps: ManagedHttpDeps, fullName: string, tok
2606
2606
  commits?: PullCommits) {
2607
2607
  const kept = pullDependencyKept(deps, repoId)
2608
2608
  const reading: { told?: PullDependencies } = {}
2609
+ // Where its review is on, those of lockfiles it leaves out told to none,
2610
+ // whoever asks.
2611
+ const setting = await deps.db.repoDependencyReview(repoId)
2612
+ // Where the host names bases and its review is asked for and on, one into
2613
+ // the default branch is read without its merge base (`baseless`,
2614
+ // pull-dependencies.ts): the branch's own state is told apart.
2615
+ const repo = review && deps.reviewedDependencies?.base && setting?.enabled ? (await deps.db.listSelectedRepos()).find(row => row.repoId === repoId) : undefined
2616
+ const into = repo ? repo.cachedDefaultBranch ?? repo.defaultBranch : null
2609
2617
  // With the branches they are of, where told, kept with them.
2610
2618
  const answered = commits ? { value: { baseRef: commits.baseRef, headRef: commits.headRef, fork: commits.fork, commits: `${commits.base}...${commits.head}` }, kept: true }
2611
2619
  : await keptAnswer(deps, `${repoId}\0pull-commits\0${PULL_DEPENDENCIES_READ}\0${number}`, async () => {
2612
- const { told, ...read } = await pullDependenciesAt(fullName, token, number, kept)
2620
+ const { told, ...read } = await pullDependenciesAt(fullName, token, number, kept, undefined, undefined, into)
2613
2621
  reading.told = told
2614
2622
  return read
2615
2623
  }, undefined, false, stampOf(deps, repoId, fullName, token))
2616
2624
  // What its commits tell, as read, else as kept by them, else, no longer
2617
2625
  // kept, read again: by those given, without asking GitHub for them.
2618
- const held = reading.told ?? (typeof answered.value.commits === 'string' ? await kept.read(answered.value.commits) : null)
2619
- const pulled = { number, ...held ?? (await pullDependenciesAt(fullName, token, number, kept, undefined, commits)).told }
2620
- // Where its review is on, those of lockfiles it leaves out told to none,
2621
- // whoever asks.
2622
- const setting = await deps.db.repoDependencyReview(repoId)
2626
+ const baseless = into !== null && answered.value.baseRef === into
2627
+ const held = reading.told ?? (typeof answered.value.commits === 'string' ? await kept.read(pullKey(answered.value.commits, baseless)) : null)
2628
+ const pulled = { number, ...held ?? (await pullDependenciesAt(fullName, token, number, kept, undefined, commits, into)).told }
2623
2629
  // With what the stasis.config.json files it holds to reach, each a
2624
2630
  // directory of its own, none waited for; a lockfile's versions those reach
2625
2631
  // not marked as its package manager's alone (withReach).
2626
2632
  const asked: GithubAsked = { github: false }
2627
2633
  const scoped = setting?.enabled ? withReach(heldDependencies({ ...pulled, lockfiles: [...pulled.lockfiles,
2628
- ...await stasisDirectories(deps, fullName, token, repoId, setting.lockfiles, pulled.base, pulled.head, asked, pullRefs(answered.value.baseRef, answered.value.headRef, answered.value.fork))] },
2634
+ ...await stasisDirectories(deps, fullName, token, repoId, setting.lockfiles, pulled.base, pulled.head, asked, pullRefs(answered.value.baseRef, answered.value.headRef, answered.value.fork),
2635
+ pulled.baseless === true)] },
2629
2636
  setting.lockfiles)) : pulled
2630
2637
  const now = review ? await deps.db.repoDependencyReviewState(repoId, user.id, reviewedPackages(scoped)) : null
2631
2638
  // Its review by the lockfiles they were told by, though they have changed
@@ -2648,28 +2655,29 @@ async function pullDependencyAnswer(deps: ManagedHttpDeps, fullName: string, tok
2648
2655
  })
2649
2656
  // Each patch its lockfiles name by its hash alone with its file (npm-patch.ts), where its review is in effect.
2650
2657
  const patched = state ? await withPatchFiles(told, repoId, fullName, token, patchStore(deps.db, deps.config.debug), asked) : told
2651
- const dependencies = await reviewedDependencies(patched, state, { baseline, baselineUnread: unread, baselineError: error, reviewed, commentReviews: noting })
2658
+ const bases = new Map<string, ReviewedBase>()
2659
+ const dependencies = await reviewedDependencies(patched, state, { baseline, baselineUnread: unread, baselineError: error, reviewed, commentReviews: noting, namedBases: bases })
2652
2660
  // The comment the host formats of the reader's reviews of its versions, for
2653
2661
  // its copy button, but those its comments make of theirs already.
2654
- const formatted = await formattedPull(reviewed, deps.db, user.id, told, state, { repository: fullName, number }, commented)
2662
+ const formatted = await formattedPull(reviewed, deps.db, user.id, told, state, { repository: fullName, number }, commented, bases)
2655
2663
  return { value: { number: told.number, ...dependencies, ...formatted ? { formatted } : {} }, kept: answered.kept && held !== null && !asked.github }
2656
2664
  }
2657
2665
 
2658
2666
  // What the stasis.config.json files repository `repoId`'s review holds to
2659
2667
  // (`scope`) have Stasis reach, each a directory of dependencies by its own
2660
2668
  // path (stasis-dependencies.ts stasisDirectory): at `head`, against `base`
2661
- // where one is given. None is waited for: one not built yet is built behind
2669
+ // where one is given and it isn't read without it (`baseless`). None is waited for: one not built yet is built behind
2662
2670
  // the answer (stasisReader), told the branch its commit is of where `refs`
2663
2671
  // names it, a pull request's head's, or its base's, which holds `base`. An
2664
2672
  // open pull request's head that is a fork's (`refs.fork`) is no commit of
2665
2673
  // the repository's own, which Stasis refuses: nothing is built for it.
2666
2674
  function stasisDirectories(deps: ManagedHttpDeps, fullName: string, token: string, repoId: number, scope: LockfileScope, base: string | null, head: string,
2667
- asked: GithubAsked, refs: PullRefs = {}): Promise<DirectoryDependencies[]> {
2675
+ asked: GithubAsked, refs: PullRefs = {}, baseless = false): Promise<DirectoryDependencies[]> {
2668
2676
  if (refs.fork) return Promise.resolve(stasisConfigs(scope).map(config => ({ paths: [config], error: 'stasis-failed', detail: 'commit-not-own' })))
2669
2677
  const reader = stasisReader(deps), reads = lockfileKept(deps, repoId)
2670
2678
  return Promise.all(stasisConfigs(scope).map(config => stasisDirectory(config, base, head,
2671
2679
  commit => reader.read({ repoId, fullName }, token, commit, config, commit === head ? refs.headRef : refs.baseRef),
2672
- (commit, held) => lockedAt(fullName, token, commit, reads, held, asked))))
2680
+ (commit, held) => lockedAt(fullName, token, commit, reads, held, asked), baseless)))
2673
2681
  }
2674
2682
 
2675
2683
  // What reads repositories' Stasis dependencies, one a database: kept by it,
@@ -2952,21 +2960,24 @@ async function keptPullCommits(deps: ManagedHttpDeps, repoId: number, numbers: n
2952
2960
  }
2953
2961
 
2954
2962
  // The lines the versions wanting reviews of `answers` change, as their rows
2955
- // show them (npm-delta.js deltaBase), a patched one's none, where they are
2963
+ // show them (npm-delta.js reviewBase), a patched one's none, where they are
2956
2964
  // counted already: of public versions alone, those npm answered for in a day
2957
2965
  // (npmVersionStore), their integrities those npmDelta keys them by. `[name,
2958
2966
  // version, base, delta]` each, none counted here.
2959
2967
  async function teamDeltas(deps: ManagedHttpDeps, answers: object[]) {
2960
2968
  const asked = new Map<string, [string, string, string]>()
2961
- for (const answer of answers as { lockfiles?: { added?: unknown; unreviewed?: unknown }[]; review?: { required?: number } }[]) {
2969
+ for (const answer of answers as { lockfiles?: { added?: unknown; unreviewed?: unknown }[]; review?: { required?: number; reviewedBases?: true } }[]) {
2962
2970
  const required = answer.review?.required
2963
2971
  if (!Number.isSafeInteger(required)) continue
2964
2972
  for (const pkg of (answer.lockfiles ?? []).flatMap(dir => [...Array.isArray(dir.added) ? dir.added : [], ...Array.isArray(dir.unreviewed) ? dir.unreviewed : []]) as
2965
- { name?: unknown; version?: unknown; source?: unknown; was?: unknown; reviews?: unknown; rejected?: unknown; baseline?: unknown; reviewed?: unknown; unsupported?: unknown
2966
- patch?: unknown }[]) {
2973
+ { name?: unknown; version?: unknown; source?: unknown; was?: unknown; base?: { name?: unknown; version?: unknown }; reviews?: unknown; rejected?: unknown; baseline?: unknown
2974
+ reviewed?: unknown; unsupported?: unknown; patch?: unknown }[]) {
2967
2975
  if (pkg.source !== 'registry' || pkg.patch || typeof pkg.name !== 'string' || typeof pkg.version !== 'string' || !isExactVersion(pkg.version)) continue
2968
2976
  if (pkg.unsupported || pkg.baseline || pkg.reviewed || typeof pkg.reviews !== 'number' || (pkg.reviews >= required! && !pkg.rejected)) continue
2969
- const was = Array.isArray(pkg.was) ? pkg.was.find(prior => typeof prior === 'string' && prior !== pkg.version) as string | undefined : undefined
2977
+ // Against the base the host names, where it names them; one of another package's not counted.
2978
+ if (answer.review?.reviewedBases && pkg.base && pkg.base.name !== pkg.name) continue
2979
+ const was = answer.review?.reviewedBases ? pkg.base?.version as string | undefined
2980
+ : Array.isArray(pkg.was) ? pkg.was.find(prior => typeof prior === 'string' && prior !== pkg.version) as string | undefined : undefined
2970
2981
  asked.set(`${pkg.name}\0${pkg.version}\0${was ?? '(empty)'}`, [pkg.name, pkg.version, was ?? '(empty)'])
2971
2982
  }
2972
2983
  }
@@ -87,8 +87,8 @@ export function touchesLockfile(paths: string[], changed: number): boolean | nul
87
87
  // A package version new to a directory, as its lockfile locks it, with its
88
88
  // integrity, which its reviews are held to; of a package its lockfiles locked
89
89
  // before, the versions of it they did (`was`, the highest first), none of one
90
- // new to it.
91
- export type AddedPackage = LockedPackage & { was?: string[] }
90
+ // new to it; and the version the host names to review it against (`base`).
91
+ export type AddedPackage = LockedPackage & { was?: string[]; base?: { name: string; version: string } }
92
92
  // A directory's lockfiles the pull request changes (`paths`, those it adds,
93
93
  // modifies, removes or renames, by either name): the package versions they
94
94
  // lock new to it, by name and version (as many as MAX_LOCKED, told as many
@@ -105,11 +105,14 @@ export type DirectoryDependencies = { paths: string[] } & ({ added: AddedPackage
105
105
  // in; and `cut` where it changes more files than GitHub lists, or lockfiles
106
106
  // in more directories than are read, with, where only those cut it and they
107
107
  // are few enough, the paths of those directories' lockfiles (`omitted`), for
108
- // a review holding to none of them to fail in nothing.
109
- export interface PullDependencies { base: string; head: string; lockfiles: DirectoryDependencies[]; cut: boolean; omitted?: string[] }
108
+ // a review holding to none of them to fail in nothing; and whether it was
109
+ // read without its merge base (`baseless`), every version new to it.
110
+ export interface PullDependencies { base: string; head: string; lockfiles: DirectoryDependencies[]; cut: boolean; omitted?: string[]; baseless?: true }
110
111
  const MAX_OMITTED = 1000
111
112
 
112
- // What is told of a pull request, by the commits it is of, `${base}...${head}`.
113
+ // What is told of a pull request, by the commits it is of, `${base}...${head}`,
114
+ // read without its merge base apart (pullKey).
115
+ export const pullKey = (commits: string, baseless: boolean) => baseless ? `${commits}\0baseless` : commits
113
116
  export interface PullDependencyStore {
114
117
  read(key: string): Promise<PullDependencies | null>
115
118
  write(key: string, value: PullDependencies): Promise<void>
@@ -329,33 +332,36 @@ export async function pullDependencies(fullName: string, token: string, number:
329
332
  return (await pullDependenciesAt(fullName, token, number, kept, fetchImpl)).told
330
333
  }
331
334
  // The same, with the commits it is kept by (`commits`), its base's and
332
- // head's, by which `kept` reads it: those `given`, as a page of its
335
+ // head's, by which `kept` reads it (pullKey): those `given`, as a page of its
333
336
  // repository's open pull requests read them (repository-issues.ts), else as
334
337
  // GitHub has them now; and the branches they are of, where told (PullRefs).
335
338
  // Commits given that its own list of its files is no longer of are read as
336
- // GitHub has them now.
339
+ // GitHub has them now. One into branch `baselessInto` is read without its
340
+ // merge base's lockfiles (`baseless`).
337
341
  export async function pullDependenciesAt(fullName: string, token: string, number: number, kept: PullDependencyStore,
338
- fetchImpl: typeof fetch = globalThis.fetch, given?: PullCommits): Promise<PullRefs & { commits: string; told: PullDependencies }> {
342
+ fetchImpl: typeof fetch = globalThis.fetch, given?: PullCommits, baselessInto: string | null = null): Promise<PullRefs & { commits: string; told: PullDependencies }> {
339
343
  const { base, head, ...refs } = given ?? await pullCommits(fullName, token, number, fetchImpl)
340
- const key = `${base}...${head}`
344
+ const baseless = baselessInto !== null && refs.baseRef === baselessInto, commits = `${base}...${head}`, key = pullKey(commits, baseless)
341
345
  const held = await kept.read(key)
342
- if (held) return { ...refs, commits: key, told: held }
346
+ if (held) return { ...refs, commits, told: held }
343
347
  const current = async () => {
344
348
  const now = given && await pullCommits(fullName, token, number, fetchImpl)
345
349
  return !now || (now.base === base && now.head === head)
346
350
  }
347
351
  const pulled = await pullFiles(fullName, token, number, base, head, fetchImpl, current)
348
- if (!pulled) return pullDependenciesAt(fullName, token, number, kept, fetchImpl)
352
+ if (!pulled) return pullDependenciesAt(fullName, token, number, kept, fetchImpl, undefined, baselessInto)
349
353
  const { mergeBase, files, cut: filesCut } = pulled
350
354
  const { directories, cut, omitted } = lockfilesChanged(files)
351
- const reads = directories.flatMap(({ before, after }) => [...before.map(lockfile => [mergeBase, lockfile] as const), ...after.map(lockfile => [head, lockfile] as const)])
355
+ const reads = directories.flatMap(({ before, after }) => [...baseless ? [] : before.map(lockfile => [mergeBase, lockfile] as const),
356
+ ...after.map(lockfile => [head, lockfile] as const)])
352
357
  const read = await eachOf(reads, READ_PARALLEL, ([ref, lockfile]) => readLockfile(fullName, token, ref, lockfile))
353
358
  let at = 0
354
359
  const lockfiles = directories.map(({ before, after, paths }) => {
355
- const readBefore = read.slice(at, at += before.length)
360
+ const readBefore = baseless ? [] : read.slice(at, at += before.length)
356
361
  return addedIn([...paths].toSorted(), readBefore, read.slice(at, at += after.length))
357
362
  })
358
- const told = { base: mergeBase, head, lockfiles, cut: filesCut || cut, ...cut && !filesCut && omitted.length <= MAX_OMITTED ? { omitted } : {} }
363
+ const told = { base: mergeBase, head, lockfiles, cut: filesCut || cut, ...cut && !filesCut && omitted.length <= MAX_OMITTED ? { omitted } : {},
364
+ ...baseless ? { baseless: true as const } : {} }
359
365
  await kept.write(key, told)
360
- return { ...refs, commits: key, told }
366
+ return { ...refs, commits, told }
361
367
  }
@@ -18,7 +18,7 @@
18
18
  // project's isn't. Its reviews are those of it, of an integrity it is locked
19
19
  // with, either whole, compared with any version of another package, or
20
20
  // compared with a version of its own: for a version the pull request adds,
21
- // one it was; for another, any. A patched
21
+ // one it was, or the one the host names (`base`, withBases); for another, any. A patched
22
22
  // one's (`patch`) are of it as patched, by its patch's hash, its patch read
23
23
  // of the repository at its file, which its lockfile names, or which is found
24
24
  // where it names it by its hash alone (npm-patch.ts withPatchFiles):
@@ -34,9 +34,9 @@ import { GithubApiError } from './github-errors.ts'
34
34
  import type { LockedPackage } from './locked-packages.ts'
35
35
  import { EVERY_LOCKFILE, type LockfileScope, heldTo, isEvery, reviewedIn } from './lockfile-scope.ts'
36
36
  import { type Lru, lru } from './lru.ts'
37
- import { type DirectoryDependencies, type GithubAsked, type LockfileStore, MAX_ADDED, type PullDependencies, lockedAs, lockedWith } from './pull-dependencies.ts'
37
+ import { type AddedPackage, type DirectoryDependencies, type GithubAsked, type LockfileStore, MAX_ADDED, type PullDependencies, lockedAs, lockedWith } from './pull-dependencies.ts'
38
38
  import type { PublishedReview, RepoReviewState } from './repository-dependency-reviews.ts'
39
- import { type ReviewedDependencies, type ReviewedDependency, askReviewed } from './reviewed-dependencies.ts'
39
+ import { type ReviewedBase, type ReviewedDependencies, type ReviewedDependency, askBases, askReviewed } from './reviewed-dependencies.ts'
40
40
 
41
41
  // The other versions told unreviewed, and those told unsupported, of each
42
42
  // directory, those past them counted.
@@ -181,24 +181,31 @@ function judge(pkg: LockedPackage, bases: string[] | 'any', { state, reviews, ba
181
181
  // of them, and those of all that want one (`toReview`); the others its lockfiles lock that want reviews, and every one
182
182
  // that can't be reviewed (as many of each as MAX_UNREVIEWED, how many more,
183
183
  // once `capped`); and how many it locks past those read (`moreLocked`), which
184
- // aren't checked; without `review`, what it adds alone.
185
- function reviewedDirectory(dir: DirectoryDependencies, review: Judge | null) {
184
+ // aren't checked; without `review`, what it adds alone. Read without its
185
+ // base (`baseless`), it tells only those it adds that pass none.
186
+ function reviewedDirectory(dir: DirectoryDependencies, review: Judge | null, baseless = false) {
186
187
  if ('error' in dir) return dir
187
188
  const { locked, moreLocked, added, ...told } = dir
188
- if (!review) return { ...told, added: added.slice(0, MAX_ADDED).map(shown) }
189
+ if (!review) return { ...told, added: baseless ? [] : added.slice(0, MAX_ADDED).map(shown), ...baseless ? { more: 0 } : {} }
189
190
  const adds = new Map(added.map(pkg => [lockedAs(pkg), { pkg, variants: [pkg] }]))
190
191
  for (const pkg of locked) {
191
192
  const of = adds.get(lockedAs(pkg))
192
193
  if (of && lockedWith(pkg) !== lockedWith(of.pkg)) of.variants.push(pkg)
193
194
  }
194
195
  const own = [...adds.values()].map(({ pkg, variants }) => {
195
- const judged = variants.map(variant => ({ variant, ...review(variant, pkg.was ?? []) }))
196
+ const judged = variants.map(variant => ({ variant, ...review(variant, basesOf(pkg, (variant as AddedPackage).base ?? null)) }))
196
197
  const least = judged.find(one => 'unsupported' in one.review) ?? judged.find(one => one.wants) ?? judged[0]!
197
198
  return { pkg, judged: least, wanting: judged.filter(one => one.wants).map(({ variant }) => variant) }
198
199
  })
199
200
  const others = locked.filter(pkg => !adds.has(lockedAs(pkg))).map(pkg => ({ pkg, judged: review(pkg, 'any') }))
200
201
  const unsupported = locked.flatMap(pkg => { const as = reviewedAs(pkg); return as === 'version' || as === 'skip' ? [] : [{ ...shown(pkg), unsupported: as }] })
201
- return { ...told, added: own.slice(0, MAX_ADDED).map(({ pkg, judged }) => ({ ...shown(pkg), ...judged.review })),
202
+ const listed = baseless ? own.filter(({ judged }) => judged.wants || 'unsupported' in judged.review) : own
203
+ // Each row against the base of the way it is locked that it is told by.
204
+ const row = ({ pkg, judged }: (typeof own)[number]) => {
205
+ const { base: _base, ...rest } = shown(pkg as AddedPackage), { base } = judged.variant as AddedPackage
206
+ return { ...rest, ...base ? { base } : {}, ...judged.review }
207
+ }
208
+ return { ...told, ...baseless ? { more: Math.max(0, listed.length - MAX_ADDED) } : {}, added: listed.slice(0, MAX_ADDED).map(row),
202
209
  toReview: own.flatMap(({ wanting }) => wanting.map(shown)),
203
210
  unreviewed: others.filter(({ judged }) => judged.wants).map(({ pkg, judged }) => ({ ...shown(pkg), ...judged.review })), unsupported, moreLocked }
204
211
  }
@@ -215,6 +222,20 @@ const distinct = (lists: Shown[][], key: (pkg: Shown) => string) => new Set(list
215
222
  const versionKey = (pkg: Shown) => `${pkg.name}@${pkg.version ?? ''}\0${pkg.patch?.hash ?? ''}`
216
223
  const sourceKey = (pkg: Shown) => `${pkg.source}\0${pkg.name}@${pkg.version ?? ''}\0${pkg.from ?? ''}`
217
224
 
225
+ // The versions of its package an added version's reviews may be compared
226
+ // with: those it was, and the base the host names it (null for none).
227
+ export const basesOf = (pkg: AddedPackage, base: ReviewedBase | null | undefined = pkg.base) => [...pkg.was ?? [], ...base?.name === pkg.name ? [base.version] : []]
228
+ // `dirs`, each version of `asking` as it is locked with the version `base`
229
+ // names to review it against (`base`, of its package or another), its row's
230
+ // link and line count then against that one, and its reviews against it
231
+ // passing it; each named onto `named` too, by what it is asked.
232
+ async function withBases(dirs: DirectoryDependencies[], base: NonNullable<ReviewedDependencies['base']>, asking: Map<string, ReviewedDependency>,
233
+ named: Map<string, ReviewedBase>): Promise<DirectoryDependencies[]> {
234
+ for (const [key, one] of asking.size > 0 ? await askBases(base, asking) : []) named.set(key, one)
235
+ const based = <P extends LockedPackage>(pkg: P) => { const one = named.get(askedOf(pkg)[0]); return one ? { ...pkg, base: one } : pkg }
236
+ return dirs.map(dir => 'error' in dir ? dir : { ...dir, added: dir.added.map(based), locked: dir.locked.map(based) })
237
+ }
238
+
218
239
  // The reviews an open pull request's comments make of `wanting`, the
219
240
  // versions still wanting one (pull-comment-reviews.ts): those that count,
220
241
  // and whether they couldn't be read.
@@ -232,12 +253,14 @@ export function heldDependencies<T extends PullDependencies>(told: T, scope: Loc
232
253
  // A pull request's dependencies as the client is told them: without the
233
254
  // versions its directories lock; with `state`, a repository's review in
234
255
  // effect, each version's review (reviewedDirectory), those wanting one asked
235
- // of the registered reviewed dependencies (`reviewed`), and those still
256
+ // of the registered reviewed dependencies (`reviewed`), those they don't pass
257
+ // of their `base` (onto `namedBases`), and those still
236
258
  // wanting one of the reviews its comments make (`commentReviews`, where the
237
259
  // host reads them), and the review's terms (`review`), with how many
238
260
  // reviewers' its comments count (`commentReviews`), or that they couldn't be
239
261
  // read (`commentsFailed`), and that reviews count by comments alone, those
240
- // published here not (`byComments`, where the host reads them), and how many versions across its directories want
262
+ // published here not (`byComments`, where the host reads them), and that
263
+ // they name bases (`reviewedBases`), and how many versions across its directories want
241
264
  // reviews, of those it adds (`toReview`) and the rest (`unreviewed`), and
242
265
  // can't be reviewed (`unsupported`), each once; how many the reviewed dependencies failed to
243
266
  // answer (`unasked`), and whether they are registered (`reviewedDependencies`,
@@ -250,12 +273,14 @@ export function heldDependencies<T extends PullDependencies>(told: T, scope: Loc
250
273
  // lockfiles the review holds to (`lockfiles`, lockfile-scope.ts, told in its
251
274
  // terms where not every one) are left out (heldDependencies).
252
275
  export async function reviewedDependencies(told: PullDependencies, state: RepoReviewState | null,
253
- { baseline = null, baselineUnread = [], baselineError = null, reviewed = null, commentReviews = null }: { baseline?: Set<string> | null; baselineUnread?: string[]
254
- baselineError?: string | null; reviewed?: ReviewedDependencies | null; commentReviews?: CommentReviews | null } = {}) {
276
+ { baseline = null, baselineUnread = [], baselineError = null, reviewed = null, commentReviews = null, namedBases = new Map() }: { baseline?: Set<string> | null
277
+ baselineUnread?: string[]; baselineError?: string | null; reviewed?: ReviewedDependencies | null; commentReviews?: CommentReviews | null; namedBases?: Map<string, ReviewedBase> } = {}) {
255
278
  const scope = state?.lockfiles ?? EVERY_LOCKFILE
256
279
  const answered = heldDependencies(told, scope)
257
- if (!state) return { ...answered, lockfiles: answered.lockfiles.map(dir => reviewedDirectory(dir, null)) }
258
- const { cut, lockfiles: held } = answered
280
+ const baseless = told.baseless === true
281
+ if (!state) return { ...answered, lockfiles: answered.lockfiles.map(dir => reviewedDirectory(dir, null, baseless)) }
282
+ const { cut } = answered
283
+ let held = answered.lockfiles
259
284
  // Reviews published here count but where the host reads those pull
260
285
  // requests' comments make (`parseComments`): what is reviewed is then the
261
286
  // host's to tell, by those and its `lookup`, and one published here counts
@@ -283,18 +308,20 @@ export async function reviewedDependencies(told: PullDependencies, state: RepoRe
283
308
  }
284
309
  const asked = wanting()
285
310
  await ask(asked)
311
+ const parsing = new Map([...asked].filter(([key]) => !passed.has(key)))
312
+ // Those `lookup` doesn't pass against the bases the host names them.
313
+ if (reviewed?.base) held = await withBases(held, reviewed.base, parsing, namedBases)
286
314
  // Of those still wanting one, and every other one the lockfiles it holds
287
315
  // to add that its teams' reviews pass, telling other pull requests those
288
316
  // it reviews (`commented`), but those `lookup` passes, reviewed, the
289
317
  // reviews its comments make, an open one's alone (pull-comment-reviews.ts),
290
318
  // which count as its teams' do; those their rejects hold asked of `lookup`
291
319
  // too.
292
- const parsing = new Map([...asked].filter(([key]) => !passed.has(key)))
293
320
  if (commentReviews) {
294
321
  const others = new Map<string, ReviewedDependency>()
295
322
  for (const pkg of held.flatMap(dir => 'added' in dir ? dir.added : [])) {
296
323
  const [key, dependency] = askedOf(pkg)
297
- if (!asked.has(key) && 'reviews' in judge(pkg, pkg.was ?? [], context).review) others.set(key, dependency)
324
+ if (!asked.has(key) && 'reviews' in judge(pkg, basesOf(pkg), context).review) others.set(key, dependency)
298
325
  }
299
326
  const vouched = others.size > 0 && reviewed ? (await askReviewed(reviewed.lookup, others)).passed : new Set<string>()
300
327
  for (const [key, dependency] of others) if (!vouched.has(key)) parsing.set(key, dependency)
@@ -307,11 +334,12 @@ export async function reviewedDependencies(told: PullDependencies, state: RepoRe
307
334
  const dirs = held.map(dir => reviewedDirectory(dir, (pkg, bases) => {
308
335
  const judged = judge(pkg, bases, context)
309
336
  return judged.wants && passed.has(askedOf(pkg)[0]) ? { review: { reviewed: true }, wants: false } : judged
310
- }))
337
+ }, baseless))
311
338
  const unread = baselineUnread.filter(path => heldTo(scope, path))
312
339
  const listed = dirs.filter(dir => 'unreviewed' in dir)
313
340
  return { ...answered, cut, lockfiles: dirs.map(dir => 'unreviewed' in dir ? capped(dir) : dir), review: { required: state.required,
314
- since: reviewed ? null : state.since, canReview: state.canReview, ...reviewed ? { reviewedDependencies: true } : {}, ...reviewed?.parseComments ? { byComments: true } : {},
341
+ since: reviewed ? null : state.since, canReview: state.canReview, ...reviewed ? { reviewedDependencies: true } : {}, ...reviewed?.base ? { reviewedBases: true } : {},
342
+ ...reviewed?.parseComments ? { byComments: true } : {},
315
343
  toReview: distinct(listed.map(dir => dir.toReview), versionKey), unreviewed: distinct(listed.map(dir => dir.unreviewed), versionKey),
316
344
  unsupported: distinct(listed.map(dir => dir.unsupported), sourceKey),
317
345
  ...unasked > 0 ? { unasked } : {}, ...baselineError && !reviewed ? { baselineError } : {},
@@ -1,7 +1,9 @@
1
1
  // The reviewed dependencies a host keeps beyond the app, as it registers
2
2
  // them before the server is assembled (server.ts registerReviewedDependencies):
3
3
  // an async method telling whether a dependency, as a lockfile locks it, is
4
- // reviewed there (`lookup`), and, optionally, one reading the reviews of
4
+ // reviewed there (`lookup`), and, optionally, one naming the version to
5
+ // review one a pull request adds against (`base`, pull-dependency-reviews.ts),
6
+ // one reading the reviews of
5
7
  // dependencies an open pull request's comments make (`parseComments`,
6
8
  // pull-comment-reviews.ts), and one formatting one's own dependency reviews
7
9
  // as a comment, for a copy button to give (`formatDependencyReviews`,
@@ -14,9 +16,11 @@
14
16
  // comments' reviews count for the pull request alone, as it is open: the
15
17
  // host's to keep, as it is merged, among those `lookup` tells of.
16
18
  //
17
- // Each version is asked of `lookup` once a request, as many at once as
19
+ // Each version is asked of `lookup` (and `base`) once a request, as many at once as
18
20
  // ASK_AT_ONCE, its answer kept in this instance KEPT_MS; one it fails to
19
- // answer is unreviewed, and counted so (`unasked`).
21
+ // answer is unreviewed, and counted so (`unasked`), or has no base.
22
+ import { isExactVersion } from '@preventive/upstream/semver.js'
23
+ import { isNpmPackageName } from '../common/managed/npm-packages.js'
20
24
  import { type Lru, lru } from './lru.ts'
21
25
 
22
26
  export type ReviewedLockfile = 'npm' | 'pnpm' | 'yarn1'
@@ -87,8 +91,12 @@ export interface DependencyReviewEntry {
87
91
  // What `formatDependencyReviews` formats: one's own reviews, never another's,
88
92
  // and the pull request whose versions they are of, where its copy asks.
89
93
  export interface FormatDependencyReviewsInput { reviews: DependencyReviewEntry[]; pullRequest?: { repository: string; number: number } }
94
+ // A version to review a dependency against: of its package or another.
95
+ export interface ReviewedBase { name: string; version: string }
90
96
  export interface ReviewedDependencies {
91
97
  lookup(dependency: ReviewedDependency): Promise<boolean>
98
+ // The reviewed version to review it against; none for its whole package.
99
+ base?(dependency: ReviewedDependency): Promise<ReviewedBase | null | undefined>
92
100
  parseComments?(input: ParseCommentsInput): Promise<CommentReview[]>
93
101
  // The comment to copy, none where it is empty, null or undefined.
94
102
  formatDependencyReviews?(input: FormatDependencyReviewsInput): Promise<string | null | undefined>
@@ -99,19 +107,20 @@ const KEPT_MS = 60_000
99
107
 
100
108
  let registered: ReviewedDependencies | null = null
101
109
  let assembled = false
102
- // Each lookup's answers, apart.
103
- const answers = new WeakMap<ReviewedDependencies['lookup'], Lru<{ at: number; reviewed: boolean }>>()
110
+ // Each method's answers, apart.
111
+ const answers = new WeakMap<object, Lru<{ at: number; value: unknown }>>()
104
112
 
105
113
  // Registers the host's reviewed dependencies, once, before the server is
106
114
  // assembled (init()): a server already assembled keeps what it was given.
107
115
  export function registerReviewedDependencies(reviewed: ReviewedDependencies): void {
108
116
  const optional = (method: unknown) => method === undefined || typeof method === 'function'
109
- if (typeof reviewed?.lookup !== 'function' || !optional(reviewed.parseComments) || !optional(reviewed.formatDependencyReviews)) {
110
- throw new TypeError('registerReviewedDependencies: expected { lookup, parseComments?, formatDependencyReviews? }, async methods')
117
+ if (typeof reviewed?.lookup !== 'function' || !optional(reviewed.base) || !optional(reviewed.parseComments) || !optional(reviewed.formatDependencyReviews)) {
118
+ throw new TypeError('registerReviewedDependencies: expected { lookup, base?, parseComments?, formatDependencyReviews? }, async methods')
111
119
  }
112
120
  if (assembled) throw new Error('registerReviewedDependencies: call it before init(), as the server takes them as it is assembled')
113
121
  if (registered) throw new Error('registerReviewedDependencies: reviewed dependencies are registered already')
114
- registered = { lookup: reviewed.lookup.bind(reviewed), ...reviewed.parseComments ? { parseComments: reviewed.parseComments.bind(reviewed) } : {},
122
+ registered = { lookup: reviewed.lookup.bind(reviewed), ...reviewed.base ? { base: reviewed.base.bind(reviewed) } : {},
123
+ ...reviewed.parseComments ? { parseComments: reviewed.parseComments.bind(reviewed) } : {},
115
124
  ...reviewed.formatDependencyReviews ? { formatDependencyReviews: reviewed.formatDependencyReviews.bind(reviewed) } : {} }
116
125
  }
117
126
 
@@ -122,28 +131,39 @@ export function assembledReviewedDependencies(): ReviewedDependencies | null {
122
131
  return registered
123
132
  }
124
133
 
125
- // Which of `dependencies`, by their keys, `lookup` passes, and how many it
126
- // failed to answer.
127
- export async function askReviewed(lookup: ReviewedDependencies['lookup'], dependencies: Map<string, ReviewedDependency>): Promise<{ passed: Set<string>; unasked: number }> {
128
- const passed = new Set<string>()
129
- let unasked = 0
134
+ // What `method` answers for each of `dependencies`, by their keys; one it
135
+ // fails to answer for left out, and logged, as failing to `what`.
136
+ async function askEach<T>(method: (dependency: ReviewedDependency) => Promise<T>, dependencies: Map<string, ReviewedDependency>, what: string): Promise<Map<string, T>> {
137
+ const told = new Map<string, T>()
130
138
  const pending = [...dependencies]
131
- const kept = answers.get(lookup) ?? answers.set(lookup, lru(100_000)).get(lookup)!
139
+ const kept = answers.get(method) ?? answers.set(method, lru(100_000)).get(method)!
132
140
  await Promise.all(Array.from({ length: Math.min(ASK_AT_ONCE, pending.length) }, async () => {
133
141
  for (let next = pending.pop(); next; next = pending.pop()) {
134
142
  const [key, dependency] = next
135
143
  const known = kept.get(key)
136
- let answer = known && Date.now() - known.at < KEPT_MS ? known.reviewed : null
137
- if (answer === null) {
138
- try { answer = await lookup({ ...dependency }) === true } catch (error) {
139
- unasked++
140
- console.warn('reviewed dependencies: failed to answer', `${dependency.name}@${dependency.version}`, error instanceof Error ? error.message : error)
141
- continue
142
- }
143
- kept.set(key, { at: Date.now(), reviewed: answer })
144
+ if (known && Date.now() - known.at < KEPT_MS) { told.set(key, known.value as T); continue }
145
+ try {
146
+ const value = await method({ ...dependency })
147
+ kept.set(key, { at: Date.now(), value })
148
+ told.set(key, value)
149
+ } catch (error) {
150
+ console.warn(`reviewed dependencies: failed to ${what}`, `${dependency.name}@${dependency.version}`, error instanceof Error ? error.message : error)
144
151
  }
145
- if (answer) passed.add(key)
146
152
  }
147
153
  }))
148
- return { passed, unasked }
154
+ return told
155
+ }
156
+
157
+ // Which of `dependencies`, by their keys, `lookup` passes, and how many it
158
+ // failed to answer.
159
+ export async function askReviewed(lookup: ReviewedDependencies['lookup'], dependencies: Map<string, ReviewedDependency>): Promise<{ passed: Set<string>; unasked: number }> {
160
+ const told = await askEach(lookup, dependencies, 'answer')
161
+ return { passed: new Set([...told].flatMap(([key, reviewed]) => reviewed === true ? [key] : [])), unasked: dependencies.size - told.size }
162
+ }
163
+
164
+ // The version `base` names to review each of `dependencies` against, by
165
+ // their keys: none where it names no exact version of an npm package.
166
+ export async function askBases(base: NonNullable<ReviewedDependencies['base']>, dependencies: Map<string, ReviewedDependency>): Promise<Map<string, ReviewedBase>> {
167
+ return new Map([...await askEach(base, dependencies, 'name a base')].flatMap(([key, one]) => isNpmPackageName(one?.name) && typeof one?.version === 'string'
168
+ && isExactVersion(one.version) ? [[key, { name: one.name, version: one.version }] as const] : []))
149
169
  }
@@ -122,11 +122,12 @@ export function stasisDependencyReader({ store, build, behind, stopping }: Reade
122
122
  // which can't be reviewed. Where a build is still to be made, that it is
123
123
  // (`stasis-pending`); where the head's failed, or GitHub failed the base's,
124
124
  // why (`stasis-failed`). A base that couldn't be built of its own, as one of
125
- // no such file, reaches nothing, so every version at the head is new.
125
+ // no such file, reaches nothing, so every version at the head is new, as
126
+ // where it is read without its base (`baseless`), which isn't built then.
126
127
  export async function stasisDirectory(config: string, base: string | null, head: string, read: (commit: string) => Promise<StasisRead>,
127
- locked: (commit: string, held: (path: string) => boolean) => Promise<CommitLockfiles>): Promise<DirectoryDependencies> {
128
+ locked: (commit: string, held: (path: string) => boolean) => Promise<CommitLockfiles>, baseless = false): Promise<DirectoryDependencies> {
128
129
  const paths = [config]
129
- const [after, before] = await Promise.all([read(head), base === null || base === head ? null : read(base)])
130
+ const [after, before] = await Promise.all([read(head), baseless || base === null || base === head ? null : read(base)])
130
131
  if (after.status === 'failed') return { paths, error: 'stasis-failed', detail: after.error }
131
132
  if (before?.status === 'failed' && before.transient) return { paths, error: 'stasis-failed', detail: before.error }
132
133
  if (after.status === 'pending' || before?.status === 'pending') return { paths, error: 'stasis-pending' }
@@ -135,7 +136,7 @@ export async function stasisDirectory(config: string, base: string | null, head:
135
136
  return [...found.locked, ...found.unlocked.map(({ name, version }): LockedPackage => ({ name, version, source: 'registry', unlocked: true }))]
136
137
  }
137
138
  const [now, was] = await Promise.all([lockedAt(head, after.dependencies), before?.status === 'ready' ? lockedAt(base!, before.dependencies) : []])
138
- return addedBetween(paths, before === null ? now : was, now)
139
+ return addedBetween(paths, baseless ? [] : before === null ? now : was, now)
139
140
  }
140
141
 
141
142
  // `answer`, a review's dependencies, each version its package manager alone
package/server.ts CHANGED
@@ -10,7 +10,7 @@ import { startServer } from './server-common/standalone.ts'
10
10
  // reviews as a comment to copy (`formatDependencyReviews`). They replace a
11
11
  // repository's commit its dependencies are reviewed since.
12
12
  export { registerReviewedDependencies } from './server-managed/reviewed-dependencies.ts'
13
- export type { CommentReview, DependencyReviewEntry, FormatDependencyReviewsInput, ParseCommentsInput, ReviewComment, ReviewedDependencies, ReviewedDependency,
13
+ export type { CommentReview, DependencyReviewEntry, FormatDependencyReviewsInput, ParseCommentsInput, ReviewComment, ReviewedBase, ReviewedDependencies, ReviewedDependency,
14
14
  ReviewedLockfile, ReviewedVersion, ReviewVerdict } from './server-managed/reviewed-dependencies.ts'
15
15
 
16
16
  const modes = ['e2e', 'managed', 'managed-e2e', 'e2e-managed'] as const