@preventive/triage 1.0.0-alpha.60 → 1.0.0-alpha.61

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 (132) hide show
  1. package/common/default-scan-models.ts +6 -5
  2. package/common/managed/comments.ts +9 -0
  3. package/out/activity.js +1 -1
  4. package/out/chunk-6CCSTJWB.js +1 -0
  5. package/out/{chunk-VZJIHHTQ.js → chunk-B3FNMHOE.js} +1 -1
  6. package/out/chunk-BNH52UHC.js +2 -0
  7. package/out/chunk-BRO77PQY.js +42 -0
  8. package/out/chunk-GRGIZOTP.js +4 -0
  9. package/out/chunk-JJK5OZG2.js +15 -0
  10. package/out/chunk-OFZYEWBH.js +244 -0
  11. package/out/{chunk-YGRRXC2L.js → chunk-OIERSXON.js} +1 -1
  12. package/out/{chunk-TZS7KERJ.js → chunk-QCOGVL37.js} +1 -1
  13. package/out/{chunk-6VDDCFHT.js → chunk-W3QFV4SP.js} +1 -1
  14. package/out/chunk-W6VOKW2N.js +12 -0
  15. package/out/chunk-ZQNEWVGG.js +1 -0
  16. package/out/client-managed.js +2 -2
  17. package/out/compare.js +19 -14
  18. package/out/dialogs.js +38 -38
  19. package/out/graph.js +12 -12
  20. package/out/index.html +5 -5
  21. package/out/scan.js +1 -1
  22. package/out/terminal.js +12 -12
  23. package/out/view.css +1 -1
  24. package/out/view.js +4 -4
  25. package/package.json +9 -6
  26. package/server-managed/activity.ts +23 -43
  27. package/server-managed/agent-merges.ts +2 -2
  28. package/server-managed/blob-store.ts +10 -1
  29. package/server-managed/bundle-advisories.ts +3 -2
  30. package/server-managed/bundle-advisory-inventory.ts +1 -1
  31. package/server-managed/bundle-build-worker.js +41 -6
  32. package/server-managed/bundle-build.ts +18 -10
  33. package/server-managed/bundle-cache.ts +29 -41
  34. package/server-managed/bundle-catalog.ts +11 -11
  35. package/server-managed/bundle-commits.ts +9 -16
  36. package/server-managed/bundle-dependency-reviews.ts +5 -11
  37. package/server-managed/bundle-summary-cache.ts +23 -14
  38. package/server-managed/bundle-validation.ts +2 -1
  39. package/server-managed/combined.ts +1 -5
  40. package/server-managed/comments.ts +15 -28
  41. package/server-managed/commit-coauthors.ts +4 -5
  42. package/server-managed/commit-lockfiles.ts +6 -5
  43. package/server-managed/comparison.ts +3 -5
  44. package/server-managed/config.ts +1 -2
  45. package/server-managed/db-methods.ts +163 -244
  46. package/server-managed/db-neon.ts +82 -178
  47. package/server-managed/db-schema.ts +15 -0
  48. package/server-managed/db.ts +5 -11
  49. package/server-managed/dependabot-access.ts +2 -1
  50. package/server-managed/dependabot-alerts.ts +7 -12
  51. package/server-managed/dependency-review-comments.ts +7 -13
  52. package/server-managed/dependency-reviews.ts +14 -15
  53. package/server-managed/github-accounts.ts +4 -5
  54. package/server-managed/github-actions.ts +6 -6
  55. package/server-managed/github-app.ts +19 -48
  56. package/server-managed/github-graphql.ts +5 -2
  57. package/server-managed/github-issue-links.ts +62 -42
  58. package/server-managed/github-issue-oauth.ts +7 -24
  59. package/server-managed/github-issues.ts +9 -7
  60. package/server-managed/github-link-oauth.ts +7 -20
  61. package/server-managed/github-oauth.ts +38 -12
  62. package/server-managed/github-pulls.ts +37 -26
  63. package/server-managed/github-requests.ts +21 -8
  64. package/server-managed/github-values.ts +26 -0
  65. package/server-managed/history-windows.ts +7 -7
  66. package/server-managed/http.ts +495 -554
  67. package/server-managed/index.ts +6 -6
  68. package/server-managed/link-reports.ts +6 -19
  69. package/server-managed/lockfile-scope.ts +1 -1
  70. package/server-managed/management.ts +14 -3
  71. package/server-managed/npm-delta.ts +22 -57
  72. package/server-managed/npm-insights.ts +31 -26
  73. package/server-managed/npm-kept.ts +9 -8
  74. package/server-managed/npm-loads.ts +2 -7
  75. package/server-managed/npm-manifest.ts +6 -4
  76. package/server-managed/npm-packages.ts +17 -9
  77. package/server-managed/npm-patch.ts +8 -16
  78. package/server-managed/npm-provenance.ts +12 -8
  79. package/server-managed/npm-risk.ts +9 -7
  80. package/server-managed/object-storage-disk.ts +2 -3
  81. package/server-managed/object-storage-vercel.ts +15 -11
  82. package/server-managed/object-storage.ts +7 -0
  83. package/server-managed/pretty-print.ts +8 -19
  84. package/server-managed/public-workspace.ts +50 -46
  85. package/server-managed/pull-comment-reviews.ts +2 -2
  86. package/server-managed/pull-dependencies.ts +20 -31
  87. package/server-managed/pull-dependency-reviews.ts +17 -24
  88. package/server-managed/pull-reviews.ts +4 -7
  89. package/server-managed/queue.ts +14 -0
  90. package/server-managed/release-commits.ts +9 -8
  91. package/server-managed/rename-diff.ts +17 -60
  92. package/server-managed/report-migration.ts +5 -8
  93. package/server-managed/report-sources.ts +6 -10
  94. package/server-managed/report-store.ts +2 -10
  95. package/server-managed/repository-actions.ts +7 -8
  96. package/server-managed/repository-agents.ts +31 -57
  97. package/server-managed/repository-aliases.ts +3 -9
  98. package/server-managed/repository-browser.ts +18 -16
  99. package/server-managed/repository-changes.ts +33 -37
  100. package/server-managed/repository-code.ts +5 -5
  101. package/server-managed/repository-dependency-reviews.ts +6 -13
  102. package/server-managed/repository-discovery.ts +2 -1
  103. package/server-managed/repository-history.ts +47 -51
  104. package/server-managed/repository-issues.ts +59 -30
  105. package/server-managed/repository-pulls.ts +7 -12
  106. package/server-managed/repository-pulse.ts +51 -45
  107. package/server-managed/repository-risk-assess.ts +5 -2
  108. package/server-managed/repository-risk-audit.ts +1 -1
  109. package/server-managed/repository-risk-read.ts +6 -6
  110. package/server-managed/repository-risk.ts +32 -40
  111. package/server-managed/repository-squashes.ts +7 -15
  112. package/server-managed/request-timing.ts +1 -1
  113. package/server-managed/sql.ts +18 -0
  114. package/server-managed/storage-encryption.ts +5 -7
  115. package/server-managed/team-app.ts +4 -7
  116. package/server-managed/team-npm-scopes.ts +5 -8
  117. package/server-managed/team-reports.ts +15 -15
  118. package/server-managed/type-only-proof.js +108 -0
  119. package/server-managed/type-only-worker.js +26 -14
  120. package/server-managed/type-only.ts +72 -62
  121. package/server-managed/uploads.ts +3 -3
  122. package/server-managed/upstream-cache.ts +5 -7
  123. package/server-managed/worker-turns.ts +76 -0
  124. package/server-managed/workspace-shares.ts +1 -2
  125. package/out/chunk-2SY4PYUQ.js +0 -4
  126. package/out/chunk-4HI2MSAV.js +0 -17
  127. package/out/chunk-4TQKM3JC.js +0 -42
  128. package/out/chunk-EEQHVKR3.js +0 -1
  129. package/out/chunk-HNQNDNIE.js +0 -12
  130. package/out/chunk-OFPDMZJF.js +0 -244
  131. package/out/chunk-OQRSIBSC.js +0 -1
  132. package/out/chunk-YTO6AQZM.js +0 -2
@@ -18,13 +18,15 @@
18
18
  import { type AgentAuthor, type AgentBranch, type AgentCommit, type AgentIssue, type AgentPull, type AgentSignals, type AppAgent, agentSignals } from '../common/managed/agent-tasks.ts'
19
19
  import { GITHUB_AGENTS, type GithubAgentAccount, type GithubAgentId, githubAgent } from '../common/managed/github-agents.ts'
20
20
  import { AGENT_BRANCH_PREFIXES, APP_AGENTS } from './app-agents.ts'
21
- import type { GraphqlError } from './github-graphql.ts'
22
- import { ACTOR, ALL_BRANCHES, type HistoryCommit, type HistoryPages, type NamedAccount, actorOf, commitAccount, commitMarks, githubGraphql, historyFrom, historyMarks,
23
- inBatches, linkNoreplyUsers, messageMarks, variablesOf } from './repository-history.ts'
21
+ import { ACTOR, type GraphAccount, type GraphActor, type NamedAccount, actorOf, commitAccount, linkNoreplyUsers } from './github-accounts.ts'
22
+ import { githubGraphql, notFound } from './github-graphql.ts'
23
+ import { SHA, count, nameOf, timeOf } from './github-values.ts'
24
+ import { ALL_BRANCHES, type Connection, type HistoryCommit, type HistoryPages, commitIds, commitMarks, commitsQuery, historyFrom, historyMarks, inBatches, messageMarks,
25
+ nextCursor } from './repository-history.ts'
24
26
  import type { IssueList, PullList } from './repository-pulls.ts'
25
27
 
26
- export const AGENT_PULLS_PAGE = 50
27
- export const AGENT_COMMITS_PAGE = 100
28
+ const AGENT_PULLS_PAGE = 50
29
+ const AGENT_COMMITS_PAGE = 100
28
30
  const AGENT_ISSUES = 100
29
31
  const AGENT_BRANCHES = 500
30
32
  const CLOSES = 5
@@ -32,9 +34,6 @@ const CLOSES = 5
32
34
  // page.
33
35
  const LABELS = 100
34
36
  const MAX_TITLE = 1000
35
- const MAX_NAME = 256
36
- const LOGIN = /^[A-Za-z\d][A-Za-z\d-]{0,38}(?:\[bot\])?$/u
37
- const SHA = /^[a-f\d]{40}$/u
38
37
  // Commits whether a pull request brought each is looked up of, in a query,
39
38
  // and queries at once.
40
39
  const PULLED_COMMITS = 100
@@ -45,11 +44,7 @@ const AGENT_EMAILS = APP_AGENTS.flatMap(({ id }) => GITHUB_AGENTS[id as GithubAg
45
44
  .flatMap(({ id: account, logins }: GithubAgentAccount) => account === undefined ? [] : logins.map(login => `${account}+${login}@users.noreply.github.com`)))
46
45
 
47
46
  // Branches' tip commits, `c<n>` the `n`th's: each's message and author.
48
- const tipsQuery = (count: number) => `query($owner: String!, $name: String!, ${variablesOf('o', count, 'GitObjectID!')}) {
49
- repository(owner: $owner, name: $name) {
50
- ${Array.from({ length: count }, (_, at) => `c${at}: object(oid: $o${at}) { ... on Commit { message author { email user { login databaseId } } } }`).join('\n ')}
51
- }
52
- }`
47
+ const tipsQuery = (size: number) => commitsQuery(size, 'c', 'message author { email user { login databaseId } }')
53
48
  // Tips looked up a query, and queries at once.
54
49
  const TIPS = 100
55
50
  const TIPS_PARALLEL = 4
@@ -99,62 +94,47 @@ const SEARCH_QUERY = `query($query: String!, $after: String) {
99
94
  }
100
95
  }`
101
96
 
102
- type Login = { login?: unknown; databaseId?: unknown } | null | undefined
103
- export type PullNode = { number?: unknown; title?: unknown; state?: unknown; isDraft?: unknown; createdAt?: unknown; updatedAt?: unknown; author?: Login; body?: unknown
104
- headRefName?: unknown; isCrossRepository?: unknown; headRepositoryOwner?: Login; additions?: unknown; deletions?: unknown; commits?: { totalCount?: unknown } | null
97
+ export type PullNode = { number?: unknown; title?: unknown; state?: unknown; isDraft?: unknown; createdAt?: unknown; updatedAt?: unknown; author?: GraphAccount; body?: unknown
98
+ headRefName?: unknown; isCrossRepository?: unknown; headRepositoryOwner?: GraphAccount; additions?: unknown; deletions?: unknown; commits?: { totalCount?: unknown } | null
105
99
  last?: { nodes?: ({ commit?: { message?: unknown } | null } | null)[] } | null; mergeCommit?: { message?: unknown } | null
106
100
  closingIssuesReferences?: { nodes?: ({ number?: unknown } | null)[] }; labels?: { nodes?: ({ name?: unknown } | null)[] } }
107
- type GitActor = { email?: unknown; user?: Login }
108
101
  type CommitNode = { oid?: unknown; messageHeadline?: unknown; message?: unknown; committedDate?: unknown; additions?: unknown; deletions?: unknown
109
- author?: GitActor | null; associatedPullRequests?: { totalCount?: unknown } }
110
- export type IssueNode = { number?: unknown; title?: unknown; state?: unknown; createdAt?: unknown; updatedAt?: unknown; author?: Login }
111
- type Connection<T> = { pageInfo?: { hasNextPage?: unknown; endCursor?: unknown }; nodes?: (T | null)[] }
102
+ author?: GraphActor | null; associatedPullRequests?: { totalCount?: unknown } }
103
+ export type IssueNode = { number?: unknown; title?: unknown; state?: unknown; createdAt?: unknown; updatedAt?: unknown; author?: GraphAccount }
112
104
  // Whether a pull request brought each commit, `c<n>` the `n`th's.
113
- const pulledQuery = (count: number) => `query($owner: String!, $name: String!, ${variablesOf('o', count, 'GitObjectID!')}) {
114
- repository(owner: $owner, name: $name) {
115
- ${Array.from({ length: count }, (_, at) => `c${at}: object(oid: $o${at}) { ... on Commit { associatedPullRequests(first: 1) { totalCount } } }`).join('\n ')}
116
- }
117
- }`
105
+ const pulledQuery = (size: number) => commitsQuery(size, 'c', 'associatedPullRequests(first: 1) { totalCount }')
118
106
  type Pulled = { repository?: Record<string, { associatedPullRequests?: { totalCount?: unknown } } | null> | null }
119
107
  type Authored = { repository?: { object?: { history?: Connection<CommitNode> } | null } | null }
120
108
  type Issues = { repository?: { issues?: Connection<IssueNode> } | null }
121
- type Tips = { repository?: Record<string, { message?: unknown; author?: GitActor | null } | null> | null }
109
+ type Tips = { repository?: Record<string, { message?: unknown; author?: GraphActor | null } | null> | null }
122
110
  type RefNode = { prefix?: unknown; name?: unknown; target?: { oid?: unknown; committedDate?: unknown } | null }
123
111
  type RefsPage = { repository?: { refs?: Connection<RefNode> } | null }
124
112
  type Found = { search?: { pageInfo?: { endCursor?: unknown }; nodes?: (PullNode | null)[] } | null } | null
125
113
 
126
- const count = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0 ? value as number : 0
127
114
  const number = (value: unknown) => Number.isSafeInteger(value) && (value as number) > 0 ? value as number : null
128
- const timeOf = (value: unknown) => {
129
- const at = typeof value === 'string' ? Date.parse(value) : Number.NaN
130
- return Number.isSafeInteger(at) ? at : null
131
- }
132
- const nameOf = (value: unknown, max = MAX_NAME) => typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : null
133
- const loginOf = (author: Login) => typeof author?.login === 'string' && LOGIN.test(author.login) ? author.login : null
134
115
  const PULL_STATES: Record<string, AgentPull['state']> = { OPEN: 'open', MERGED: 'merged', CLOSED: 'closed' }
135
116
 
136
117
  // A pull request's row: what it is, and the marks an agent left on it.
137
118
  export function pull(node: PullNode | null): AgentPull | null {
138
119
  const at = number(node?.number)
139
120
  if (!node || !at) return null
140
- const author = accountOf(node.author)
121
+ const author = actorOf(node.author)
141
122
  return { number: at, title: nameOf(node.title, MAX_TITLE) ?? '', state: PULL_STATES[String(node.state)] ?? 'closed', draft: node.isDraft === true,
142
- author: loginOf(node.author), authorId: author?.id ?? null, createdAt: timeOf(node.createdAt), updatedAt: timeOf(node.updatedAt), head: nameOf(node.headRefName),
123
+ author: author.login, authorId: author.id, createdAt: timeOf(node.createdAt), updatedAt: timeOf(node.updatedAt), head: nameOf(node.headRefName),
143
124
  // A fork's, its owner; one GitHub no longer names, a fork of its own.
144
- fork: node.isCrossRepository === true ? loginOf(node.headRepositoryOwner) ?? `pull-${at}` : null,
125
+ fork: node.isCrossRepository === true ? actorOf(node.headRepositoryOwner).login ?? `pull-${at}` : null,
145
126
  additions: count(node.additions), deletions: count(node.deletions), commits: count(node.commits?.totalCount),
146
127
  closes: (node.closingIssuesReferences?.nodes ?? []).flatMap(closed => number(closed?.number) ?? []),
147
128
  signals: agentSignals([node.body, node.last?.nodes?.[0]?.commit?.message, node.mergeCommit?.message], APP_AGENTS, nameOf(node.headRefName),
148
- author, (node.labels?.nodes ?? []).map(label => label?.name)) }
129
+ both(author), (node.labels?.nodes ?? []).map(label => label?.name)) }
149
130
  }
150
131
 
151
132
  // An account as GitHub names it, by its login and id, both.
152
133
  const both = ({ login, id }: NamedAccount): AgentAuthor | null => login !== null && id !== null ? { login, id } : null
153
- const accountOf = (actor: Login) => both(actorOf(actor))
154
134
  // A commit's author: the account GitHub knows by its address, else the one
155
135
  // its no-reply address names by id and login, as a bot's, Copilot's or
156
136
  // Dependabot's, is told by that alone (repository-history.ts commitAccount).
157
- const authorOf = (actor: GitActor | null | undefined) => both(commitAccount(actor))
137
+ const authorOf = (actor: GraphActor | null | undefined) => both(commitAccount(actor))
158
138
 
159
139
  // A commit the app agents' accounts authored, as kept: as read, its
160
140
  // message's marks (messageMarks) in its place, never the message.
@@ -169,7 +149,7 @@ function directCommit(node: AuthoredCommit | null): AgentCommit | null {
169
149
  const signals = commitMarks(node.marks, { name: null, email: node.author?.email, account: commitAccount(node.author) })
170
150
  if (!signals) return null
171
151
  return { oid: node.oid, title: nameOf(node.messageHeadline, MAX_TITLE) ?? '', at: timeOf(node.committedDate),
172
- author: author?.login ?? loginOf(node.author?.user), authorId: author?.id ?? null,
152
+ author: author?.login ?? actorOf(node.author?.user).login, authorId: author?.id ?? null,
173
153
  additions: count(node.additions), deletions: count(node.deletions), signals }
174
154
  }
175
155
 
@@ -184,17 +164,13 @@ export interface CommitPulls {
184
164
  write(sha: string, pulled: boolean): Promise<void>
185
165
  }
186
166
 
187
- // A commit GitHub has none of, as one rewritten away: its field null.
188
- const notFound = (error: GraphqlError) => error?.type === 'NOT_FOUND'
189
-
190
167
  // Those of `shas` a pull request brought: as kept (`kept`), the rest looked
191
168
  // up, PULLED_COMMITS a query, and kept; one GitHub has none of, none.
192
169
  async function pulledCommits(fullName: string, token: string, shas: string[], kept: CommitPulls, fetchImpl: typeof fetch) {
193
170
  const [owner, name] = fullName.split('/') as [string, string]
194
171
  const known = await kept.read(shas)
195
172
  await inBatches(shas.filter(sha => !known.has(sha)), PULLED_COMMITS, PULLED_PARALLEL, async batch => {
196
- const data = await githubGraphql(pulledQuery(batch.length), { owner, name, ...Object.fromEntries(batch.map((sha, at) => [`o${at}`, sha])) }, token, fetchImpl,
197
- notFound) as Pulled
173
+ const data = await githubGraphql(pulledQuery(batch.length), { owner, name, ...commitIds(batch) }, token, fetchImpl, notFound) as Pulled
198
174
  await Promise.all(batch.map((sha, at) => {
199
175
  const node = data?.repository?.[`c${at}`]
200
176
  if (!node) return Promise.resolve()
@@ -227,13 +203,14 @@ function frontier(commits: HistoryCommit[], left: string[]) {
227
203
  export function issue(node: IssueNode | null): AgentIssue | null {
228
204
  const at = number(node?.number)
229
205
  if (!node || !at) return null
230
- return { number: at, title: nameOf(node.title, MAX_TITLE) ?? '', state: node.state === 'OPEN' ? 'open' : 'closed', author: loginOf(node.author),
231
- authorId: accountOf(node.author)?.id ?? null, createdAt: timeOf(node.createdAt), updatedAt: timeOf(node.updatedAt) }
206
+ const author = actorOf(node.author)
207
+ return { number: at, title: nameOf(node.title, MAX_TITLE) ?? '', state: node.state === 'OPEN' ? 'open' : 'closed', author: author.login,
208
+ authorId: author.id, createdAt: timeOf(node.createdAt), updatedAt: timeOf(node.updatedAt) }
232
209
  }
233
210
 
234
211
  // A branch's tip, as kept: its message's marks (messageMarks), never the
235
212
  // message, and its author as read.
236
- export interface BranchTip { marks: AgentSignals | null; author: GitActor | null }
213
+ export interface BranchTip { marks: AgentSignals | null; author: GraphActor | null }
237
214
  // The tips of branches, kept by their commits, which never change.
238
215
  export interface BranchTips {
239
216
  read(shas: string[]): Promise<Map<string, BranchTip>>
@@ -248,7 +225,7 @@ function agentBranch({ name, at }: { name: string; at: number | null }, tip: Bra
248
225
  const author = authorOf(tip?.author)
249
226
  const authored = author ? githubAgent(author.login, author.id) : null
250
227
  const marks = tip?.marks
251
- return { name, at, author: author?.login ?? loginOf(tip?.author?.user), authorId: author?.id ?? null, signals: { sessions: marks?.sessions ?? [],
228
+ return { name, at, author: author?.login ?? actorOf(tip?.author?.user).login, authorId: author?.id ?? null, signals: { sessions: marks?.sessions ?? [],
252
229
  tasks: marks?.tasks ?? [], claude: marks?.claude ?? false, codex: marks?.codex ?? false,
253
230
  agents: APP_AGENTS.flatMap(({ id, prefix }) => marks?.agents.includes(id) || authored === id || name.startsWith(prefix) ? [id] : []) } }
254
231
  }
@@ -259,17 +236,15 @@ async function prefixHeads(owner: string, name: string, prefix: string, token: s
259
236
  const found: Head[] = []
260
237
  let after: string | null = null
261
238
  for (let page = 0; page < MAX_BRANCH_PAGES; page++) {
262
- const refs: Connection<RefNode> | undefined = (await githubGraphql(BRANCHES_QUERY, { owner, name, prefix: `refs/heads/${prefix}`, after }, token, fetchImpl) as RefsPage)
263
- ?.repository?.refs
239
+ const refs = (await githubGraphql(BRANCHES_QUERY, { owner, name, prefix: `refs/heads/${prefix}`, after }, token, fetchImpl) as RefsPage)?.repository?.refs
264
240
  for (const node of refs?.nodes ?? []) {
265
241
  const ref = typeof node?.prefix === 'string' && typeof node.name === 'string' ? `${node.prefix}${node.name}` : null
266
242
  const branch = ref?.startsWith('refs/heads/') ? nameOf(ref.slice('refs/heads/'.length)) : null
267
243
  const sha = node?.target?.oid
268
244
  if (branch?.startsWith(prefix) && typeof sha === 'string' && SHA.test(sha)) found.push({ name: branch, sha, at: timeOf(node!.target!.committedDate) })
269
245
  }
270
- const next: Connection<RefNode>['pageInfo'] = refs?.pageInfo
271
- if (next?.hasNextPage !== true || typeof next.endCursor !== 'string') break
272
- after = next.endCursor
246
+ after = nextCursor(refs?.pageInfo)
247
+ if (after === null) break
273
248
  }
274
249
  return found
275
250
  }
@@ -288,8 +263,7 @@ async function agentBranches(fullName: string, token: string, { heads, cut }: {
288
263
  const shas = [...new Set(shown.map(head => head.sha))]
289
264
  const known = await tips.read(shas)
290
265
  await inBatches(shas.filter(sha => !known.has(sha)), TIPS, TIPS_PARALLEL, async batch => {
291
- const data = await githubGraphql(tipsQuery(batch.length), { owner, name, ...Object.fromEntries(batch.map((sha, at) => [`o${at}`, sha])) }, token, fetchImpl,
292
- notFound) as Tips
266
+ const data = await githubGraphql(tipsQuery(batch.length), { owner, name, ...commitIds(batch) }, token, fetchImpl, notFound) as Tips
293
267
  await linkNoreplyUsers(batch.map((_, at) => data?.repository?.[`c${at}`]?.author), token, fetchImpl)
294
268
  await Promise.all(batch.map((sha, at) => {
295
269
  const node = data?.repository?.[`c${at}`]
@@ -345,7 +319,7 @@ const updatedBy = (at: number) => Number.isFinite(at) ? ` updated:<=${new Date(a
345
319
  type Head = { name: string; sha: string; at: number | null }
346
320
  // The commits the app agents' accounts authored from a head (AUTHORED_QUERY),
347
321
  // kept by it and the addresses they were asked by (`key`).
348
- export interface AuthoredCommits {
322
+ interface AuthoredCommits {
349
323
  read(key: string): Promise<AuthoredCommit[] | null>
350
324
  write(key: string, commits: AuthoredCommit[]): Promise<void>
351
325
  }
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto'
2
2
  import { reportRepoGithub } from '@preventive/report'
3
3
  import { type RepositoryAliasInput, matchRepositoryAlias, repositoryAliasNeedsFilePrefix } from '../common/managed/repository-alias.ts'
4
4
  import type { ManagedDb } from './db.ts'
5
- import { ManagedMutationError } from './management.ts'
5
+ import { ManagedMutationError, sessionAdmin } from './management.ts'
6
6
  import { normalizeTeamPath } from './repo-path.ts'
7
7
  import type { ManagedSql } from './sql.ts'
8
8
 
@@ -49,12 +49,6 @@ function parseAlias(input: unknown): RepositoryAliasInput {
49
49
  }
50
50
 
51
51
  export function repositoryAliasMethods(db: ManagedSql): RepositoryAliasStore {
52
- async function authorize(sessionId: string) {
53
- const user = await db.prepare(`SELECT u.role FROM managed_session s JOIN managed_user u ON u.id = s.user_id
54
- WHERE s.id = ? AND s.expires_at > ?`).get(sessionId, Date.now()) as { role: string } | undefined
55
- if (!user) throw new ManagedMutationError(401, 'unauthenticated')
56
- if (user.role !== 'admin') throw new ManagedMutationError(403, 'forbidden')
57
- }
58
52
  async function listRepositoryAliases() {
59
53
  return await db.prepare(`SELECT id, old_repo AS oldRepo, old_path AS oldPath, repo_id AS repoId, new_path AS newPath
60
54
  FROM managed_repository_alias ORDER BY old_repo, old_path, id`).all() as RepositoryAlias[]
@@ -62,7 +56,7 @@ export function repositoryAliasMethods(db: ManagedSql): RepositoryAliasStore {
62
56
  return {
63
57
  listRepositoryAliases,
64
58
  async saveRepositoryAlias(sessionId, id, input) {
65
- await authorize(sessionId)
59
+ await sessionAdmin(db, sessionId)
66
60
  const alias = parseAlias(input)
67
61
  if (!await db.prepare('SELECT repo_id FROM managed_selected_repo WHERE repo_id = ? AND active = 1').get(alias.repoId)) throw new ManagedMutationError(400, 'bad-repo')
68
62
  if (id && !await db.prepare('SELECT id FROM managed_repository_alias WHERE id = ?').get(id)) throw new ManagedMutationError(404, 'no-alias')
@@ -75,7 +69,7 @@ export function repositoryAliasMethods(db: ManagedSql): RepositoryAliasStore {
75
69
  return { id: key, ...alias }
76
70
  },
77
71
  async deleteRepositoryAlias(sessionId, id) {
78
- await authorize(sessionId)
72
+ await sessionAdmin(db, sessionId)
79
73
  if (!(await db.prepare('DELETE FROM managed_repository_alias WHERE id = ?').run(id)).changes) throw new ManagedMutationError(404, 'no-alias')
80
74
  },
81
75
  async getRepositoryImportLocation(github, directory, filePrefix = '') {
@@ -1,7 +1,10 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import type { ManagedConfig } from './config.ts'
3
3
  import type { SelectedRepo } from './db.ts'
4
- import { GithubApiError, type GithubIdentity, READ_PERMISSIONS, githubJson, githubRepoPermission, githubUserIdentity, onTokenRejected, repoAccessToken } from './github-app.ts'
4
+ import { type GithubIdentity, READ_PERMISSIONS, githubRepoPermission, githubUserIdentity, repoAccessToken } from './github-app.ts'
5
+ import { GithubApiError } from './github-errors.ts'
6
+ import { encodedPath, githubJson, onTokenRejected, repoApi } from './github-requests.ts'
7
+ import { SHA } from './github-values.ts'
5
8
  import { MAX_PACKAGE_BYTES, readConfigEntryPoints, readPackageEntryPoints } from './package-entry-points.ts'
6
9
  import { MAX_STASIS_CONFIG_BYTES, STASIS_CONFIG } from './stasis-config.ts'
7
10
  import { readSolidityEntryPoints } from './solidity-entry-points.ts'
@@ -13,7 +16,7 @@ const REFS_PAGE = 100
13
16
  // Each branch or tag GitHub lists, by its name and commit, those it names
14
17
  // one for.
15
18
  const refCommits = (items: { name?: unknown; commit?: { sha?: unknown } }[]) => items.flatMap(item => typeof item?.name === 'string' && item.name
16
- && typeof item.commit?.sha === 'string' && /^[a-f\d]{40}$/u.test(item.commit.sha) ? [{ name: item.name, sha: item.commit.sha }] : [])
19
+ && typeof item.commit?.sha === 'string' && SHA.test(item.commit.sha) ? [{ name: item.name, sha: item.commit.sha }] : [])
17
20
 
18
21
  // Each branch GitHub lists, by its name and commit. Branches are listed by
19
22
  // name, a full page of them leaving the default branch out where many come
@@ -21,8 +24,8 @@ const refCommits = (items: { name?: unknown; commit?: { sha?: unknown } }[]) =>
21
24
  async function branchCommits(read: (suffix: string) => Promise<unknown>, branches: { name?: unknown; commit?: { sha?: unknown } }[], defaultBranch: string) {
22
25
  const listed = refCommits(branches)
23
26
  if (!defaultBranch || branches.length < REFS_PAGE || listed.some(item => item.name === defaultBranch)) return listed
24
- const ref = await read(`/git/ref/heads/${defaultBranch.split('/').map(encodeURIComponent).join('/')}`).catch(() => null) as { object?: { sha?: unknown } } | null
25
- return typeof ref?.object?.sha === 'string' && /^[a-f\d]{40}$/u.test(ref.object.sha) ? [...listed, { name: defaultBranch, sha: ref.object.sha }] : listed
27
+ const ref = await read(`/git/ref/heads/${encodedPath(defaultBranch)}`).catch(() => null) as { object?: { sha?: unknown } } | null
28
+ return typeof ref?.object?.sha === 'string' && SHA.test(ref.object.sha) ? [...listed, { name: defaultBranch, sha: ref.object.sha }] : listed
26
29
  }
27
30
 
28
31
  export interface RepositoryEntry { name: string; path: string; type: 'dir' | 'file' | 'symlink' | 'submodule' }
@@ -36,7 +39,7 @@ export function scopedDirectory(path: string, scopes: (string | null)[]): Reposi
36
39
  return [...names].toSorted().map(name => ({ name, path: prefix + name, type: 'dir' }))
37
40
  }
38
41
 
39
- export interface RepositoryBrowserUser { githubUserId: number | null; token: string | null }
42
+ interface RepositoryBrowserUser { githubUserId: number | null; token: string | null }
40
43
 
41
44
  function credentialFailure(err: unknown): err is GithubApiError {
42
45
  return err instanceof GithubApiError && ([401, 404].includes(err.status) || err.message === 'github-status-403')
@@ -69,9 +72,8 @@ onTokenRejected((token, fetchImpl) => {
69
72
  function verdictCache(config: ManagedConfig, user: RepositoryBrowserUser, repo: SelectedRepo, fetchImpl: typeof fetch): VerdictCache | null {
70
73
  const keepMs = config.repositoryAccessCacheMs
71
74
  if (!(keepMs > 0)) return null
72
- let verdicts = accessVerdicts.get(fetchImpl)
73
- if (!verdicts) { verdicts = new Map(); accessVerdicts.set(fetchImpl, verdicts) }
74
- const kept = verdicts
75
+ const kept = accessVerdicts.get(fetchImpl) ?? new Map<string, AccessVerdict>()
76
+ accessVerdicts.set(fetchImpl, kept)
75
77
  // The token hashed with the rest, never kept as it is.
76
78
  const key = createHash('sha256').update(JSON.stringify([user.githubUserId, user.token, repo.repoId, repo.fullName.toLowerCase(), repo.installationId, config.githubAppId])).digest('hex')
77
79
  return {
@@ -133,8 +135,8 @@ export function createRepositoryBrowser(config: ManagedConfig, user: RepositoryB
133
135
  // (readToken): how many and their bytes, or null where GitHub cuts the
134
136
  // listing short, as it does past 100,000 entries.
135
137
  export async function repositoryTreeFiles(fullName: string, token: string | null, tree: string, fetchImpl: typeof fetch = globalThis.fetch) {
136
- if (!/^[a-f\d]{40}$/u.test(tree)) throw new GithubApiError(400, 'bad-tree')
137
- const url = `https://api.github.com/repos/${fullName.split('/').map(encodeURIComponent).join('/')}/git/trees/${tree}?recursive=1`
138
+ if (!SHA.test(tree)) throw new GithubApiError(400, 'bad-tree')
139
+ const url = `${repoApi(fullName)}/git/trees/${tree}?recursive=1`
138
140
  const data = await githubJson(url, token, fetchImpl) as { tree?: unknown; truncated?: unknown }
139
141
  if (!Array.isArray(data?.tree)) throw new GithubApiError(502, 'github-malformed')
140
142
  if (data.truncated === true) return null
@@ -155,7 +157,7 @@ type Access = { data: RepoMetadata; token: string | null; level: string | null }
155
157
  // installation's. What it told, the token reading it, and the level asked.
156
158
  async function askAccess(repo: SelectedRepo, start: string | null, userToken: string | null, installationToken: () => Promise<string | null>,
157
159
  getIdentity: () => Promise<GithubIdentity>, fetchImpl: typeof fetch): Promise<Access> {
158
- const base = `https://api.github.com/repos/${repo.fullName.split('/').map(encodeURIComponent).join('/')}`
160
+ const base = repoApi(repo.fullName)
159
161
  let token = start
160
162
  const metadata = async () => {
161
163
  try { return await githubJson(base, token, fetchImpl) }
@@ -214,9 +216,9 @@ async function keptAccess(verdicts: VerdictCache | null, userToken: string | nul
214
216
  return { ...asked, data }
215
217
  }
216
218
 
217
- async function repositoryReader(repo: SelectedRepo, userToken: string | null, installationToken: () => Promise<string | null>, getIdentity: (fresh?: boolean) => Promise<GithubIdentity>, fetchImpl: typeof fetch,
219
+ async function repositoryReader(repo: SelectedRepo, userToken: string | null, installationToken: () => Promise<string | null>, getIdentity: () => Promise<GithubIdentity>, fetchImpl: typeof fetch,
218
220
  verdicts: VerdictCache | null) {
219
- const base = `https://api.github.com/repos/${repo.fullName.split('/').map(encodeURIComponent).join('/')}`
221
+ const base = repoApi(repo.fullName)
220
222
  // Public reads can use the signed-in user's quota without repository grants.
221
223
  // Nonpublic reads still require the repository App and the effective-user gate,
222
224
  // whose permission level is kept (`level`).
@@ -233,7 +235,7 @@ async function repositoryReader(repo: SelectedRepo, userToken: string | null, in
233
235
  return {
234
236
  // Its visibility and the user's permission asked again, the user as
235
237
  // GitHub told them earlier in the request, not asked again.
236
- recheckAccess: () => checkAccess(),
238
+ recheckAccess: checkAccess,
237
239
  // Server-only credential, selected by the same live visibility/permission
238
240
  // gate as directory browsing. Never included in an HTTP response.
239
241
  readToken: () => token,
@@ -267,10 +269,10 @@ async function repositoryReader(repo: SelectedRepo, userToken: string | null, in
267
269
  // The first commit a listing from `sha` returns is that commit, without
268
270
  // the files GET /commits/:sha adds.
269
271
  async commitDetails(sha: string) {
270
- return /^[a-f\d]{40}$/u.test(sha) ? parseGithubCommit(sha, await read(`/commits?sha=${sha}&per_page=1`)) : null
272
+ return SHA.test(sha) ? parseGithubCommit(sha, await read(`/commits?sha=${sha}&per_page=1`)) : null
271
273
  },
272
274
  async directory(path: string, commit: string) {
273
- const data = await read(`/contents/${path.split('/').map(encodeURIComponent).join('/')}?ref=${encodeURIComponent(commit)}`)
275
+ const data = await read(`/contents/${encodedPath(path)}?ref=${encodeURIComponent(commit)}`)
274
276
  if (!Array.isArray(data)) throw new GithubApiError(400, 'not-a-directory')
275
277
  const entries: RepositoryEntry[] = []
276
278
  for (const item of data) {
@@ -10,7 +10,10 @@
10
10
  // commit holds, which Replay starts from (GET /api/admin/repositories/tree),
11
11
  // as GitHub lists its tree at once (repositoryTree), kept as well.
12
12
 
13
- import { GithubApiError, githubJson } from './github-app.ts'
13
+ import { GithubApiError } from './github-errors.ts'
14
+ import { githubJson, repoApi } from './github-requests.ts'
15
+ import { SHA } from './github-values.ts'
16
+ import { eachOf } from './queue.ts'
14
17
 
15
18
  // Commits an answer tells at most, read of GitHub as many at once as
16
19
  // CHANGES_PARALLEL.
@@ -21,9 +24,8 @@ const CHANGES_PARALLEL = 6
21
24
  export const MAX_FILES = 300
22
25
  export const FILES_PAGE = 100
23
26
  const MAX_PATH = 4096
24
- const SHA = /^[a-f\d]{40}$/u
25
27
 
26
- export type ChangeStatus = 'A' | 'M' | 'D' | 'R'
28
+ type ChangeStatus = 'A' | 'M' | 'D' | 'R'
27
29
  // A file a commit changes: its path, its status, and a rename's path before.
28
30
  export type ChangedFile = [path: string, status: Exclude<ChangeStatus, 'R'>] | [path: string, status: 'R', from: string]
29
31
  export interface CommitChanges { files: ChangedFile[]; more: boolean }
@@ -35,6 +37,13 @@ export interface ChangesStore {
35
37
  }
36
38
 
37
39
  const pathOf = (value: unknown) => typeof value === 'string' && value !== '' && value.length <= MAX_PATH && !/\p{Cc}/u.test(value) ? value : null
40
+ // No such commit: GitHub's 404, or its 422 for an id naming none.
41
+ const noCommit = (err: unknown) => err instanceof GithubApiError && (err.message === 'github-not-found' || err.message === 'github-status-422')
42
+ // What `read` answers; null where GitHub has no such commit.
43
+ const orNoCommit = <T>(read: Promise<T>) => read.catch((err: unknown) => {
44
+ if (noCommit(err)) return null
45
+ throw err
46
+ })
38
47
 
39
48
  // A file's status as git names it: a copy is a file added; one GitHub
40
49
  // lists unchanged (its mode alone changed, say) changes none.
@@ -71,12 +80,6 @@ export function changesWithin({ files, more }: CommitChanges, path: string): Com
71
80
  }) }
72
81
  }
73
82
 
74
- // Runs `run` for each of `items`, as many at once as `parallel`.
75
- async function eachOf<T>(items: T[], parallel: number, run: (item: T) => Promise<void>) {
76
- let next = 0
77
- await Promise.all(Array.from({ length: Math.min(parallel, items.length) }, async () => { while (next < items.length) await run(items[next++]!) }))
78
- }
79
-
80
83
  // A commit's files as GitHub lists them, read a page at a time while each
81
84
  // is full, till MAX_FILES are.
82
85
  async function commitFiles(url: string, token: string | null, fetchImpl: typeof fetch) {
@@ -96,15 +99,14 @@ export async function repositoryChanges(fullName: string, token: string | null,
96
99
  fetchImpl: typeof fetch = globalThis.fetch): Promise<Map<string, CommitChanges | null>> {
97
100
  const asked = [...new Set(shas)].filter(sha => SHA.test(sha))
98
101
  const found = new Map<string, CommitChanges | null>(await kept.read(asked))
99
- const repo = `https://api.github.com/repos/${fullName.split('/').map(encodeURIComponent).join('/')}`
102
+ const repo = repoApi(fullName)
100
103
  await eachOf(asked.filter(sha => !found.has(sha)), CHANGES_PARALLEL, async sha => {
101
104
  try {
102
105
  const changes = commitChanges(await commitFiles(`${repo}/commits/${sha}`, token, fetchImpl))
103
106
  found.set(sha, changes)
104
107
  await kept.write(sha, changes)
105
108
  } catch (err) {
106
- // No such commit: GitHub's 404, or its 422 for an id naming none.
107
- if (err instanceof GithubApiError && (err.message === 'github-not-found' || err.message === 'github-status-422')) found.set(sha, null)
109
+ if (noCommit(err)) found.set(sha, null)
108
110
  else throw err
109
111
  }
110
112
  })
@@ -130,7 +132,7 @@ export const TREES_READ = 3
130
132
  const MAX_TREE_READS = 400
131
133
  const TREES_PARALLEL = 6
132
134
  export interface CommitTree { files: string[]; sizes: number[]; cut: boolean }
133
- export interface TreeStore {
135
+ interface TreeStore {
134
136
  read(commit: string): Promise<CommitTree | null>
135
137
  write(commit: string, tree: CommitTree): Promise<void>
136
138
  }
@@ -139,25 +141,25 @@ type TreeEntry = { type?: unknown; path?: unknown; sha?: unknown; size?: unknown
139
141
  // A file read: its path and its bytes.
140
142
  type Blob = [path: string, size: number]
141
143
  type TreeListing = (tree: string, recursive: boolean) => Promise<{ entries: TreeEntry[]; truncated: boolean }>
144
+ // A tree's entries as GitHub lists them, those of every tree under it too
145
+ // where `recursive`, and whether it cut the listing short.
146
+ const treeListing = (fullName: string, token: string | null, fetchImpl: typeof fetch): TreeListing => {
147
+ const repo = repoApi(fullName)
148
+ return async (tree, recursive) => {
149
+ const data = await githubJson(`${repo}/git/trees/${tree}${recursive ? '?recursive=1' : ''}`, token, fetchImpl) as { tree?: unknown; truncated?: unknown }
150
+ if (!Array.isArray(data?.tree)) throw new GithubApiError(502, 'github-malformed')
151
+ return { entries: data.tree as TreeEntry[], truncated: data.truncated === true }
152
+ }
153
+ }
142
154
 
143
155
  export async function repositoryTree(fullName: string, token: string | null, commit: string, kept: TreeStore,
144
156
  fetchImpl: typeof fetch = globalThis.fetch): Promise<CommitTree | null> {
145
157
  if (!SHA.test(commit)) return null
146
158
  const held = await kept.read(commit)
147
159
  if (held) return held
148
- const repo = `https://api.github.com/repos/${fullName.split('/').map(encodeURIComponent).join('/')}`
149
- const listing: TreeListing = async (tree, recursive) => {
150
- const data = await githubJson(`${repo}/git/trees/${tree}${recursive ? '?recursive=1' : ''}`, token, fetchImpl) as { tree?: unknown; truncated?: unknown }
151
- if (!Array.isArray(data?.tree)) throw new GithubApiError(502, 'github-malformed')
152
- return { entries: data.tree as TreeEntry[], truncated: data.truncated === true }
153
- }
154
- let whole: Awaited<ReturnType<TreeListing>>
155
- try {
156
- whole = await listing(commit, true)
157
- } catch (err) {
158
- if (err instanceof GithubApiError && (err.message === 'github-not-found' || err.message === 'github-status-422')) return null
159
- throw err
160
- }
160
+ const listing = treeListing(fullName, token, fetchImpl)
161
+ const whole = await orNoCommit(listing(commit, true))
162
+ if (!whole) return null
161
163
  const files: Blob[] = []
162
164
  let cut = false
163
165
  if (whole.truncated) cut = await treeByTrees(commit, listing, files)
@@ -250,18 +252,12 @@ export async function directoryFiles(fullName: string, token: string | null, com
250
252
  // (GET /repos/:owner/:repo/git/trees/:tree, its own entries alone); null
251
253
  // where it has none there, or GitHub has no such commit.
252
254
  async function directoryTree(fullName: string, token: string | null, commit: string, path: string, fetchImpl: typeof fetch): Promise<string | null> {
253
- const repo = `https://api.github.com/repos/${fullName.split('/').map(encodeURIComponent).join('/')}`
255
+ const listing = treeListing(fullName, token, fetchImpl)
254
256
  let tree = commit
255
257
  for (const name of path.split('/')) {
256
- let data: { tree?: unknown }
257
- try {
258
- data = await githubJson(`${repo}/git/trees/${tree}`, token, fetchImpl) as typeof data
259
- } catch (err) {
260
- if (err instanceof GithubApiError && (err.message === 'github-not-found' || err.message === 'github-status-422')) return null
261
- throw err
262
- }
263
- if (!Array.isArray(data?.tree)) throw new GithubApiError(502, 'github-malformed')
264
- const entry = (data.tree as TreeEntry[]).find(item => item?.path === name && item.type === 'tree')
258
+ const listed = await orNoCommit(listing(tree, false))
259
+ if (!listed) return null
260
+ const entry = listed.entries.find(item => item?.path === name && item.type === 'tree')
265
261
  if (typeof entry?.sha !== 'string' || !SHA.test(entry.sha)) return null
266
262
  tree = entry.sha
267
263
  }
@@ -269,7 +265,7 @@ async function directoryTree(fullName: string, token: string | null, commit: str
269
265
  }
270
266
 
271
267
  // The files of a tree within the directory `path` ('' the whole repository).
272
- export function treeWithin({ files, sizes, cut }: CommitTree, path: string): CommitTree {
268
+ function treeWithin({ files, sizes, cut }: CommitTree, path: string): CommitTree {
273
269
  if (path === '') return { files, sizes, cut }
274
270
  const within = [...files.keys()].filter(at => files[at]!.startsWith(`${path}/`))
275
271
  return { files: within.map(at => files[at]!), sizes: within.map(at => sizes[at]!), cut }
@@ -10,6 +10,7 @@ import { Buffer } from 'node:buffer'
10
10
  import { createHash } from 'node:crypto'
11
11
  import { encodeBrotli } from './brotli.ts'
12
12
  import { CacheMissError, type CacheStorage } from './cache-storage.ts'
13
+ import { SHA } from './github-values.ts'
13
14
  import type { KeptStore } from './npm-kept.ts'
14
15
  import { plainObject } from './npm-manifest.ts'
15
16
  import { MAX_NPM_JSON_LENGTH, NpmPackageError, npmFileRows } from './npm-packages.ts'
@@ -36,12 +37,12 @@ export function repositoryCodeFits(files: RepositoryCodeFiles | null): files is
36
37
  }
37
38
 
38
39
  // A directory's files' count and bytes, as GitHub lists its tree.
39
- export interface RepositoryCodeFiles { files: number; bytes: number }
40
+ interface RepositoryCodeFiles { files: number; bytes: number }
40
41
 
41
42
  // The directory read: the repository by its id and name, the commit, the
42
43
  // directory (`''` for the root), its tree's id, and its files as listed,
43
44
  // which weigh its load among the active ones.
44
- export interface RepositoryCodeInput { repoId: number; repo: string; commit: string; path: string; tree: string; listed: RepositoryCodeFiles }
45
+ interface RepositoryCodeInput { repoId: number; repo: string; commit: string; path: string; tree: string; listed: RepositoryCodeFiles }
45
46
 
46
47
  // A package's refusals, as a directory's: past the bounds, or an archive
47
48
  // @preventive/archive refuses, as it does one holding a symlink that climbs
@@ -86,11 +87,10 @@ const KEPT_CODE_VERSION = 1
86
87
  // invocation a while uploading it: it is sent as ever, and read again the
87
88
  // next time.
88
89
  export const MAX_KEPT_CODE_BYTES = 64 * 1024 * 1024
89
- const COMMIT = /^[a-f\d]{40}$/u
90
90
 
91
91
  // A directory as kept: the repository by its id and name, the commit and the
92
92
  // directory, as its body names them; and the head they are kept at.
93
- export type KeptCodeAt = Pick<RepositoryCodeInput, 'repoId' | 'repo' | 'commit' | 'path'>
93
+ type KeptCodeAt = Pick<RepositoryCodeInput, 'repoId' | 'repo' | 'commit' | 'path'>
94
94
  type KeptCodeHead = Pick<KeptCodeAt, 'commit' | 'repo'>
95
95
  // Under the repository, then the commit, so either goes by its prefix; the
96
96
  // repository's name and the directory hashed, as a key's parts are names.
@@ -160,7 +160,7 @@ export function repositoryCodeKept(storage: CacheStorage, heads: KeptStore<KeptC
160
160
  // resolved to `commit` with `defaultBranch` GitHub's, reads and keeps
161
161
  // its directories.
162
162
  async at({ repoId, repo, commit }: Omit<KeptCodeAt, 'path'>, ref: string, defaultBranch: string): Promise<boolean> {
163
- if (!COMMIT.test(commit)) return false
163
+ if (!SHA.test(commit)) return false
164
164
  const kept = await headOf(repoId)
165
165
  const atKept = kept?.commit === commit && kept.repo === repo
166
166
  if (ref !== '' && (defaultBranch === '' || ref !== `heads/${defaultBranch}`)) return atKept
@@ -13,13 +13,12 @@
13
13
  // or Accept with nits).
14
14
  import type { ManagedSql } from './sql.ts'
15
15
  import { type LockfileScope, scopeText, storedScope } from './lockfile-scope.ts'
16
- import { reviewsIn } from './dependency-reviews.ts'
16
+ import { reviewsIn, snapshotOf } from './dependency-reviews.ts'
17
17
  import { type ReviewVerdict, summarizeReview } from '../common/dependency-reviews.js'
18
18
 
19
19
  export const REPOSITORY_DEPENDENCY_REVIEW_COLUMNS = [['dependency_review', 'INTEGER NOT NULL DEFAULT 0'],
20
20
  ['dependency_reviews_required', 'INTEGER NOT NULL DEFAULT 1'], ['dependency_review_since', 'TEXT'], ['dependency_review_lockfiles', 'TEXT']] as const
21
21
  export const MAX_REQUIRED_REVIEWS = 10
22
- export const SINCE_COMMIT = /^[a-f\d]{40}$/u
23
22
 
24
23
  export interface RepoDependencyReview { enabled: boolean; required: number; since: string | null; lockfiles: LockfileScope }
25
24
  // A review published of the version it is of: its package, version and
@@ -92,19 +91,13 @@ async function publishedReviews(db: ManagedSql, repoId: number, versions: Review
92
91
  basePackage: string | null; baseVersion: string | null; files: string | null; status: ReviewVerdict; publishedAt: number }[])
93
92
  .filter(row => keys.has(`${row.package}@${row.version}`))
94
93
  if (rows.length === 0) continue
95
- const entries = new Map<string, { file: string; status: ReviewVerdict | null }[]>()
96
- for (const { reviewId, ...entry } of await db.prepare(`SELECT review_id AS reviewId, file, status FROM managed_dependency_file_review
97
- WHERE review_id IN (${rows.map(() => '?').join(',')})`).all(...rows.map(row => row.id)) as { reviewId: string; file: string; status: ReviewVerdict | null }[]) {
98
- const of = entries.get(reviewId)
99
- if (of) of.push(entry)
100
- else entries.set(reviewId, [entry])
101
- }
94
+ const read = await db.prepare(`SELECT review_id AS reviewId, file, status FROM managed_dependency_file_review
95
+ WHERE review_id IN (${rows.map(() => '?').join(',')})`).all(...rows.map(row => row.id)) as { reviewId: string; file: string; status: ReviewVerdict | null }[]
96
+ const entries = Map.groupBy(read, entry => entry.reviewId)
102
97
  for (const row of rows) {
103
- const snapshot = row.files === null ? null : JSON.parse(row.files) as string[] | { paths: string[]; nonTextFiles: string[] }
104
98
  // A snapshot of paths alone, before non-text files were told, can't be full.
105
- const files = Array.isArray(snapshot) ? snapshot : snapshot?.paths ?? null
106
- const nonText = Array.isArray(snapshot) ? null : snapshot?.nonTextFiles ?? []
107
- const full = summarizeReview(entries.get(row.id) ?? [], files, nonText).coverage === 'full'
99
+ const { files, nonTextFiles } = snapshotOf(row.files)
100
+ const full = summarizeReview(entries.get(row.id) ?? [], files, nonTextFiles).coverage === 'full'
108
101
  found.push({ id: row.id, package: row.package, version: row.version, integrity: row.integrity, ...row.patchHash ? { patchHash: row.patchHash } : {},
109
102
  basePackage: row.basePackage, baseVersion: row.baseVersion,
110
103
  reviewer: row.userId ?? `login:${row.userLogin.toLowerCase()}`, login: row.userLogin, status: row.status, full, time: Number(row.publishedAt) })
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import type { ManagedConfig } from './config.ts'
3
- import { GithubApiError, filterInstalledRepos, listInstalledRepos, listUserRepos } from './github-app.ts'
3
+ import { filterInstalledRepos, listInstalledRepos, listUserRepos } from './github-app.ts'
4
+ import { GithubApiError } from './github-errors.ts'
4
5
  import type { ConnectedRepo, RepoListing } from './github-app.ts'
5
6
 
6
7
  const CACHE_MS = 60_000