@preventive/triage 1.0.0-alpha.44 → 1.0.0-alpha.45

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 (183) hide show
  1. package/common/bundle-sources.js +20 -1
  2. package/common/default-scan-models.ts +1 -1
  3. package/common/dependency-reviews.d.ts +0 -5
  4. package/common/dependency-reviews.js +0 -17
  5. package/common/managed/agent-tasks.ts +292 -0
  6. package/common/managed/github-agents.ts +92 -0
  7. package/common/managed/github-logins.ts +49 -0
  8. package/common/managed/roles.ts +7 -0
  9. package/common/managed/routes.js +88 -7
  10. package/common/managed/team-app.d.ts +5 -2
  11. package/common/managed/team-app.js +2 -2
  12. package/common/server-info.ts +3 -0
  13. package/common/workspace-app.js +6 -3
  14. package/out/brotli-fallback.js +3 -3
  15. package/out/chunk-2XUEZHIP.js +18 -18
  16. package/out/chunk-2ZDZWLFY.js +1 -0
  17. package/out/chunk-3PS4KWD2.js +10 -0
  18. package/out/chunk-5DHL5NG3.js +2 -0
  19. package/out/chunk-6HNXNIQY.js +52 -0
  20. package/out/chunk-7C7DWL7I.js +1 -0
  21. package/out/chunk-AFLZH7WG.js +1 -0
  22. package/out/chunk-BC2UCLFJ.js +1 -0
  23. package/out/chunk-C4Z6ZBXV.js +6 -6
  24. package/out/chunk-GDPCLSOS.js +2 -0
  25. package/out/chunk-GO7FT4OD.js +1 -0
  26. package/out/chunk-HMAJDVXN.js +1 -0
  27. package/out/chunk-I2MDGSQX.js +3 -0
  28. package/out/chunk-IYPY47MC.js +1 -0
  29. package/out/chunk-IZ7POWI3.js +18 -0
  30. package/out/chunk-JCIIBLKR.js +1 -1
  31. package/out/chunk-NPW52BM2.js +17 -0
  32. package/out/chunk-NRPC74AM.js +1 -1
  33. package/out/chunk-NV7ES4EW.js +1 -0
  34. package/out/chunk-OKRLLE5I.js +17 -0
  35. package/out/chunk-OOJM4CTU.js +1 -1
  36. package/out/chunk-PNHBZGDD.js +1 -1
  37. package/out/chunk-PTGDYLNS.js +36 -0
  38. package/out/chunk-PXK7EU4V.js +1 -0
  39. package/out/chunk-Q6MVYGYV.js +3 -0
  40. package/out/chunk-QB4CBOX2.js +1 -0
  41. package/out/chunk-QRD6GIG5.js +229 -0
  42. package/out/chunk-R3NZFXVR.js +1 -0
  43. package/out/chunk-R5O6FAW4.js +1 -1
  44. package/out/chunk-SXV2T5C4.js +80 -0
  45. package/out/chunk-TUII34K2.js +1 -1
  46. package/out/chunk-VFWMQ3LG.js +2 -0
  47. package/out/chunk-VH4XMZIW.js +2 -0
  48. package/out/chunk-WFYLMF6Z.js +10 -0
  49. package/out/chunk-WI7Z5A2T.js +6 -0
  50. package/out/chunk-WQ74ZBZF.js +7 -0
  51. package/out/chunk-XVBEOGOS.js +3 -0
  52. package/out/client-managed-import.js +3 -3
  53. package/out/client-managed.js +31 -35
  54. package/out/client-sync.js +11 -11
  55. package/out/compare.js +35 -0
  56. package/out/dialogs.js +51 -0
  57. package/out/github-issue-authorized.html +1 -1
  58. package/out/github-issue-authorized.js +1 -1
  59. package/out/graph.js +17 -17
  60. package/out/index.html +30 -34
  61. package/out/prism.js +14 -14
  62. package/out/scan.js +2 -0
  63. package/out/terminal.js +294 -293
  64. package/out/view.css +1 -1
  65. package/out/view.js +16 -107
  66. package/package.json +51 -6
  67. package/risk/actions/findings.js +156 -0
  68. package/risk/actions/resolve.js +219 -0
  69. package/risk/actions/scripts/commands.js +182 -0
  70. package/risk/actions/scripts/grade.js +113 -0
  71. package/risk/actions/scripts/packages.js +123 -0
  72. package/risk/actions/scripts/shell.js +165 -0
  73. package/risk/actions/uses.js +76 -0
  74. package/risk/actions/workflow.js +110 -0
  75. package/risk/files/hosts.js +6 -6
  76. package/risk/files/readability.js +23 -17
  77. package/risk/files/runs-code.js +18 -6
  78. package/risk/files/script.js +7 -3
  79. package/risk/files/stamps.js +8 -7
  80. package/risk/index.d.ts +68 -1
  81. package/risk/index.js +6 -2
  82. package/risk/npm/assess.js +1 -1
  83. package/risk/npm/compare.js +34 -10
  84. package/risk/npm/files.js +413 -2
  85. package/risk/npm/tarball.js +56 -73
  86. package/server-managed/agent-merges.ts +198 -0
  87. package/server-managed/app-agents.ts +30 -0
  88. package/server-managed/avatar-store.ts +1 -0
  89. package/server-managed/commit-coauthors.ts +83 -0
  90. package/server-managed/commit-lockfiles.ts +62 -0
  91. package/server-managed/db-methods.ts +29 -10
  92. package/server-managed/db-neon.ts +30 -2
  93. package/server-managed/db-schema.ts +9 -2
  94. package/server-managed/db.ts +7 -0
  95. package/server-managed/dependabot-access.ts +60 -0
  96. package/server-managed/dependabot-alerts.ts +185 -0
  97. package/server-managed/dependency-review-comments.ts +97 -0
  98. package/server-managed/dependency-reviews.ts +65 -15
  99. package/server-managed/github-accounts.ts +33 -0
  100. package/server-managed/github-actions.ts +71 -0
  101. package/server-managed/github-app.ts +23 -9
  102. package/server-managed/github-errors.ts +2 -0
  103. package/server-managed/github-link-oauth.ts +69 -0
  104. package/server-managed/github-links.ts +204 -0
  105. package/server-managed/github-oauth.ts +5 -2
  106. package/server-managed/github-users.ts +30 -0
  107. package/server-managed/http.ts +1122 -52
  108. package/server-managed/index.ts +6 -2
  109. package/server-managed/locked-packages.ts +37 -16
  110. package/server-managed/lockfile-scope.ts +49 -0
  111. package/server-managed/npm-delta-worker.js +23 -0
  112. package/server-managed/npm-delta.ts +173 -0
  113. package/server-managed/npm-insights.ts +20 -11
  114. package/server-managed/npm-kept.ts +51 -4
  115. package/server-managed/npm-loads.ts +20 -13
  116. package/server-managed/npm-packages.ts +24 -64
  117. package/server-managed/pull-comment-reviews.ts +161 -0
  118. package/server-managed/pull-dependencies.ts +280 -0
  119. package/server-managed/pull-dependency-reviews.ts +318 -0
  120. package/server-managed/pull-reviews.ts +205 -0
  121. package/server-managed/release-commits.ts +84 -0
  122. package/server-managed/repository-actions.ts +209 -0
  123. package/server-managed/repository-agents.ts +220 -0
  124. package/server-managed/repository-browser.ts +54 -13
  125. package/server-managed/repository-changes.ts +284 -0
  126. package/server-managed/repository-code.ts +52 -0
  127. package/server-managed/repository-dependency-reviews.ts +135 -0
  128. package/server-managed/repository-history.ts +445 -0
  129. package/server-managed/repository-issues.ts +181 -0
  130. package/server-managed/repository-pulse.ts +432 -0
  131. package/server-managed/repository-risk-read.ts +165 -0
  132. package/server-managed/repository-risk.ts +113 -105
  133. package/server-managed/reviewed-dependencies.ts +149 -0
  134. package/server-managed/session.ts +9 -5
  135. package/server-managed/sql.ts +1 -1
  136. package/server-managed/storage-stores.ts +5 -0
  137. package/server-managed/team-app.ts +19 -3
  138. package/server-managed/workspace-shares.ts +4 -1
  139. package/server.ts +11 -0
  140. package/out/chunk-2ABLKCOY.js +0 -46
  141. package/out/chunk-2KBF5TZ7.js +0 -2
  142. package/out/chunk-35VE6CDH.js +0 -2
  143. package/out/chunk-3BZ7JERB.js +0 -1
  144. package/out/chunk-4XCDFGDP.js +0 -10
  145. package/out/chunk-5LSXOLUS.js +0 -1
  146. package/out/chunk-5RCM2J63.js +0 -1
  147. package/out/chunk-7B6HB4D7.js +0 -1
  148. package/out/chunk-AJ4GTATZ.js +0 -3
  149. package/out/chunk-CH4UN6WK.js +0 -225
  150. package/out/chunk-CMQA4DM6.js +0 -1
  151. package/out/chunk-CVVJAXVY.js +0 -2
  152. package/out/chunk-DIJJNTRH.js +0 -10
  153. package/out/chunk-EDKLBQQN.js +0 -17
  154. package/out/chunk-F47DXCEV.js +0 -33
  155. package/out/chunk-FK3DZEKL.js +0 -1
  156. package/out/chunk-G6AJWENO.js +0 -1
  157. package/out/chunk-GJ4IUCNS.js +0 -1
  158. package/out/chunk-GNXOKIGP.js +0 -80
  159. package/out/chunk-GZ4MS3TE.js +0 -13
  160. package/out/chunk-GZWM7UQM.js +0 -2
  161. package/out/chunk-IU3CCINR.js +0 -3
  162. package/out/chunk-K3X5EJBQ.js +0 -2
  163. package/out/chunk-KEX2ATEW.js +0 -2
  164. package/out/chunk-KYCNJVB7.js +0 -1
  165. package/out/chunk-LPCTJYNA.js +0 -7
  166. package/out/chunk-O4RJY5TP.js +0 -2
  167. package/out/chunk-OD4LPN3H.js +0 -1
  168. package/out/chunk-QWDWTBM7.js +0 -1
  169. package/out/chunk-QYWKC557.js +0 -1
  170. package/out/chunk-R75XOKUP.js +0 -1
  171. package/out/chunk-SWTLADW5.js +0 -1
  172. package/out/chunk-T7OKH4VW.js +0 -1
  173. package/out/chunk-TZ5KB2Y5.js +0 -10
  174. package/out/chunk-UNTRGE26.js +0 -2
  175. package/out/chunk-UTR2LVME.js +0 -2
  176. package/out/chunk-UYAXVRVL.js +0 -1
  177. package/out/chunk-V3ME6FI5.js +0 -2
  178. package/out/chunk-V5O7M2YT.js +0 -1
  179. package/out/chunk-VIHGO77Y.js +0 -1
  180. package/out/chunk-W4J3MGLB.js +0 -1
  181. package/out/chunk-WGG7KQUH.js +0 -1
  182. package/out/chunk-XYFXXB2G.js +0 -10
  183. package/out/chunk-ZESLQCTF.js +0 -6
@@ -0,0 +1,318 @@
1
+ // What an open pull request's lockfiles' versions want of review, in a
2
+ // repository that reviews dependencies (repository-dependency-reviews.ts), as
3
+ // its tile and popup show it: each version it adds, whether it passes, by as
4
+ // many reviewers' reviews as the repository requires (`reviews`) or by the
5
+ // reviewed dependencies the host registers (`reviewed`,
6
+ // reviewed-dependencies.ts), or needs none, being among those the
7
+ // repository's lockfiles locked at the commit it is reviewed since
8
+ // (`baseline`); apart from them, the other versions its lockfiles lock that
9
+ // neither passes nor needs none (`unreviewed`); and those that can't be
10
+ // reviewed (`unsupported`), which fail its review, as a lockfile it changes
11
+ // that isn't read does. Without that commit, every version wants its
12
+ // reviews; registered reviewed dependencies replace it.
13
+ //
14
+ // A version is reviewed as npm's registry has it, by its name, version and
15
+ // integrity: one locked of npm's registry, by its name or its link to its
16
+ // tarball (locked-packages.ts), with an integrity. One from git, another
17
+ // tarball (a mirror's too), or with no integrity can't be; a file of the
18
+ // project's isn't. Its reviews are those of it, of an integrity it is locked
19
+ // with, either whole, or compared with a version of its package: for a
20
+ // version the pull request adds, one it was; for another, any. A patched one
21
+ // (`patched`) passes by none of them, the app reviewing no patch yet: only
22
+ // by the reviewed dependencies, or locked so, its patch too, at that commit.
23
+ // Which versions the repository's lockfiles locked at that commit never
24
+ // changes: it is read once, every lockfile there of those read here
25
+ // (pull-dependencies.ts), and kept by the commit (`baselines` in this
26
+ // instance, `kept` beyond it), never stored as reviews.
27
+ import { lockedAt, lockedIn } from './commit-lockfiles.ts'
28
+ import { GithubApiError } from './github-app.ts'
29
+ import type { LockedPackage } from './locked-packages.ts'
30
+ import { EVERY_LOCKFILE, type LockfileScope, heldTo, isEvery, reviewedIn } from './lockfile-scope.ts'
31
+ import { type Lru, lru } from './lru.ts'
32
+ import { type DirectoryDependencies, MAX_ADDED, type PullDependencies, lockedAs, lockedWith } from './pull-dependencies.ts'
33
+ import type { PublishedReview, RepoReviewState } from './repository-dependency-reviews.ts'
34
+ import { type ReviewedDependencies, type ReviewedDependency, askReviewed } from './reviewed-dependencies.ts'
35
+
36
+ // The other versions told unreviewed, and those told unsupported, of each
37
+ // directory, those past them counted.
38
+ export const MAX_UNREVIEWED = 200
39
+
40
+ // The versions a commit's lockfiles lock, and the lockfiles there that
41
+ // couldn't be read (`unread`), whose versions want reviews all the same.
42
+ export interface Baseline { versions: Set<string>; unread: string[] }
43
+ export interface ReviewBaselineStore {
44
+ read(key: string): Promise<{ versions: string[]; unread: string[] } | null>
45
+ write(key: string, value: { versions: string[]; unread: string[] }): Promise<void>
46
+ }
47
+ const baselines: Lru<Baseline> = lru(500_000, baseline => baseline.versions.size + baseline.unread.length + 1)
48
+
49
+ // Why a version can't be reviewed: from git, of a tarball not npm's
50
+ // registry's of its version, or locked with no integrity.
51
+ export type Unsupported = 'git' | 'tarball' | 'integrity'
52
+ // How a version is reviewed: by its name, version and integrity
53
+ // (`version`), not at all (`skip`), or why it can't be.
54
+ function reviewedAs(pkg: LockedPackage): 'version' | 'skip' | Unsupported {
55
+ if (pkg.source === 'file') return 'skip'
56
+ if (pkg.source === 'git') return 'git'
57
+ if (pkg.source !== 'registry' || pkg.version === null) return 'tarball'
58
+ return pkg.integrity ? 'version' : 'integrity'
59
+ }
60
+ // The hashes an integrity names, each of which is npm's of it.
61
+ const hashesOf = (pkg: LockedPackage) => (pkg.integrity ?? '').split(/\s+/u).filter(Boolean)
62
+ // A version as a baseline holds it: its name and version with each hash,
63
+ // and its patch.
64
+ const baselineKeys = (pkg: LockedPackage) => hashesOf(pkg).map(hash => `${pkg.name}@${pkg.version ?? ''}\0${hash}\0${pkg.patchHash ?? ''}`)
65
+
66
+ // The versions the repository's lockfiles locked at commit `since` that are
67
+ // reviewed (reviewedAs), as kept, else read of GitHub (commit-lockfiles.ts)
68
+ // and kept; with the lockfiles there its reader refuses, isn't one of, or
69
+ // past those read (`unread`). GitHub having none of a lockfile it lists
70
+ // there is a failure of the whole, as of any file, never kept.
71
+ export async function reviewBaseline(fullName: string, token: string, repoId: number, since: string, kept: ReviewBaselineStore): Promise<Baseline> {
72
+ const key = `${repoId}\0${since}`
73
+ const known = baselines.get(key)
74
+ if (known) return known
75
+ const stored = await kept.read(key)
76
+ if (stored) { const baseline = { versions: new Set(stored.versions), unread: stored.unread }; baselines.set(key, baseline); return baseline }
77
+ const read = await lockedAt(fullName, token, since)
78
+ const { packages } = lockedIn(read), { unread } = read
79
+ const versions = new Set<string>()
80
+ for (const pkg of packages) if (reviewedAs(pkg) === 'version') for (const held of baselineKeys(pkg)) versions.add(held)
81
+ const baseline = { versions, unread }
82
+ baselines.set(key, baseline)
83
+ await kept.write(key, { versions: [...versions], unread: baseline.unread })
84
+ return baseline
85
+ }
86
+
87
+ // Passing reviews by the version they are of, its name and version.
88
+ type ReviewsOf = Map<string, PublishedReview[]>
89
+ function reviewsByVersion(reviews: PublishedReview[]): ReviewsOf {
90
+ const by: ReviewsOf = new Map()
91
+ for (const review of reviews) {
92
+ const key = `${review.package}@${review.version}`
93
+ const held = by.get(key)
94
+ if (held) held.push(review)
95
+ else by.set(key, [review])
96
+ }
97
+ return by
98
+ }
99
+
100
+ const ACCEPTING = new Set(['accept', 'accept-with-nits'])
101
+ // Where `pkg`'s reviewers stand on it among `reviews`, those of its version,
102
+ // of an integrity it is locked with, and of its patch: each one's latest
103
+ // telling it, any rejecting it holding it unreviewed (`rejected`); those
104
+ // accepting it passing it (`passing`), each once, by a full, accepting
105
+ // review of theirs, whole or compared with one of `bases` of its package
106
+ // (any, for `any`); and how many review it in its pull request's comments
107
+ // alone (`commented`), which count for it alone: whose reviews passing it,
108
+ // else whose latest, are its comments'.
109
+ function stancesOf(pkg: LockedPackage, reviews: ReviewsOf, bases: string[] | 'any') {
110
+ const hashes = hashesOf(pkg)
111
+ const by = new Map<string, PublishedReview[]>()
112
+ for (const review of reviews.get(`${pkg.name}@${pkg.version}`) ?? []) {
113
+ if (!hashes.includes(review.integrity) || (review.patchHash ?? '') !== (pkg.patchHash ?? '')) continue
114
+ by.set(review.reviewer, [...by.get(review.reviewer) ?? [], review])
115
+ }
116
+ const qualifies = (review: PublishedReview) => review.full && ACCEPTING.has(review.status)
117
+ && (review.basePackage === null || (review.basePackage === pkg.name && (bases === 'any' || bases.includes(review.baseVersion ?? ''))))
118
+ let commented = 0, passing = 0, rejected = false
119
+ for (const theirs of by.values()) {
120
+ const latest = theirs.reduce((one, other) => other.time > one.time ? other : one)
121
+ // In its comments alone where those telling where they stand are: those
122
+ // passing it, where they pass it, else their latest.
123
+ const telling = ACCEPTING.has(latest.status) && theirs.some(qualifies) ? theirs.filter(qualifies) : [latest]
124
+ if (telling.every(review => review.comment)) commented++
125
+ if (latest.status === 'reject') rejected = true
126
+ else if (ACCEPTING.has(latest.status) && theirs.some(qualifies)) passing++
127
+ }
128
+ return { passing, rejected, commented }
129
+ }
130
+
131
+ // A version as the client is told it: what its reviews are held to left
132
+ // out, but whether it is patched.
133
+ function shown<T extends LockedPackage>(pkg: T): Omit<T, 'integrity' | 'shasum' | 'patchHash' | 'lockfile'> & { patched?: true } {
134
+ const copy = { ...pkg }
135
+ for (const field of ['integrity', 'shasum', 'patchHash', 'lockfile'] as const) delete copy[field]
136
+ return { ...copy, ...pkg.patchHash ? { patched: true as const } : {} }
137
+ }
138
+
139
+ // A version as the registered reviewed dependencies are asked of it, by
140
+ // what it is asked.
141
+ function askedOf(pkg: LockedPackage): [string, ReviewedDependency] {
142
+ const dependency: ReviewedDependency = { ecosystem: 'npm', lockfile: pkg.lockfile ?? 'npm', name: pkg.name, version: pkg.version ?? '', integrity: pkg.integrity ?? '',
143
+ ...pkg.shasum ? { shasum: pkg.shasum } : {}, ...pkg.patchHash ? { patchHash: pkg.patchHash } : {} }
144
+ return [JSON.stringify(dependency), dependency]
145
+ }
146
+
147
+ // A version's review, and whether it wants one (`wants`), neither passing
148
+ // nor needing none, as only one that can be reviewed may.
149
+ type Review = { unsupported: Unsupported } | { baseline: true } | { reviewed: true } | { reviews: number; rejected?: true; commented?: number } | Record<string, never>
150
+ interface Judged { review: Review; wants: boolean }
151
+ type Judge = (pkg: LockedPackage, bases: string[] | 'any') => Judged
152
+ interface Context { state: RepoReviewState; reviews: ReviewsOf; baseline: Set<string> | null }
153
+ function judge(pkg: LockedPackage, bases: string[] | 'any', { state, reviews, baseline }: Context): Judged {
154
+ const as = reviewedAs(pkg)
155
+ if (as === 'skip') return { review: {}, wants: false }
156
+ if (as !== 'version') return { review: { unsupported: as }, wants: false }
157
+ if (baselineKeys(pkg).some(key => baseline?.has(key))) return { review: { baseline: true }, wants: false }
158
+ const { passing, rejected, commented } = stancesOf(pkg, reviews, bases)
159
+ const told = { reviews: passing, ...commented > 0 ? { commented } : {} }
160
+ if (rejected) return { review: { ...told, rejected: true }, wants: true }
161
+ return { review: told, wants: passing < state.required }
162
+ }
163
+
164
+ // A directory as the client is told it: what it adds, as many as MAX_ADDED,
165
+ // each version with its review (`review`, as judged), those past them judged
166
+ // as they are, against the versions they were, as is every one its lockfiles
167
+ // lock of them (another integrity of it, say), each told by the least passing
168
+ // of them, and those of all that want one (`toReview`); the others its lockfiles lock that want reviews, and every one
169
+ // that can't be reviewed (as many of each as MAX_UNREVIEWED, how many more,
170
+ // once `capped`); and how many it locks past those read (`moreLocked`), which
171
+ // aren't checked; without `review`, what it adds alone.
172
+ function reviewedDirectory(dir: DirectoryDependencies, review: Judge | null) {
173
+ if ('error' in dir) return dir
174
+ const { locked, moreLocked, added, ...told } = dir
175
+ if (!review) return { ...told, added: added.slice(0, MAX_ADDED).map(shown) }
176
+ const adds = new Map(added.map(pkg => [lockedAs(pkg), { pkg, variants: [pkg] }]))
177
+ for (const pkg of locked) {
178
+ const of = adds.get(lockedAs(pkg))
179
+ if (of && lockedWith(pkg) !== lockedWith(of.pkg)) of.variants.push(pkg)
180
+ }
181
+ const own = [...adds.values()].map(({ pkg, variants }) => {
182
+ const judged = variants.map(variant => ({ variant, ...review(variant, pkg.was ?? []) }))
183
+ const least = judged.find(one => 'unsupported' in one.review) ?? judged.find(one => one.wants) ?? judged[0]!
184
+ return { pkg, judged: least, wanting: judged.filter(one => one.wants).map(({ variant }) => variant) }
185
+ })
186
+ const others = locked.filter(pkg => !adds.has(lockedAs(pkg))).map(pkg => ({ pkg, judged: review(pkg, 'any') }))
187
+ const unsupported = locked.flatMap(pkg => { const as = reviewedAs(pkg); return as === 'version' || as === 'skip' ? [] : [{ ...shown(pkg), unsupported: as }] })
188
+ return { ...told, added: own.slice(0, MAX_ADDED).map(({ pkg, judged }) => ({ ...shown(pkg), ...judged.review })),
189
+ toReview: own.flatMap(({ wanting }) => wanting.map(shown)),
190
+ unreviewed: others.filter(({ judged }) => judged.wants).map(({ pkg, judged }) => ({ ...shown(pkg), ...judged.review })), unsupported, moreLocked }
191
+ }
192
+ function capped<T extends { toReview: unknown[]; unreviewed: unknown[]; unsupported: unknown[] }>({ toReview: _toReview, ...dir }: T) {
193
+ return { ...dir, unreviewed: dir.unreviewed.slice(0, MAX_UNREVIEWED), moreUnreviewed: Math.max(0, dir.unreviewed.length - MAX_UNREVIEWED),
194
+ unsupported: dir.unsupported.slice(0, MAX_UNREVIEWED), moreUnsupported: Math.max(0, dir.unsupported.length - MAX_UNREVIEWED) }
195
+ }
196
+ // How many versions of `lists` there are, each once across them, by `key`,
197
+ // as the client tells them once: one wanting reviews by its name and
198
+ // version, one that can't be reviewed by where it is from too.
199
+ type Shown = Pick<LockedPackage, 'name' | 'version' | 'source' | 'from'>
200
+ const distinct = (lists: Shown[][], key: (pkg: Shown) => string) => new Set(lists.flat().map(key)).size
201
+ const versionKey = (pkg: Shown) => `${pkg.name}@${pkg.version ?? ''}`
202
+ const sourceKey = (pkg: Shown) => `${pkg.source}\0${versionKey(pkg)}\0${pkg.from ?? ''}`
203
+
204
+ // The reviews an open pull request's comments make of `wanting`, the
205
+ // versions still wanting one (pull-comment-reviews.ts): those that count,
206
+ // and whether they couldn't be read.
207
+ export type CommentReviews = (wanting: ReviewedDependency[]) => Promise<{ reviews: PublishedReview[]; failed: boolean }>
208
+
209
+ // What a pull request's lockfiles lock, but in directories none of whose
210
+ // lockfiles `scope` holds to, as they aren't reviewed: left out, as lockfiles
211
+ // left unread are where it holds to none of them (`omitted`, told to none).
212
+ export function heldDependencies<T extends PullDependencies>(told: T, scope: LockfileScope): Omit<T, 'omitted'> {
213
+ const { omitted, ...answered } = told
214
+ if (isEvery(scope)) return answered
215
+ return { ...answered, cut: told.cut && !(omitted && !omitted.some(path => heldTo(scope, path))), lockfiles: told.lockfiles.filter(dir => reviewedIn(scope, dir.paths)) }
216
+ }
217
+
218
+ // A pull request's dependencies as the client is told them: without the
219
+ // versions its directories lock; with `state`, a repository's review in
220
+ // effect, each version's review (reviewedDirectory), those wanting one asked
221
+ // of the registered reviewed dependencies (`reviewed`), and those still
222
+ // wanting one of the reviews its comments make (`commentReviews`, where the
223
+ // host reads them), and the review's terms (`review`), with how many
224
+ // reviewers' its comments count (`commentReviews`), or that they couldn't be
225
+ // read (`commentsFailed`), and how many versions across its directories want
226
+ // reviews, of those it adds (`toReview`) and the rest (`unreviewed`), and
227
+ // can't be reviewed (`unsupported`), each once; how many the reviewed dependencies failed to
228
+ // answer (`unasked`), and whether they are registered (`reviewedDependencies`,
229
+ // the commit reviewed since then none); and where the baseline couldn't be
230
+ // read, why (`baselineError`), every version then wanting its reviews, or
231
+ // the lockfiles there left unread (`baselineUnread`), whose versions do. It
232
+ // fails where a version can't be reviewed, a directory's lockfiles couldn't
233
+ // be read or lock more than are checked, or the pull request changes more
234
+ // lockfiles than are read (`cut`). Those of directories none of whose
235
+ // lockfiles the review holds to (`lockfiles`, lockfile-scope.ts, told in its
236
+ // terms where not every one) are left out (heldDependencies).
237
+ export async function reviewedDependencies(told: PullDependencies, state: RepoReviewState | null,
238
+ { baseline = null, baselineUnread = [], baselineError = null, reviewed = null, commentReviews = null }: { baseline?: Set<string> | null; baselineUnread?: string[]
239
+ baselineError?: string | null; reviewed?: ReviewedDependencies | null; commentReviews?: CommentReviews | null } = {}) {
240
+ const scope = state?.lockfiles ?? EVERY_LOCKFILE
241
+ const answered = heldDependencies(told, scope)
242
+ if (!state) return { ...answered, lockfiles: answered.lockfiles.map(dir => reviewedDirectory(dir, null)) }
243
+ const { cut, lockfiles: held } = answered
244
+ let context = { state, reviews: reviewsByVersion(state.reviews), baseline: reviewed ? null : baseline }
245
+ // What wants a review, as `lookup` is asked of, each once.
246
+ const wanting = () => {
247
+ const asked = new Map<string, ReviewedDependency>()
248
+ const asking: Judge = (pkg, bases) => {
249
+ const judged = judge(pkg, bases, context)
250
+ if (judged.wants) asked.set(...askedOf(pkg))
251
+ return judged
252
+ }
253
+ for (const dir of held) reviewedDirectory(dir, asking)
254
+ return asked
255
+ }
256
+ const passed = new Set<string>()
257
+ let unasked = 0
258
+ const ask = async (asked: Map<string, ReviewedDependency>) => {
259
+ const answer = asked.size > 0 && reviewed ? await askReviewed(reviewed.lookup, asked) : { passed: new Set<string>(), unasked: 0 }
260
+ for (const key of answer.passed) passed.add(key)
261
+ unasked += answer.unasked
262
+ }
263
+ const asked = wanting()
264
+ await ask(asked)
265
+ // Of those still wanting one, and every other one the lockfiles it holds
266
+ // to add that its teams' reviews pass, telling other pull requests those
267
+ // it reviews (`commented`), but those `lookup` passes, reviewed, the
268
+ // reviews its comments make, an open one's alone (pull-comment-reviews.ts),
269
+ // which count as its teams' do; those their rejects hold asked of `lookup`
270
+ // too.
271
+ const parsing = new Map([...asked].filter(([key]) => !passed.has(key)))
272
+ if (commentReviews) {
273
+ const others = new Map<string, ReviewedDependency>()
274
+ for (const pkg of held.flatMap(dir => 'added' in dir ? dir.added : [])) {
275
+ const [key, dependency] = askedOf(pkg)
276
+ if (!asked.has(key) && 'reviews' in judge(pkg, pkg.was ?? [], context).review) others.set(key, dependency)
277
+ }
278
+ const vouched = others.size > 0 && reviewed ? (await askReviewed(reviewed.lookup, others)).passed : new Set<string>()
279
+ for (const [key, dependency] of others) if (!vouched.has(key)) parsing.set(key, dependency)
280
+ }
281
+ const comments = parsing.size > 0 && commentReviews ? await commentReviews([...parsing.values()]) : { reviews: [], failed: false }
282
+ if (comments.reviews.length > 0) {
283
+ context = { ...context, reviews: reviewsByVersion([...state.reviews, ...comments.reviews.map(review => ({ ...review, comment: true as const }))]) }
284
+ await ask(new Map([...wanting()].filter(([key]) => !asked.has(key))))
285
+ }
286
+ const dirs = held.map(dir => reviewedDirectory(dir, (pkg, bases) => {
287
+ const judged = judge(pkg, bases, context)
288
+ return judged.wants && passed.has(askedOf(pkg)[0]) ? { review: { reviewed: true }, wants: false } : judged
289
+ }))
290
+ const unread = baselineUnread.filter(path => heldTo(scope, path))
291
+ const listed = dirs.flatMap(dir => 'unreviewed' in dir ? [dir] : [])
292
+ return { ...answered, cut, lockfiles: dirs.map(dir => 'unreviewed' in dir ? capped(dir) : dir), review: { required: state.required,
293
+ since: reviewed ? null : state.since, canReview: state.canReview, ...reviewed ? { reviewedDependencies: true } : {},
294
+ toReview: distinct(listed.map(dir => dir.toReview), versionKey), unreviewed: distinct(listed.map(dir => dir.unreviewed), versionKey),
295
+ unsupported: distinct(listed.map(dir => dir.unsupported), sourceKey),
296
+ ...unasked > 0 ? { unasked } : {}, ...baselineError && !reviewed ? { baselineError } : {},
297
+ ...comments.reviews.length > 0 ? { commentReviews: new Set(comments.reviews.map(review => review.reviewer)).size } : {}, ...comments.failed ? { commentsFailed: true } : {},
298
+ ...unread.length > 0 && !reviewed ? { baselineUnread: unread.slice(0, MAX_UNREVIEWED) } : {}, ...isEvery(scope) ? {} : { lockfiles: scope } } }
299
+ }
300
+
301
+ // The packages a pull request's lockfiles lock that its reviews here may
302
+ // pass, whose reviews are asked: those that can be reviewed, unpatched.
303
+ export const reviewedPackages = (told: PullDependencies) => told.lockfiles
304
+ .flatMap(dir => 'error' in dir ? [] : dir.locked.filter(pkg => reviewedAs(pkg) === 'version' && !pkg.patchHash).map(pkg => pkg.name))
305
+
306
+ // A repository's baseline as read for a pull request: its versions and the
307
+ // lockfiles there left unread; none where it reviews since no commit; and
308
+ // where GitHub doesn't read it, none and why.
309
+ export async function baselineFor(fullName: string, token: string, repoId: number, state: RepoReviewState, kept: ReviewBaselineStore) {
310
+ if (!state.since) return { baseline: null, unread: [], error: null }
311
+ try {
312
+ const { versions, unread } = await reviewBaseline(fullName, token, repoId, state.since, kept)
313
+ return { baseline: versions, unread, error: null }
314
+ } catch (err) {
315
+ if (err instanceof GithubApiError && err.status !== 429 && err.status !== 401) return { baseline: null, unread: [], error: err.message }
316
+ throw err
317
+ }
318
+ }
@@ -0,0 +1,205 @@
1
+ // What an open pull request's reviews say, as the code viewer's Pull requests
2
+ // tab and a pull request's popup show it (repository-issues.ts): who
3
+ // reviewed it and how, each by their latest review and the commit it was on,
4
+ // its author's own aside (the replies GitHub makes reviews of in a thread);
5
+ // whose review is requested, and how many more than those read; its review
6
+ // threads open and resolved, the latest read (open ones are, mostly, those
7
+ // lately opened), the gravest open one by the P0–P3 badge Codex marks a
8
+ // finding with; and
9
+ // Codex's own, which it keeps in a comment of its own (its summary, edited in
10
+ // place) rather than in reviews, reviewing only where it finds something:
11
+ // the commit its code review and its security review were last on, either
12
+ // one still running, asked for again since, or failed since. A review an
13
+ // agentic workflow (gh-aw) posted, as GitHub Actions' bot, names its
14
+ // workflow by the marker gh-aw leaves (`<!-- gh-aw-workflow-id: NAME -->`), in
15
+ // the popup, which reads reviews' bodies.
16
+ import { githubAgent } from '../common/managed/github-agents.ts'
17
+ import { ACTOR, type GraphAccount, actorOf } from './github-accounts.ts'
18
+
19
+ const REVIEWERS = 20
20
+ const REQUESTS = 10
21
+ // The threads the Pull requests tab counts, and those a popup lists.
22
+ export const TILE_THREADS = 50
23
+ export const ITEM_THREADS = 100
24
+ // The comments read for Codex's: its summary among the first, posted as the
25
+ // pull request opens, or among the last, where it was first asked later;
26
+ // asking it again, and its failures, among the last.
27
+ const FIRST_COMMENTS = 5
28
+ const LAST_COMMENTS = 20
29
+ const MAX_TITLE = 200
30
+ const MAX_PATH = 1000
31
+ const COMMIT = /^[a-f\d]{40}$/u
32
+
33
+ // The fields a pull request's reviews are read by, its threads' places and
34
+ // links with them for its popup (`detail`). A team requested is no reviewer
35
+ // read, but one of those requested GitHub names no one for: reading a team
36
+ // needs its organization's Members permission, and a query reading one
37
+ // without it fails whole (as one naming an EnterpriseTeam, which GitHub's
38
+ // docs name and its API knows none of, does).
39
+ export const reviewFields = (threads: number, detail: boolean) => `headRefOid
40
+ latestReviews(first: ${REVIEWERS}) { totalCount nodes { author { ${ACTOR} } state submittedAt commit { oid }${detail ? ' body' : ''} } }
41
+ reviewRequests(first: ${REQUESTS}) { totalCount nodes { requestedReviewer { __typename ... on User { login databaseId } ... on Bot { login databaseId }
42
+ ... on Mannequin { login databaseId } } } }
43
+ reviewThreads(last: ${threads}) { totalCount nodes { isResolved isOutdated${detail ? ' path line originalLine' : ''}
44
+ comments(first: 1) { nodes { author { ${ACTOR} } body${detail ? ' url' : ''} } } } }
45
+ firstComments: comments(first: ${FIRST_COMMENTS}) { nodes { author { ${ACTOR} } body updatedAt } }
46
+ lastComments: comments(last: ${LAST_COMMENTS}) { nodes { author { ${ACTOR} } body createdAt updatedAt } }`
47
+
48
+ // The fields read for reviews that GitHub may refuse alone, as it refuses an
49
+ // App a pull request's checks: their pull request then shows no reviews.
50
+ const REVIEW_PATHS = new Set(['latestReviews', 'reviewRequests', 'reviewThreads', 'firstComments', 'lastComments'])
51
+ export const reviewsRefused = (error: { type?: unknown; path?: unknown } | null | undefined) => error?.type === 'FORBIDDEN' && Array.isArray(error.path)
52
+ && error.path.some(part => REVIEW_PATHS.has(part as string))
53
+
54
+ type Comment = { author?: GraphAccount; body?: unknown; updatedAt?: unknown; createdAt?: unknown } | null
55
+ type Thread = { isResolved?: unknown; isOutdated?: unknown; path?: unknown; line?: unknown; originalLine?: unknown
56
+ comments?: { nodes?: (Comment & { url?: unknown })[] } | null } | null
57
+ export type ReviewNode = {
58
+ headRefOid?: unknown
59
+ latestReviews?: { totalCount?: unknown; nodes?: ({ author?: GraphAccount; state?: unknown; submittedAt?: unknown; commit?: { oid?: unknown } | null; body?: unknown } | null)[] } | null
60
+ reviewRequests?: { totalCount?: unknown; nodes?: ({ requestedReviewer?: { __typename?: unknown; login?: unknown; databaseId?: unknown } | null } | null)[] } | null
61
+ reviewThreads?: { totalCount?: unknown; nodes?: Thread[] } | null
62
+ firstComments?: { nodes?: Comment[] } | null
63
+ lastComments?: { nodes?: Comment[] } | null
64
+ }
65
+
66
+ const STATES: Record<string, string> = { APPROVED: 'approved', CHANGES_REQUESTED: 'changes', COMMENTED: 'commented', DISMISSED: 'dismissed' }
67
+ const CODEX_STATES: Record<string, string> = { completed: 'done', running: 'running', queued: 'running', pending: 'running', in_progress: 'running', failed: 'failed', error: 'failed' }
68
+ const SEVERITY = /!\[(P[0-3]) Badge\]/u
69
+ const SUMMARY = /<!--\s*codex-review-state:v1\s+(\{[^]*?\})\s*-->/u
70
+ // Asking it to review again reruns its code review alone, never its security review.
71
+ const ASKED = /^@codex\s+review\b/iu
72
+ const FAILED = /^Codex Review: Something went wrong/u
73
+ const WORKFLOW = /<!--\s*gh-aw-workflow-id:\s*([\w.-]{1,100})\s*-->/u
74
+
75
+ const timeOf = (value: unknown) => {
76
+ const at = typeof value === 'string' ? Date.parse(value) : Number.NaN
77
+ return Number.isSafeInteger(at) ? at : null
78
+ }
79
+ const commitOf = (value: unknown) => typeof value === 'string' && COMMIT.test(value.toLowerCase()) ? value.toLowerCase() : null
80
+ const textOf = (value: unknown) => typeof value === 'string' ? value : ''
81
+ const isCodex = (account: GraphAccount) => {
82
+ const { login, id } = actorOf(account)
83
+ return login !== null && githubAgent(login, id) === 'codex'
84
+ }
85
+
86
+ // A finding's gravity, by its badge, `p0` the gravest; null for none.
87
+ const severityOf = (body: string) => SEVERITY.exec(body.slice(0, 500))?.[1]?.toLowerCase() ?? null
88
+ // A thread's title: its first comment's first line with words, as written,
89
+ // but for Codex's badge and emphasis.
90
+ function titleOf(body: string) {
91
+ for (const line of body.split('\n', 6)) {
92
+ const words = line.replaceAll(/!\[[^\]]*\]\([^)]*\)|<\/?sub>|\*\*|__/gu, '').trim()
93
+ if (words) return words.slice(0, MAX_TITLE)
94
+ }
95
+ return ''
96
+ }
97
+
98
+ // Codex's review of one kind, as its summary names it: the commit it was
99
+ // last on and how it stands.
100
+ function codexReview(value: unknown) {
101
+ const review = value && typeof value === 'object' ? value as { commit_sha?: unknown; status?: unknown } : null
102
+ if (!review) return null
103
+ return { commit: commitOf(review.commit_sha), status: CODEX_STATES[String(review.status)] ?? null }
104
+ }
105
+
106
+ // What Codex's summary says of its reviews, else null.
107
+ function summaryState(body: string): { code_review?: unknown; security_review?: unknown } | null {
108
+ try {
109
+ const value: unknown = JSON.parse(SUMMARY.exec(body)?.[1] ?? 'null')
110
+ return value && typeof value === 'object' ? value : null
111
+ } catch { return null }
112
+ }
113
+
114
+ // Codex's reviews, from its summary, else none: its account, as the summary
115
+ // names it; whether it was asked again since the summary last changed
116
+ // (`@codex review`), and whether it failed since it was last asked.
117
+ function codexOf(node: ReviewNode) {
118
+ const summary = [...node.firstComments?.nodes ?? [], ...node.lastComments?.nodes ?? []]
119
+ .find(comment => comment && isCodex(comment.author) && SUMMARY.test(textOf(comment.body)))
120
+ if (!summary) return null
121
+ const state = summaryState(textOf(summary.body))
122
+ if (!state) return null
123
+ const since = timeOf(summary.updatedAt) ?? 0
124
+ const later = (node.lastComments?.nodes ?? []).filter(comment => comment && (timeOf(comment.createdAt) ?? 0) > since) as NonNullable<Comment>[]
125
+ const at = (comment: NonNullable<Comment> | undefined) => comment ? timeOf(comment.createdAt) ?? 0 : null
126
+ const asked = at(later.findLast(comment => !isCodex(comment.author) && ASKED.test(textOf(comment.body).trim())))
127
+ const failed = at(later.findLast(comment => isCodex(comment.author) && FAILED.test(textOf(comment.body).trim())))
128
+ const { login, id } = actorOf(summary.author)
129
+ return { login, id, code: codexReview(state.code_review), security: codexReview(state.security_review),
130
+ requested: asked !== null && !(failed !== null && failed > asked), failed: failed !== null && (asked === null || failed > asked) }
131
+ }
132
+
133
+ type Reviewer = { login: string | null; id: number | null; workflow?: string; state: string | null; requested: boolean; commit: string | null; at: number | null }
134
+
135
+ // The reviewers, each once: by their latest review, its state and commit;
136
+ // whose is requested (again, for one who reviewed), a user, a bot (Copilot's
137
+ // code review, asked for, is its bot's) or an imported account's mannequin.
138
+ // Codex's reviews are its summary's where it has one (`codex`). How many
139
+ // requested GitHub named no one for, a team among them, as `unnamed`,
140
+ // counted with those past the ones read.
141
+ function reviewersOf(node: ReviewNode, author: string | null, codex: boolean) {
142
+ const own = author?.toLowerCase()
143
+ const reviewers: Reviewer[] = (node.latestReviews?.nodes ?? []).flatMap(review => {
144
+ const { login, id } = actorOf(review?.author)
145
+ const state = STATES[String(review?.state)]
146
+ if (!state || (login !== null && login.toLowerCase() === own) || (codex && isCodex(review?.author))) return []
147
+ const workflow = WORKFLOW.exec(textOf(review?.body))?.[1]
148
+ return [{ login, id, ...workflow ? { workflow } : {}, state, requested: false, commit: commitOf(review?.commit?.oid), at: timeOf(review?.submittedAt) }]
149
+ })
150
+ let unnamed = 0
151
+ for (const request of node.reviewRequests?.nodes ?? []) {
152
+ const reviewer = request?.requestedReviewer
153
+ const { login, id } = actorOf(reviewer)
154
+ if (login === null) {
155
+ unnamed++
156
+ continue
157
+ }
158
+ // By their account where both name it, as GitHub may name one account
159
+ // otherwise on its reviews than on its requests (Copilot's code review's
160
+ // bot); else by their login.
161
+ const reviewed = reviewers.find(item => id !== null && item.id !== null ? item.id === id : item.login?.toLowerCase() === login.toLowerCase())
162
+ if (reviewed) reviewed.requested = true
163
+ else reviewers.push({ login, id, state: null, requested: true, commit: null, at: null })
164
+ }
165
+ return { reviewers, unnamed }
166
+ }
167
+
168
+ // Its review threads, the latest read: how many are open and resolved,
169
+ // whether more than those read are, the gravest open one; and, for its popup (`detail`), each
170
+ // open one: its gravity, title, file and line, whether its code changed
171
+ // since, who opened it and where it is on GitHub.
172
+ function threadsOf(node: ReviewNode, detail: boolean) {
173
+ const threads = (node.reviewThreads?.nodes ?? []).filter(Boolean) as NonNullable<Thread>[]
174
+ const open = threads.filter(thread => thread.isResolved !== true)
175
+ const severities = open.map(thread => severityOf(textOf(thread.comments?.nodes?.[0]?.body))).filter(Boolean) as string[]
176
+ const total = node.reviewThreads?.totalCount
177
+ const counted = { open: open.length, resolved: threads.length - open.length,
178
+ more: Number.isSafeInteger(total) && (total as number) > threads.length, severity: severities.toSorted()[0] ?? null }
179
+ if (!detail) return counted
180
+ return { ...counted, list: open.map(thread => {
181
+ const first = thread.comments?.nodes?.[0]
182
+ const body = textOf(first?.body)
183
+ const opener = actorOf(first?.author)
184
+ const line = Number.isSafeInteger(thread.line) ? thread.line : Number.isSafeInteger(thread.originalLine) ? thread.originalLine : null
185
+ const url = typeof first?.url === 'string' && first.url.startsWith('https://github.com/') ? first.url : null
186
+ return { severity: severityOf(body), title: titleOf(body), path: typeof thread.path === 'string' ? thread.path.slice(0, MAX_PATH) : null, line,
187
+ outdated: thread.isOutdated === true, author: opener.login, authorId: opener.id, url }
188
+ }) }
189
+ }
190
+
191
+ // A pull request's reviews (`author` its author's login), for its tile or,
192
+ // with its threads listed, its popup (`detail`); null where none was read, or
193
+ // GitHub refused its reviews, requests or threads (reviewsRefused), rather
194
+ // than none.
195
+ export function pullReviews(node: ReviewNode, author: string | null, detail = false) {
196
+ if (node.headRefOid === undefined || node.latestReviews === null || node.reviewRequests === null || node.reviewThreads === null) return null
197
+ const codex = codexOf(node)
198
+ // Those past the reviews and the requests read, as many as GitHub counts,
199
+ // apart: a review unread may be on the latest commit, a request never is.
200
+ const past = (connection: { totalCount?: unknown; nodes?: unknown[] } | null | undefined) => Number.isSafeInteger(connection?.totalCount)
201
+ ? Math.max(0, (connection!.totalCount as number) - (connection!.nodes?.length ?? 0)) : 0
202
+ const { reviewers, unnamed } = reviewersOf(node, author, codex !== null)
203
+ return { head: commitOf(node.headRefOid), reviewers, moreReviews: past(node.latestReviews), moreRequests: past(node.reviewRequests) + unnamed,
204
+ threads: threadsOf(node, detail), codex }
205
+ }
@@ -0,0 +1,84 @@
1
+ // The commits that release a repository, for its Pulse (repository-pulse.ts
2
+ // commitStats): one a tag names that changes no code, only package.json
3
+ // files (at least one, in any directory), the lockfiles beside them
4
+ // (RELEASE_LOCKFILES) and changelogs written in Markdown (RELEASE_CHANGELOG,
5
+ // a changeset's file among them), as `npm version` and a release's tooling
6
+ // leave one. What each commit changes is read as Replay reads it, kept by
7
+ // the commit (repository-changes.ts repositoryChanges).
8
+ import { type ChangesStore, type CommitChanges, repositoryChanges } from './repository-changes.ts'
9
+ import { githubGraphql } from './repository-history.ts'
10
+
11
+ // The tags read, a page a query, the latest commits' first, as many pages as
12
+ // TAG_PAGES; of the commits they name, as many as RELEASES_READ have their
13
+ // files read.
14
+ const TAG_PAGE = 100
15
+ const TAG_PAGES = 5
16
+ const RELEASES_READ = 200
17
+ // An annotated tag's target, its own target in turn, through as many as
18
+ // TAG_DEPTH annotated tags.
19
+ const TAG_DEPTH = 3
20
+ const SHA = /^[a-f\d]{40}$/u
21
+ const RELEASE_LOCKFILES = new Set(['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lock', 'bun.lockb'])
22
+ const RELEASE_CHANGELOG = /^(?:changelog|changes|history|news|releases?)(?:[._-][^/]*)?\.(?:md|markdown)$/iu
23
+ const CHANGESET = /(?:^|\/)\.changeset\/[^/]+\.md$/iu
24
+
25
+ const tagTarget = (depth: number): string => `target { __typename oid ... on Commit { committedDate }${depth > 0 ? ` ... on Tag { ${tagTarget(depth - 1)} }` : ''} }`
26
+ const TAGS_QUERY = `query($owner: String!, $name: String!, $after: String) {
27
+ repository(owner: $owner, name: $name) {
28
+ refs(refPrefix: "refs/tags/", first: ${TAG_PAGE}, after: $after, orderBy: { field: TAG_COMMIT_DATE, direction: DESC }) {
29
+ pageInfo { hasNextPage endCursor }
30
+ nodes { ${tagTarget(TAG_DEPTH)} }
31
+ }
32
+ }
33
+ }`
34
+ type TagTarget = { __typename?: unknown; oid?: unknown; committedDate?: unknown; target?: TagTarget | null } | null | undefined
35
+ type TagsPage = { repository?: { refs?: { pageInfo?: { hasNextPage?: unknown; endCursor?: unknown }; nodes?: ({ target?: TagTarget } | null)[] } | null } | null }
36
+
37
+ // The commit a tag names, through its annotated tags, and when it was
38
+ // committed; null for one naming no commit (a tree, a blob).
39
+ function taggedCommit(target: TagTarget, depth = TAG_DEPTH): { oid: string; at: number } | null {
40
+ if (target?.__typename === 'Tag' && depth > 0) return taggedCommit(target.target, depth - 1)
41
+ const at = typeof target?.committedDate === 'string' ? Date.parse(target.committedDate) : Number.NaN
42
+ return target?.__typename === 'Commit' && typeof target.oid === 'string' && SHA.test(target.oid) && Number.isSafeInteger(at) ? { oid: target.oid, at } : null
43
+ }
44
+
45
+ // The commits the repository's tags name committed since `since`, the
46
+ // latest first, as many pages of them as TAG_PAGES.
47
+ export async function taggedCommits(fullName: string, token: string, since: number, fetchImpl: typeof fetch = globalThis.fetch): Promise<Set<string>> {
48
+ const [owner, name] = fullName.split('/') as [string, string]
49
+ const tagged = new Set<string>()
50
+ let after: string | null = null
51
+ for (let pages = 0; pages < TAG_PAGES; pages++) {
52
+ const page = await githubGraphql(TAGS_QUERY, { owner, name, after }, token, fetchImpl) as TagsPage | null
53
+ const refs = page?.repository?.refs
54
+ const commits = (refs?.nodes ?? []).flatMap(node => taggedCommit(node?.target) ?? [])
55
+ for (const commit of commits) if (commit.at >= since) tagged.add(commit.oid)
56
+ if (refs?.pageInfo?.hasNextPage !== true || typeof refs.pageInfo.endCursor !== 'string' || commits.some(commit => commit.at < since)) break
57
+ after = refs.pageInfo.endCursor
58
+ }
59
+ return tagged
60
+ }
61
+
62
+ // Whether a path is one a release changes: a package.json, a lockfile beside
63
+ // one, or a changelog in Markdown.
64
+ const releaseFile = (path: string) => {
65
+ const base = path.slice(path.lastIndexOf('/') + 1)
66
+ return base === 'package.json' || RELEASE_LOCKFILES.has(base) || RELEASE_CHANGELOG.test(base) || CHANGESET.test(path)
67
+ }
68
+
69
+ // Whether what a commit changes is a release's: a package.json at least, and
70
+ // nothing a release changes none of, a rename's both paths alike; one
71
+ // GitHub listed only some files of, not.
72
+ export function releaseChanges({ files, more }: CommitChanges): boolean {
73
+ const paths = files.flatMap(([path, status, from]) => status === 'R' ? [path, from] : [path])
74
+ return !more && paths.some(path => path.slice(path.lastIndexOf('/') + 1) === 'package.json') && paths.every(releaseFile)
75
+ }
76
+
77
+ // The commits since `since` that release the repository: those its tags
78
+ // name whose changes are a release's, each read as Replay reads it (`kept`),
79
+ // as many as RELEASES_READ, sorted.
80
+ export async function releaseCommits(fullName: string, token: string, since: number, kept: ChangesStore, fetchImpl: typeof fetch = globalThis.fetch): Promise<string[]> {
81
+ const tagged = [...await taggedCommits(fullName, token, since, fetchImpl)].slice(0, RELEASES_READ)
82
+ const changes = await repositoryChanges(fullName, token, tagged, kept, fetchImpl)
83
+ return tagged.filter(sha => { const read = changes.get(sha); return read ? releaseChanges(read) : false }).toSorted()
84
+ }