@preventive/triage 1.0.0-alpha.6 → 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 (409) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +17 -0
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +3 -0
  13. package/common/bundle-compare-diff.js +376 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-metadata.d.ts +15 -0
  20. package/common/bundle-metadata.js +226 -0
  21. package/common/bundle-pkg-of.d.ts +1 -0
  22. package/common/bundle-pkg-of.js +90 -0
  23. package/common/bundle-reasons.d.ts +2 -0
  24. package/common/bundle-reasons.js +21 -0
  25. package/common/bundle-source-links.d.ts +6 -0
  26. package/common/bundle-source-links.js +216 -0
  27. package/common/bundle-sourcemap.d.ts +10 -0
  28. package/common/bundle-sourcemap.js +100 -0
  29. package/common/bundle-sources.d.ts +7 -0
  30. package/common/bundle-sources.js +333 -0
  31. package/common/bundle-stats.js +41 -0
  32. package/common/bundle-tabs.js +1 -0
  33. package/common/code-language.js +65 -0
  34. package/common/default-scan-models.ts +36 -0
  35. package/common/dependency-reviews.d.ts +18 -0
  36. package/common/dependency-reviews.js +64 -0
  37. package/common/finding-duplicates.js +58 -0
  38. package/common/finding-filters.js +274 -0
  39. package/common/finding-id.js +47 -0
  40. package/common/finding-repo.d.ts +5 -0
  41. package/common/finding-repo.js +67 -0
  42. package/common/github-issue-labels.d.ts +1 -0
  43. package/common/github-issue-labels.js +11 -0
  44. package/common/github-pr.ts +56 -0
  45. package/common/gzip.js +59 -0
  46. package/common/line-diff.d.ts +8 -0
  47. package/common/line-diff.js +57 -0
  48. package/common/linked-workspace-groups.js +63 -0
  49. package/common/managed/agent-tasks.ts +292 -0
  50. package/common/managed/comments.ts +43 -0
  51. package/common/managed/finding-detail.d.ts +5 -0
  52. package/common/managed/finding-detail.js +75 -0
  53. package/common/managed/finding-values.d.ts +2 -0
  54. package/common/managed/finding-values.js +44 -0
  55. package/common/managed/github-agents.ts +114 -0
  56. package/common/managed/github-logins.ts +49 -0
  57. package/common/managed/lite-name.d.ts +2 -0
  58. package/common/managed/lite-name.js +20 -0
  59. package/common/managed/npm-packages.d.ts +7 -0
  60. package/common/managed/npm-packages.js +51 -0
  61. package/common/managed/permissions.ts +31 -0
  62. package/common/managed/report-content.ts +72 -0
  63. package/common/managed/report-filter.ts +120 -0
  64. package/common/managed/repository-alias.ts +65 -0
  65. package/common/managed/roles.ts +35 -0
  66. package/common/managed/routes.d.ts +2 -0
  67. package/common/managed/routes.js +363 -0
  68. package/common/managed/scan-models.ts +6 -0
  69. package/common/managed/team-app.d.ts +15 -0
  70. package/common/managed/team-app.js +100 -0
  71. package/common/managed/team-filters.js +26 -0
  72. package/common/managed/triage.ts +83 -0
  73. package/common/managed/upload-seal.ts +126 -0
  74. package/common/pretty-print.d.ts +5 -0
  75. package/common/pretty-print.js +24 -0
  76. package/common/repo-commit.d.ts +4 -0
  77. package/common/repo-commit.js +30 -0
  78. package/common/revalidation-conflicts.js +48 -0
  79. package/common/revalidation-input-groups.js +56 -0
  80. package/common/save-error-reason.ts +20 -7
  81. package/common/scan-server.ts +13 -0
  82. package/common/security-links.d.ts +5 -0
  83. package/common/security-links.js +33 -0
  84. package/common/server-info.ts +46 -0
  85. package/common/utf8.d.ts +3 -0
  86. package/common/utf8.js +45 -0
  87. package/common/workspace-app.js +71 -0
  88. package/common/workspace-groups.js +176 -0
  89. package/out/activity.js +4 -0
  90. package/out/brotli-fallback.js +3 -3
  91. package/out/chunk-2XUEZHIP.js +28 -0
  92. package/out/chunk-4EMM6UCD.js +1 -0
  93. package/out/chunk-4ISO5F7Y.js +7 -0
  94. package/out/chunk-4XIH7YTX.js +1 -0
  95. package/out/chunk-6CCSTJWB.js +1 -0
  96. package/out/chunk-74AEKRES.js +10 -0
  97. package/out/chunk-7BKKYVWR.js +7 -0
  98. package/out/chunk-7C7DWL7I.js +1 -0
  99. package/out/chunk-B3FNMHOE.js +1 -0
  100. package/out/chunk-BNH52UHC.js +2 -0
  101. package/out/chunk-BRO77PQY.js +42 -0
  102. package/out/chunk-C4Z6ZBXV.js +10 -0
  103. package/out/chunk-DEVAORP2.js +1 -0
  104. package/out/chunk-E3LFSUDJ.js +9 -0
  105. package/out/chunk-G3LY2FV4.js +1 -0
  106. package/out/chunk-GO7FT4OD.js +1 -0
  107. package/out/chunk-GRGIZOTP.js +4 -0
  108. package/out/chunk-HAZKDK4M.js +4 -0
  109. package/out/chunk-HOB3YPS5.js +1 -0
  110. package/out/chunk-IYPY47MC.js +1 -0
  111. package/out/chunk-IZ6MYRYB.js +3 -0
  112. package/out/chunk-J2FWBXFV.js +1 -0
  113. package/out/chunk-JCIIBLKR.js +1 -0
  114. package/out/chunk-JFL7WLRV.js +1 -0
  115. package/out/chunk-JJK5OZG2.js +15 -0
  116. package/out/chunk-JMG5DXII.js +2 -0
  117. package/out/chunk-JOXLZXMI.js +1 -0
  118. package/out/chunk-M37X4LCF.js +14 -0
  119. package/out/chunk-M3Y6SLC4.js +1 -0
  120. package/out/chunk-NRPC74AM.js +1 -0
  121. package/out/chunk-NXATZJQ2.js +1 -0
  122. package/out/chunk-OFZYEWBH.js +244 -0
  123. package/out/chunk-OIERSXON.js +1 -0
  124. package/out/chunk-OOJM4CTU.js +1 -0
  125. package/out/chunk-PAD2JHZT.js +1 -0
  126. package/out/chunk-PNHBZGDD.js +1 -0
  127. package/out/chunk-PTFQKLKO.js +1 -0
  128. package/out/chunk-PWFUOLZK.js +17 -0
  129. package/out/chunk-PXK7EU4V.js +1 -0
  130. package/out/chunk-QCOGVL37.js +52 -0
  131. package/out/chunk-QMVOEBWC.js +13 -0
  132. package/out/chunk-QRKFPLA4.js +80 -0
  133. package/out/chunk-R3NZFXVR.js +1 -0
  134. package/out/chunk-R5O6FAW4.js +2 -0
  135. package/out/chunk-RRBIJL2B.js +1 -0
  136. package/out/chunk-SYXT3SFP.js +2 -0
  137. package/out/chunk-TOXMUOIW.js +5 -0
  138. package/out/chunk-TUII34K2.js +1 -0
  139. package/out/chunk-UCP3JRE2.js +1 -0
  140. package/out/chunk-VFWMQ3LG.js +2 -0
  141. package/out/chunk-VRX2APNA.js +9 -0
  142. package/out/chunk-W3QFV4SP.js +3 -0
  143. package/out/chunk-W6VOKW2N.js +12 -0
  144. package/out/chunk-WCPJDAYA.js +10 -0
  145. package/out/chunk-WMFDQS2L.js +11 -0
  146. package/out/chunk-WREU7JAG.js +1 -0
  147. package/out/chunk-Y5ZHFNBD.js +2 -0
  148. package/out/chunk-YF4M5OCI.js +1 -0
  149. package/out/chunk-Z667U2UJ.js +1 -0
  150. package/out/chunk-ZQHLECTI.js +1 -0
  151. package/out/chunk-ZQNEWVGG.js +1 -0
  152. package/out/client-managed-import.js +4 -0
  153. package/out/client-managed.js +34 -0
  154. package/out/client-sync.js +11 -17
  155. package/out/compare.js +40 -0
  156. package/out/dialogs.js +40 -0
  157. package/out/github-issue-authorized.html +3 -0
  158. package/out/github-issue-authorized.js +1 -0
  159. package/out/graph.js +19 -4
  160. package/out/index.html +106 -8
  161. package/out/prism.js +14 -10
  162. package/out/scan.js +2 -0
  163. package/out/stasis.svg +20 -0
  164. package/out/terminal.js +366 -39
  165. package/out/view.css +1 -1
  166. package/out/view.js +19 -144
  167. package/package.json +383 -63
  168. package/risk/actions/findings.js +161 -0
  169. package/risk/actions/resolve.js +250 -0
  170. package/risk/actions/scripts/commands.js +182 -0
  171. package/risk/actions/scripts/grade.js +113 -0
  172. package/risk/actions/scripts/packages.js +123 -0
  173. package/risk/actions/scripts/shell.js +169 -0
  174. package/risk/actions/uses.js +76 -0
  175. package/risk/actions/workflow.js +110 -0
  176. package/risk/files/characters.js +196 -0
  177. package/risk/files/hosts.js +205 -0
  178. package/risk/files/readability.js +177 -0
  179. package/risk/files/runs-code.js +615 -0
  180. package/risk/files/script.js +118 -0
  181. package/risk/files/stamps.js +47 -0
  182. package/risk/index.d.ts +272 -0
  183. package/risk/index.js +11 -0
  184. package/risk/npm/assess.js +285 -0
  185. package/risk/npm/combined.js +68 -0
  186. package/risk/npm/compare.js +257 -0
  187. package/risk/npm/dependencies.js +172 -0
  188. package/risk/npm/diff.js +79 -0
  189. package/risk/npm/downloads.js +84 -0
  190. package/risk/npm/files.js +445 -0
  191. package/risk/npm/held.js +63 -0
  192. package/risk/npm/install-scripts.js +34 -0
  193. package/risk/npm/malware.js +38 -0
  194. package/risk/npm/manifest.js +65 -0
  195. package/risk/npm/new-dependency.js +60 -0
  196. package/risk/npm/old-version.js +108 -0
  197. package/risk/npm/registry.js +390 -0
  198. package/risk/npm/release.js +85 -0
  199. package/risk/npm/score.js +59 -0
  200. package/risk/npm/specs.js +124 -0
  201. package/risk/npm/tarball.js +96 -0
  202. package/server-common/database-config.ts +16 -0
  203. package/server-common/initialize.ts +18 -0
  204. package/server-common/npm-advisories.ts +101 -0
  205. package/{server → server-common}/origin.ts +5 -5
  206. package/server-common/reap.ts +48 -0
  207. package/server-common/scan-config.ts +19 -0
  208. package/server-common/standalone.ts +29 -0
  209. package/server-common/storage-crypto.ts +182 -0
  210. package/server-common/storage-log.ts +38 -0
  211. package/server-common/vercel-blob.ts +103 -0
  212. package/server-e2e/app.ts +487 -0
  213. package/{server → server-e2e}/bus-receiver.ts +2 -1
  214. package/{server → server-e2e}/cli.js +9 -4
  215. package/{server → server-e2e}/config.ts +50 -42
  216. package/{server → server-e2e}/db-neon.ts +2 -2
  217. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  218. package/{server → server-e2e}/db-stmt.ts +2 -2
  219. package/{server → server-e2e}/db.ts +7 -7
  220. package/{server → server-e2e}/http.ts +44 -13
  221. package/{server → server-e2e}/hub.ts +40 -9
  222. package/server-e2e/index.ts +17 -0
  223. package/server-e2e/lifecycle.ts +95 -0
  224. package/{server → server-e2e}/neon-driver.ts +2 -2
  225. package/{server → server-e2e}/npm-proxy.ts +12 -145
  226. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  227. package/{server → server-e2e}/objstore/blob.ts +1 -1
  228. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  229. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  230. package/{server → server-e2e}/objstore/init.ts +19 -27
  231. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  232. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  233. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  234. package/{server → server-e2e}/objstore/rest.ts +3 -3
  235. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  236. package/{server → server-e2e}/objstore/store.ts +7 -7
  237. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  238. package/{server → server-e2e}/pubsub.ts +12 -9
  239. package/{server → server-e2e}/sign.ts +4 -4
  240. package/{server → server-e2e}/sse-server.ts +60 -33
  241. package/{server → server-e2e}/static.ts +31 -21
  242. package/{server → server-e2e}/sync-handlers.ts +64 -30
  243. package/{server → server-e2e}/ws-server.ts +20 -9
  244. package/server-managed/activity.ts +238 -0
  245. package/server-managed/agent-merges.ts +109 -0
  246. package/server-managed/app-agents.ts +23 -0
  247. package/server-managed/avatar-store.ts +13 -0
  248. package/server-managed/blob-store.ts +26 -0
  249. package/server-managed/brotli.ts +10 -0
  250. package/server-managed/bundle-advisories.ts +103 -0
  251. package/server-managed/bundle-advisory-inventory.ts +77 -0
  252. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  253. package/server-managed/bundle-build-diagnostics.js +23 -0
  254. package/server-managed/bundle-build-leases.ts +41 -0
  255. package/server-managed/bundle-build-worker.js +238 -0
  256. package/server-managed/bundle-build.ts +240 -0
  257. package/server-managed/bundle-cache.ts +199 -0
  258. package/server-managed/bundle-catalog.ts +29 -0
  259. package/server-managed/bundle-commits.ts +133 -0
  260. package/server-managed/bundle-dependency-reviews.ts +68 -0
  261. package/server-managed/bundle-store.ts +24 -0
  262. package/server-managed/bundle-summary-cache.ts +139 -0
  263. package/server-managed/bundle-validation.ts +33 -0
  264. package/server-managed/bundle.ts +119 -0
  265. package/server-managed/cache-storage.ts +20 -0
  266. package/server-managed/cli.js +21 -0
  267. package/server-managed/combined.ts +43 -0
  268. package/server-managed/comments.ts +138 -0
  269. package/server-managed/commit-coauthors.ts +105 -0
  270. package/server-managed/commit-lockfiles.ts +77 -0
  271. package/server-managed/comparison.ts +50 -0
  272. package/server-managed/config.ts +163 -0
  273. package/server-managed/content-access.ts +15 -0
  274. package/server-managed/crypto.ts +25 -0
  275. package/server-managed/db-methods.ts +1877 -0
  276. package/server-managed/db-neon.ts +388 -0
  277. package/server-managed/db-schema.ts +253 -0
  278. package/server-managed/db-table-names.ts +22 -0
  279. package/server-managed/db.ts +146 -0
  280. package/server-managed/dependabot-access.ts +61 -0
  281. package/server-managed/dependabot-alerts.ts +180 -0
  282. package/server-managed/dependency-review-comments.ts +92 -0
  283. package/server-managed/dependency-reviews.ts +363 -0
  284. package/server-managed/github-accounts.ts +59 -0
  285. package/server-managed/github-actions.ts +71 -0
  286. package/server-managed/github-app.ts +347 -0
  287. package/server-managed/github-errors.ts +70 -0
  288. package/server-managed/github-graphql.ts +42 -0
  289. package/server-managed/github-issue-links.ts +264 -0
  290. package/server-managed/github-issue-oauth.ts +30 -0
  291. package/server-managed/github-issues.ts +157 -0
  292. package/server-managed/github-link-oauth.ts +56 -0
  293. package/server-managed/github-links.ts +204 -0
  294. package/server-managed/github-metadata.ts +213 -0
  295. package/server-managed/github-oauth.ts +264 -0
  296. package/server-managed/github-pulls.ts +257 -0
  297. package/server-managed/github-requests.ts +179 -0
  298. package/server-managed/github-users.ts +30 -0
  299. package/server-managed/github-values.ts +26 -0
  300. package/server-managed/history-windows.ts +172 -0
  301. package/server-managed/http-response.ts +76 -0
  302. package/server-managed/http.ts +5796 -0
  303. package/server-managed/import-triage.ts +51 -0
  304. package/server-managed/index.ts +204 -0
  305. package/server-managed/kept-briefly.ts +37 -0
  306. package/server-managed/kept.ts +28 -0
  307. package/server-managed/link-reports.ts +149 -0
  308. package/server-managed/listed-activity.ts +39 -0
  309. package/server-managed/locked-packages.ts +152 -0
  310. package/server-managed/lockfile-scope.ts +49 -0
  311. package/server-managed/lru.ts +30 -0
  312. package/server-managed/managed-issues.ts +92 -0
  313. package/server-managed/management-catalog.ts +45 -0
  314. package/server-managed/management.ts +110 -0
  315. package/server-managed/npm-delta-worker.js +23 -0
  316. package/server-managed/npm-delta.ts +159 -0
  317. package/server-managed/npm-insights.ts +455 -0
  318. package/server-managed/npm-kept.ts +234 -0
  319. package/server-managed/npm-loads.ts +259 -0
  320. package/server-managed/npm-manifest.ts +117 -0
  321. package/server-managed/npm-packages.ts +462 -0
  322. package/server-managed/npm-patch.ts +317 -0
  323. package/server-managed/npm-provenance.ts +127 -0
  324. package/server-managed/npm-risk.ts +287 -0
  325. package/server-managed/object-storage-disk.ts +147 -0
  326. package/server-managed/object-storage-vercel.ts +71 -0
  327. package/server-managed/object-storage.ts +82 -0
  328. package/server-managed/package-entry-points.ts +79 -0
  329. package/server-managed/pretty-print.ts +425 -0
  330. package/server-managed/public-workspace.ts +242 -0
  331. package/server-managed/pull-comment-reviews.ts +161 -0
  332. package/server-managed/pull-dependencies.ts +340 -0
  333. package/server-managed/pull-dependency-reviews.ts +327 -0
  334. package/server-managed/pull-reviews.ts +202 -0
  335. package/server-managed/queue.ts +53 -0
  336. package/server-managed/release-commits.ts +85 -0
  337. package/server-managed/rename-diff-worker.js +26 -0
  338. package/server-managed/rename-diff.ts +236 -0
  339. package/server-managed/repo-path.ts +21 -0
  340. package/server-managed/report-migration.ts +32 -0
  341. package/server-managed/report-query.ts +10 -0
  342. package/server-managed/report-response.ts +16 -0
  343. package/server-managed/report-sources.ts +181 -0
  344. package/server-managed/report-store.ts +77 -0
  345. package/server-managed/repository-actions.ts +220 -0
  346. package/server-managed/repository-agents.ts +422 -0
  347. package/server-managed/repository-aliases.ts +85 -0
  348. package/server-managed/repository-browser.ts +303 -0
  349. package/server-managed/repository-changes.ts +280 -0
  350. package/server-managed/repository-code.ts +215 -0
  351. package/server-managed/repository-dependency-reviews.ts +159 -0
  352. package/server-managed/repository-discovery.ts +83 -0
  353. package/server-managed/repository-history.ts +428 -0
  354. package/server-managed/repository-issues.ts +224 -0
  355. package/server-managed/repository-policy.ts +27 -0
  356. package/server-managed/repository-pulls.ts +207 -0
  357. package/server-managed/repository-pulse.ts +477 -0
  358. package/server-managed/repository-risk-assess.ts +108 -0
  359. package/server-managed/repository-risk-audit.ts +78 -0
  360. package/server-managed/repository-risk-read.ts +170 -0
  361. package/server-managed/repository-risk.ts +483 -0
  362. package/server-managed/repository-squashes.ts +160 -0
  363. package/server-managed/repository-stamp.ts +41 -0
  364. package/server-managed/request-timing.ts +63 -0
  365. package/server-managed/reviewed-dependencies.ts +149 -0
  366. package/server-managed/revisions.ts +35 -0
  367. package/server-managed/scan-downloads.ts +87 -0
  368. package/server-managed/session.ts +132 -0
  369. package/server-managed/slugs.ts +38 -0
  370. package/server-managed/solidity-entry-points.ts +71 -0
  371. package/server-managed/sql-postgres.ts +34 -0
  372. package/server-managed/sql.ts +107 -0
  373. package/server-managed/stasis-config.ts +55 -0
  374. package/server-managed/static.ts +28 -0
  375. package/server-managed/storage-command.ts +16 -0
  376. package/server-managed/storage-db.ts +183 -0
  377. package/server-managed/storage-encryption.ts +288 -0
  378. package/server-managed/storage-maintenance.ts +259 -0
  379. package/server-managed/storage-payload.ts +121 -0
  380. package/server-managed/storage-stores.ts +91 -0
  381. package/server-managed/storage.ts +82 -0
  382. package/server-managed/team-app-summaries.ts +54 -0
  383. package/server-managed/team-app.ts +154 -0
  384. package/server-managed/team-catalog.ts +7 -0
  385. package/server-managed/team-feed.ts +180 -0
  386. package/server-managed/team-npm-scopes.ts +103 -0
  387. package/server-managed/team-reports.ts +351 -0
  388. package/server-managed/triage-response.ts +16 -0
  389. package/server-managed/type-only-proof.js +108 -0
  390. package/server-managed/type-only-worker.js +31 -0
  391. package/server-managed/type-only.ts +115 -0
  392. package/server-managed/uploads.ts +106 -0
  393. package/server-managed/upstream-cache.ts +250 -0
  394. package/server-managed/view-as.ts +58 -0
  395. package/server-managed/worker-turns.ts +76 -0
  396. package/server-managed/workspace-shares.ts +170 -0
  397. package/server.ts +70 -0
  398. package/server/index.ts +0 -480
  399. package/server/lifecycle.ts +0 -208
  400. /package/{LICENSE → LICENSE-MIT} +0 -0
  401. /package/{server → server-e2e}/auth.ts +0 -0
  402. /package/{server → server-e2e}/config.example.json +0 -0
  403. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  404. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  405. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  406. /package/{server → server-e2e}/peer.ts +0 -0
  407. /package/{server → server-e2e}/sse-session.ts +0 -0
  408. /package/{server → server-e2e}/util.ts +0 -0
  409. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,428 @@
1
+ // The commit history the code viewer's History tab draws
2
+ // (GET /api/admin/repositories/history), as `git log --oneline --decorate
3
+ // --graph` shows it: each commit's id, parents, subject, author and time, and
4
+ // the branches and tags pointing at commits. From a revision, a page at a
5
+ // time, of the whole repository or of the commits touching a directory, as
6
+ // GitHub's REST API lists them, for any reader; or, as `--all`, across the
7
+ // repository's most recently committed to branches at once, then on from where
8
+ // those stop, in GraphQL queries, which need a token. A whole repository's is
9
+ // read a page from a commit at a time, each page kept by the commit it starts
10
+ // at (historyFrom): a commit's history never changes, and where a commit read
11
+ // starts a page kept, that page glues on, and those after it.
12
+ import { type AgentSignals, agentSignals } from '../common/managed/agent-tasks.ts'
13
+ import { githubAgent } from '../common/managed/github-agents.ts'
14
+ import { AGENT_MARKS_READ, APP_AGENTS } from './app-agents.ts'
15
+ import { type CommitFacts, MAX_COAUTHORS, type Maker, coauthorFacts, coauthorTrailers } from './commit-coauthors.ts'
16
+ import { GithubApiError } from './github-errors.ts'
17
+ import { type GraphActor, accountOf, commitAccount, linkNoreplyUsers } from './github-accounts.ts'
18
+ import { githubGraphql } from './github-graphql.ts'
19
+ import { githubJson, repoApi } from './github-requests.ts'
20
+ import { MAX_NAME, SHA, nameOf, timeOf } from './github-values.ts'
21
+ import { inTurns } from './queue.ts'
22
+
23
+ export const HISTORY_PAGE = 100
24
+ // The deepest page read, as far as Older commits goes.
25
+ export const MAX_HISTORY_PAGE = 100
26
+ // `--all`: the branches most recently committed to, of as many as fifty
27
+ // pages of them list, the latest commits of each (as many as a GraphQL connection
28
+ // gives), and the latest tags.
29
+ export const ALL_BRANCHES = 25
30
+ const MAX_HEAD_PAGES = 50
31
+ const ALL_DEPTH = 100
32
+ const ALL_TAGS = 100
33
+ const REF_TIPS = 100
34
+ const MAX_PARENTS = 8
35
+ const MAX_SUBJECT = 1000
36
+
37
+ // A commit, its author by name, address (`authorEmail`) and their account's
38
+ // login and numeric id (`authorId`), and who it names beside them
39
+ // (commit-coauthors.ts coauthorFacts), each absent from pages kept before it
40
+ // was read, with the lines it adds and removes and when it was authored in
41
+ // its author's own time zone (`authorZone`, minutes east of UTC), where
42
+ // GitHub's GraphQL API tells them (null where its REST API lists it); and the
43
+ // marks an agent left in its message, where any (messageMarks), by the rules
44
+ // they were read by (`marked`, AGENT_MARKS_READ; absent from pages kept
45
+ // before). What of them is an agent's is told as they are answered
46
+ // (coauthorsOf, historyMarks), never kept.
47
+ export interface HistoryCommit extends CommitFacts { sha: string; parents: string[]; subject: string; committedAt: number | null; additions?: number | null
48
+ deletions?: number | null; authoredAt?: number | null; authorZone?: number | null; marks?: AgentSignals; marked?: number }
49
+ interface HistoryRef { name: string; sha: string }
50
+
51
+ // The address Claude's own commits are authored with.
52
+ const CLAUDE_EMAIL = 'noreply@anthropic.com'
53
+
54
+ const marking = (marks: AgentSignals) => marks.claude || marks.codex || marks.agents.length > 0 || marks.sessions.length > 0 || marks.tasks.length > 0
55
+
56
+ // The marks an agent left in a commit's message (agent-tasks.ts
57
+ // agentSignals: sessions' and tasks' links, agents' lines and fingerprints),
58
+ // as its history keeps them; null for one none marked.
59
+ export function messageMarks(message: unknown): AgentSignals | null {
60
+ const marks = agentSignals([message], APP_AGENTS)
61
+ return marking(marks) ? marks : null
62
+ }
63
+
64
+ // The marks an agent left on a commit, as the Agents tab tells them: its
65
+ // message's (`marks`, messageMarks), its author an app agent's account, by
66
+ // the agents the app knows now, or Claude's address; null for one none marked.
67
+ export function commitMarks(marks: AgentSignals | null | undefined, { email, account }: Maker): AgentSignals | null {
68
+ const authored = account.login !== null && account.id !== null ? githubAgent(account.login, account.id) : null
69
+ const all = { sessions: marks?.sessions ?? [], tasks: marks?.tasks ?? [], claude: (marks?.claude ?? false) || email === CLAUDE_EMAIL, codex: marks?.codex ?? false,
70
+ agents: APP_AGENTS.flatMap(({ id }) => marks?.agents.includes(id) || authored === id ? [id] : []) }
71
+ return marking(all) ? all : null
72
+ }
73
+ // A commit's marks as its history keeps it (commitMarks).
74
+ export const historyMarks = (commit: HistoryCommit) => commitMarks(commit.marks,
75
+ { name: commit.authorName, email: commit.authorEmail, account: { login: commit.authorLogin, id: commit.authorId ?? null } })
76
+
77
+ const lineCount = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0 ? value as number : null
78
+ // The minutes east of UTC an ISO 8601 time is given in: `Z` none.
79
+ const zoneOf = (value: unknown) => {
80
+ const zone = typeof value === 'string' ? /(?:Z|([+-])(\d{2}):?(\d{2}))$/u.exec(value) : null
81
+ if (!zone) return null
82
+ return zone[1] ? (zone[1] === '-' ? -1 : 1) * (Number(zone[2]) * 60 + Number(zone[3])) : 0
83
+ }
84
+
85
+ // A commit as the Commits tab reads it, its subject the message's first
86
+ // line, as `--oneline` shows, its author by name and account, and its
87
+ // co-authors (coauthorsOf, `listed` as GitHub's GraphQL API lists them), and
88
+ // the marks an agent left on it, as the Agents tab reads them from the pages
89
+ // kept (commitMarks); null for one GitHub names no commit id for. With
90
+ // `stats`, the GraphQL API's, its lines and its author's time.
91
+ function historyCommit(sha: unknown, parents: unknown[], message: unknown, author: Maker, committedAt: unknown,
92
+ stats: { additions?: unknown; deletions?: unknown; authoredAt?: unknown } | null = null, listed: Maker[] | null = null): HistoryCommit | null {
93
+ if (typeof sha !== 'string' || !SHA.test(sha)) return null
94
+ const lines = stats ? { additions: lineCount(stats.additions), deletions: lineCount(stats.deletions), authoredAt: timeOf(stats.authoredAt),
95
+ authorZone: zoneOf(stats.authoredAt) } : { additions: null, deletions: null, authoredAt: null, authorZone: null }
96
+ const marks = messageMarks(message)
97
+ return {
98
+ sha,
99
+ parents: parents.filter((parent): parent is string => typeof parent === 'string' && SHA.test(parent)).slice(0, MAX_PARENTS),
100
+ subject: typeof message === 'string' ? message.replaceAll('\r\n', '\n').split('\n', 1)[0]!.trim().slice(0, MAX_SUBJECT) : '',
101
+ authorName: nameOf(author.name),
102
+ authorEmail: nameOf(author.email),
103
+ authorLogin: author.account.login,
104
+ authorId: author.account.id,
105
+ ...coauthorFacts(message, listed),
106
+ committedAt: timeOf(committedAt),
107
+ ...lines,
108
+ ...marks ? { marks } : {},
109
+ marked: AGENT_MARKS_READ,
110
+ }
111
+ }
112
+
113
+ type RestCommit = { sha?: unknown; parents?: { sha?: unknown }[]; author?: { login?: unknown; id?: unknown } | null
114
+ commit?: { message?: unknown; author?: { name?: unknown; email?: unknown } | null; committer?: { date?: unknown } | null } }
115
+ // Its co-authors (`listed`) by its trailers, with the accounts of their addresses.
116
+ const restCommit = (item: RestCommit, listed: Maker[] | null = null) => historyCommit(item?.sha, Array.isArray(item?.parents) ? item.parents.map(parent => parent?.sha) : [],
117
+ item?.commit?.message, { name: item?.commit?.author?.name, email: item?.commit?.author?.email, account: accountOf(item?.author) }, item?.commit?.committer?.date,
118
+ null, listed)
119
+
120
+ // A page of the commits `commit` reaches, newest first as GitHub lists them,
121
+ // those touching `path` alone where it names a directory; `more` where a
122
+ // full page leaves some for the next, one that may be read. GitHub links
123
+ // each's author to its account; with a token, its co-authors by GitHub's older
124
+ // no-reply address too (linkNoreplyUsers).
125
+ export async function repositoryHistory(fullName: string, token: string | null, commit: string, path: string, page: number, fetchImpl: typeof fetch = globalThis.fetch) {
126
+ const params = new URLSearchParams({ sha: commit, per_page: String(HISTORY_PAGE), page: String(page), ...path ? { path } : {} })
127
+ const data = await githubJson(`${repoApi(fullName)}/commits?${params}`, token, fetchImpl)
128
+ if (!Array.isArray(data)) throw new GithubApiError(502, 'github-malformed')
129
+ const items = data as RestCommit[]
130
+ const trailers = items.map(item => coauthorTrailers(item?.commit?.message).map(({ name, email }): GraphActor & { name: string } => ({ name, email, user: null })))
131
+ if (token) await linkNoreplyUsers(trailers.flat(), token, fetchImpl)
132
+ return { commits: items.flatMap((item, at) => restCommit(item, token ? trailers[at]!.map(actor => ({ name: actor.name, email: actor.email, account: commitAccount(actor) })) : null) ?? []),
133
+ more: data.length >= HISTORY_PAGE && page < MAX_HISTORY_PAGE }
134
+ }
135
+
136
+ // The commits the repository's branches and tags point at, as GitHub's
137
+ // first page of each lists them, to name commits by.
138
+ export async function repositoryRefTips(fullName: string, token: string | null, fetchImpl: typeof fetch = globalThis.fetch) {
139
+ const tips = (list: unknown): HistoryRef[] => Array.isArray(list) ? list.flatMap((item: { name?: unknown; commit?: { sha?: unknown } }) =>
140
+ typeof item?.name === 'string' && item.name && typeof item.commit?.sha === 'string' && SHA.test(item.commit.sha)
141
+ ? [{ name: item.name.slice(0, MAX_NAME), sha: item.commit.sha }] : []) : []
142
+ const [branches, tags] = await Promise.all(['branches', 'tags'].map(kind => githubJson(`${repoApi(fullName)}/${kind}?per_page=${REF_TIPS}`, token, fetchImpl)))
143
+ return { branches: tips(branches), tags: tips(tags) }
144
+ }
145
+
146
+ // A commit's author and those GitHub lists beside it.
147
+ export const commitActors = (node: GraphCommit | null | undefined) => [node?.author, ...node?.authors?.nodes ?? []]
148
+
149
+ // A tag's target, an annotated tag's own target in turn, through as many as
150
+ // MAX_TAG_DEPTH annotated tags, each object's type naming what it is.
151
+ const MAX_TAG_DEPTH = 4
152
+ const tagTarget = (tags: number): string => `target { __typename oid${tags > 0 ? ` ... on Tag { ${tagTarget(tags - 1)} }` : ''} }`
153
+
154
+ // The branches' tips, a page at a time, each with its commit's date (GitHub
155
+ // orders heads by name alone), and, on the first page, the default branch's
156
+ // tip, wherever its name sorts, and the latest tags.
157
+ const HEADS_QUERY = `query($owner: String!, $name: String!, $after: String, $tags: Int!, $first: Boolean!) {
158
+ repository(owner: $owner, name: $name) {
159
+ defaultBranchRef { name target { oid ... on Commit { committedDate } } }
160
+ branches: refs(refPrefix: "refs/heads/", first: 100, after: $after) {
161
+ pageInfo { hasNextPage endCursor }
162
+ nodes { name target { oid ... on Commit { committedDate } } }
163
+ }
164
+ tags: refs(refPrefix: "refs/tags/", first: $tags, orderBy: { field: TAG_COMMIT_DATE, direction: DESC }) @include(if: $first) {
165
+ nodes { name ${tagTarget(MAX_TAG_DEPTH)} }
166
+ }
167
+ }
168
+ }`
169
+
170
+ // As many commits as gluing kept pages on goes to, in as many rounds of
171
+ // looking them up, each looking up as many commits as tops.
172
+ export const HISTORY_GLUED = 2000
173
+ const MAX_GLUE_ROUNDS = 20
174
+ const GLUE_LOOKUP = 50
175
+
176
+ // The pages of a repository's history kept, each by the commit it starts at
177
+ // (its top): the first page of the history from that commit, which never
178
+ // changes.
179
+ export interface HistoryPages {
180
+ read(tops: string[]): Promise<Map<string, HistoryCommit[]>>
181
+ // The pages kept of `first`; where none is, those of `then`, in one read
182
+ // (`first` whether they are `first`'s). Without it, both are read together.
183
+ readFirst?(first: string[], then: string[]): Promise<{ first: boolean; pages: Map<string, HistoryCommit[]> }>
184
+ write(top: string, commits: HistoryCommit[]): Promise<void>
185
+ }
186
+
187
+ // What a commit is read by in GraphQL.
188
+ export const COMMIT_FRAGMENT = `fragment historyCommit on Commit { oid message committedDate additions deletions author { name email date user { login databaseId } }
189
+ authors(first: ${MAX_COAUTHORS + 1}) { nodes { name email user { login databaseId } } } parents(first: ${MAX_PARENTS}) { nodes { oid } } }`
190
+ // A query's variables `$<prefix><n>` of `type`, as many as `count`.
191
+ export const variablesOf = (prefix: string, count: number, type: string) => Array.from({ length: count }, (_, at) => `$${prefix}${at}: ${type}`).join(', ')
192
+ // A query of commits by their ids, `$o<n>` the `n`th's (commitIds), each read
193
+ // by `fields`, `<alias><n>` the `n`th.
194
+ export const commitsQuery = (count: number, alias: string, fields: string) => `query($owner: String!, $name: String!, ${variablesOf('o', count, 'GitObjectID!')}) {
195
+ repository(owner: $owner, name: $name) {
196
+ ${Array.from({ length: count }, (_, at) => `${alias}${at}: object(oid: $o${at}) { ... on Commit { ${fields} } }`).join('\n ')}
197
+ }
198
+ }`
199
+ // Its variables of `shas`: `$o<n>` the `n`th of them.
200
+ export const commitIds = (shas: string[]) => Object.fromEntries(shas.map((sha, at) => [`o${at}`, sha]))
201
+
202
+ // The latest commits of each tip, by its id, `b<n>` the `n`th's.
203
+ const historiesQuery = (count: number) => `${commitsQuery(count, 'b', `history(first: ${ALL_DEPTH}) { pageInfo { hasNextPage } nodes { ...historyCommit } }`)}
204
+ ${COMMIT_FRAGMENT}`
205
+
206
+ export type GraphCommit = { oid?: unknown; message?: unknown; committedDate?: unknown; additions?: unknown; deletions?: unknown
207
+ author?: ({ name?: unknown; date?: unknown } & GraphActor) | null; authors?: { nodes?: (({ name?: unknown } & GraphActor) | null)[] } | null
208
+ parents?: { nodes?: { oid?: unknown }[] } }
209
+ type GraphTarget = { __typename?: unknown; oid?: unknown; committedDate?: unknown; target?: GraphTarget | null }
210
+ type GraphRef = { name?: unknown; target?: GraphTarget | null }
211
+ type HeadsPage = { repository?: { defaultBranchRef?: GraphRef | null; branches?: Connection<GraphRef>; tags?: { nodes?: GraphRef[] } } | null }
212
+ type Histories = { repository?: Record<string, { history?: { pageInfo?: { hasNextPage?: unknown }; nodes?: GraphCommit[] } } | null> | null }
213
+
214
+ // A page of a connection, as GitHub's GraphQL API answers one: whether
215
+ // another follows and where, and its nodes.
216
+ export type Connection<T> = { pageInfo?: { hasNextPage?: unknown; endCursor?: unknown }; nodes?: (T | null)[] }
217
+ // Where a connection's next page starts, as its page tells it; null where
218
+ // none follows.
219
+ export const nextCursor = (page: { hasNextPage?: unknown; endCursor?: unknown } | null | undefined) =>
220
+ page?.hasNextPage === true && typeof page.endCursor === 'string' ? page.endCursor : null
221
+
222
+ // The repository's branches, as many as MAX_HEAD_PAGES of them list, each
223
+ // with its tip's time, its default branch and latest tags (an annotated tag
224
+ // by the commit it tags), and whether any branch is left out.
225
+ async function repositoryHeads(owner: string, name: string, token: string, fetchImpl: typeof fetch) {
226
+ const heads: (HistoryRef & { at: number | null })[] = []
227
+ let first: HeadsPage['repository'] = null
228
+ let after: string | null = null
229
+ for (let page = 0; page < MAX_HEAD_PAGES; page++) {
230
+ const data = await githubGraphql(HEADS_QUERY, { owner, name, after, tags: ALL_TAGS, first: page === 0 }, token, fetchImpl) as HeadsPage
231
+ const repository = data?.repository
232
+ if (!repository) throw new GithubApiError(404, 'github-not-found')
233
+ first ??= repository
234
+ for (const ref of repository.branches?.nodes ?? []) {
235
+ const sha = ref?.target?.oid
236
+ if (typeof ref?.name === 'string' && ref.name && typeof sha === 'string' && SHA.test(sha)) heads.push({ name: ref.name.slice(0, MAX_NAME), sha, at: timeOf(ref.target?.committedDate) })
237
+ }
238
+ after = nextCursor(repository.branches?.pageInfo)
239
+ if (after === null) return { heads, repository: first, cut: false }
240
+ }
241
+ return { heads, repository: first, cut: true }
242
+ }
243
+
244
+ // Histories read in a GraphQL query, and queries at once: each counts its
245
+ // commits' lines, which GitHub works out as it answers, stopping a query
246
+ // past ten seconds.
247
+ export const PAGES_PER_QUERY = 5
248
+ export const PAGES_PARALLEL = 5
249
+
250
+ // The first page of the history from each of `tops`, by its top, each told
251
+ // to `keep` as it is read, so those read stay kept where another fails: with
252
+ // a token, in GraphQL queries of PAGES_PER_QUERY (inBatches); without, a
253
+ // REST list each.
254
+ async function readPages(fullName: string, token: string | null, tops: string[], fetchImpl: typeof fetch,
255
+ keep: (top: string, commits: HistoryCommit[]) => Promise<void>) {
256
+ const read = new Map<string, HistoryCommit[]>()
257
+ const got = (top: string, commits: HistoryCommit[]) => { read.set(top, commits); return keep(top, commits) }
258
+ if (!token) {
259
+ await Promise.all(tops.map(async top => got(top, (await repositoryHistory(fullName, null, top, '', 1, fetchImpl)).commits)))
260
+ return read
261
+ }
262
+ const [owner, name] = fullName.split('/') as [string, string]
263
+ await inBatches(tops, PAGES_PER_QUERY, PAGES_PARALLEL, async batch => {
264
+ const data = await githubGraphql(historiesQuery(batch.length), { owner, name, ...commitIds(batch) }, token, fetchImpl) as Histories
265
+ const nodes = batch.map((_, at) => data?.repository?.[`b${at}`]?.history?.nodes ?? [])
266
+ await linkNoreplyUsers(nodes.flat().flatMap(commitActors), token, fetchImpl)
267
+ await Promise.all(batch.map((top, at) => got(top, nodes[at]!.flatMap(node => graphCommit(node) ?? []))))
268
+ })
269
+ return read
270
+ }
271
+
272
+ // Its authors past the first, the git author, GitHub lists from its
273
+ // `Co-authored-by:` trailers.
274
+ export const graphCommit = (node: GraphCommit | null | undefined) => historyCommit(node?.oid, (node?.parents?.nodes ?? []).map(parent => parent?.oid),
275
+ node?.message, { name: node?.author?.name, email: node?.author?.email, account: commitAccount(node?.author) }, node?.committedDate,
276
+ { additions: node?.additions, deletions: node?.deletions, authoredAt: node?.author?.date },
277
+ Array.isArray(node?.authors?.nodes) ? node.authors.nodes.slice(1).map(actor => ({ name: actor?.name, email: actor?.email, account: commitAccount(actor) })) : null)
278
+
279
+ // The history from each of `starts`, a page of each, kept (`pages`), or read
280
+ // and then kept by its top; glued on to it, the pages kept that start at a
281
+ // parent of a commit listed not listed, each adding commits none listed has,
282
+ // and, where any of those has none kept and readable, at a commit listed, the
283
+ // oldest first (where each goes on furthest; a page at a commit listed lists
284
+ // mostly commits listed already), GLUE_LOOKUP of each looked up at a time, in
285
+ // one read where none of those parents' is kept, else two, and
286
+ // those that start where those go on, till HISTORY_GLUED are listed. The
287
+ // pages from `starts` are listed whole, however many that is (all branches'
288
+ // first, as many as ALL_BRANCHES of them): the cap is gluing's. Each commit
289
+ // once, whether any goes on past those listed (`more`), and how many pages
290
+ // were read of GitHub (`read`).
291
+ export async function historyFrom(fullName: string, token: string | null, starts: string[], pages: HistoryPages, fetchImpl: typeof fetch = globalThis.fetch) {
292
+ const kept = await pages.read(starts)
293
+ const unread = starts.filter(top => !kept.has(top))
294
+ // Kept only as GitHub listed it from its top: none for a commit it named nothing of.
295
+ const keep = (top: string, commits: HistoryCommit[]) => commits[0]?.sha === top ? pages.write(top, commits) : Promise.resolve()
296
+ const read = unread.length > 0 ? await readPages(fullName, token, unread, fetchImpl, keep) : new Map<string, HistoryCommit[]>()
297
+ const listed = new Map<string, HistoryCommit>()
298
+ const add = (commits: HistoryCommit[]) => { for (const commit of commits) if (!listed.has(commit.sha)) listed.set(commit.sha, commit) }
299
+ for (const top of starts) add(kept.get(top) ?? read.get(top) ?? [])
300
+ const looked = new Set(starts)
301
+ for (let round = 0; round < MAX_GLUE_ROUNDS && listed.size < HISTORY_GLUED; round++) {
302
+ const parents = [...new Set([...listed.values()].flatMap(commit => commit.parents.filter(parent => !listed.has(parent) && !looked.has(parent))))].slice(0, GLUE_LOOKUP)
303
+ const within = [...listed.keys()].toReversed().filter(sha => !looked.has(sha)).slice(0, GLUE_LOOKUP)
304
+ if (parents.length === 0 && within.length === 0) break
305
+ // Without readFirst, GLUE_LOOKUP of both at once, the parents first.
306
+ const asked = pages.readFirst ? null : [...parents, ...within].slice(0, GLUE_LOOKUP)
307
+ let { first, pages: glued } = asked ? { first: false, pages: await pages.read(asked) } : await pages.readFirst!(parents, within)
308
+ // A parent with no page kept, or none readable (one GitHub's REST API
309
+ // listed, read with GraphQL), its line going on only by a page at a
310
+ // commit listed: those read too, apart, the others' lines notwithstanding.
311
+ if (first && glued.size < parents.length && within.length > 0) {
312
+ glued = new Map([...glued, ...await pages.read(within)])
313
+ first = false
314
+ }
315
+ // Those at commits listed, unread where a parent's answered, are looked up again.
316
+ for (const sha of asked ?? (first ? parents : [...parents, ...within])) looked.add(sha)
317
+ for (const commit of [...glued.values()].flat()) {
318
+ if (listed.size >= HISTORY_GLUED) break
319
+ if (!listed.has(commit.sha)) listed.set(commit.sha, commit)
320
+ }
321
+ }
322
+ const commits = [...listed.values()]
323
+ return { commits, more: commits.some(commit => commit.parents.some(parent => !listed.has(parent))), read: unread.length }
324
+ }
325
+
326
+ export type AllHeads = { heads: (HistoryRef & { at: number | null })[]; defaultBranch: string | null; tags: HistoryRef[]; cut: boolean }
327
+
328
+ // `--all`'s branches: the repository's, as many as MAX_HEAD_PAGES of them
329
+ // list, each with its tip's time, its default branch among them wherever its
330
+ // name sorts; its latest tags, each by the commit it tags; and whether
331
+ // branches past those listed are left out (`cut`).
332
+ export async function repositoryAllHeads(fullName: string, token: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<AllHeads> {
333
+ const [owner, name] = fullName.split('/') as [string, string]
334
+ const { heads, repository, cut } = await repositoryHeads(owner, name, token, fetchImpl)
335
+ const defaultBranch = nameOf(repository?.defaultBranchRef?.name)
336
+ // The default branch, where its name sorts past the heads read.
337
+ const defaultTip = repository?.defaultBranchRef?.target?.oid
338
+ if (defaultBranch && typeof defaultTip === 'string' && SHA.test(defaultTip) && !heads.some(head => head.name === defaultBranch)) {
339
+ heads.push({ name: defaultBranch, sha: defaultTip, at: timeOf(repository?.defaultBranchRef?.target?.committedDate) })
340
+ }
341
+ // A tag by the commit it tags, through the annotated tags between; one
342
+ // ending at no commit names none.
343
+ const tags = (repository?.tags?.nodes ?? []).flatMap(ref => {
344
+ let target = ref?.target
345
+ while (target?.__typename === 'Tag') target = target.target
346
+ const sha = target?.__typename === 'Commit' ? target.oid : null
347
+ return typeof ref?.name === 'string' && typeof sha === 'string' && SHA.test(sha) ? [{ name: ref.name.slice(0, MAX_NAME), sha }] : []
348
+ })
349
+ return { heads, defaultBranch, tags, cut }
350
+ }
351
+
352
+ // `--all`: the latest commits of the most recently committed to of `heads`
353
+ // (repositoryAllHeads), the default branch's among them, each commit once
354
+ // (historyFrom); the branches naming them and the latest tags; the branches
355
+ // not read, newest first, whose tips none of those is (`unread`), where
356
+ // reading on goes; whether branches past those listed are left out, never to
357
+ // be read (`cut`); and whether any is left out (`more`).
358
+ export async function repositoryAllHistory(fullName: string, token: string, { heads, defaultBranch, tags, cut }: AllHeads, pages: HistoryPages,
359
+ fetchImpl: typeof fetch = globalThis.fetch) {
360
+ const newest = heads.toSorted((a, b) => Number(b.name === defaultBranch) - Number(a.name === defaultBranch) || (b.at ?? 0) - (a.at ?? 0))
361
+ const shown = newest.slice(0, ALL_BRANCHES)
362
+ const read = await historyFrom(fullName, token, [...new Set(shown.map(head => head.sha))], pages, fetchImpl)
363
+ const listed = new Set(read.commits.map(commit => commit.sha))
364
+ const more = cut || heads.length > shown.length || read.more
365
+ // Every branch naming a commit listed, those not read among them.
366
+ const branches = heads.flatMap(({ name: branch, sha }) => listed.has(sha) ? [{ name: branch, sha }] : [])
367
+ const unread = newest.slice(ALL_BRANCHES).filter(head => !listed.has(head.sha))
368
+ return { commits: read.commits, branches, tags, defaultBranch, unread, cut, more }
369
+ }
370
+
371
+ const chunked = <T>(items: T[], size: number) => Array.from({ length: Math.ceil(items.length / size) }, (_, at) => items.slice(at * size, (at + 1) * size))
372
+ // GitHub stopping a query past its time: in its answer's errors, or as a 502
373
+ // or 504 of its own.
374
+ const SLOW = new Set(['github-timeout', 'github-status-502', 'github-status-504'])
375
+ // `run` for `items` in batches of `size`, as many at once as `parallel`; a
376
+ // batch GitHub stops past its time run again in halves, down to one alone,
377
+ // so that one too slow to read fails alone, the others read. The halves
378
+ // wait their turn with the rest, and as many batches are halved as run at
379
+ // once twice over at most, GitHub slow throughout past that. Where one
380
+ // fails, none more is run, those running done before its error is thrown,
381
+ // so that what they read is kept.
382
+ export async function inBatches<T>(items: T[], size: number, parallel: number, run: (batch: T[]) => Promise<void>) {
383
+ const failed: unknown[] = []
384
+ const inTurn = inTurns(parallel)
385
+ let halved = 0
386
+ const attempt = async (batch: T[]): Promise<void> => {
387
+ // Whether it is run again in halves, once its turn is done.
388
+ const halve = await inTurn(async () => {
389
+ try {
390
+ if (failed.length === 0) await run(batch)
391
+ return false
392
+ } catch (err) {
393
+ if (batch.length === 1 || halved >= 2 * parallel || !(err instanceof GithubApiError && SLOW.has(err.message))) { failed.push(err); return false }
394
+ halved++
395
+ return true
396
+ }
397
+ })
398
+ if (!halve) return
399
+ const half = Math.ceil(batch.length / 2)
400
+ await Promise.all([attempt(batch.slice(0, half)), attempt(batch.slice(half))])
401
+ }
402
+ await Promise.all(chunked(items, size).map(attempt))
403
+ if (failed.length > 0) throw failed[0]
404
+ }
405
+
406
+ // The open pull requests most recently updated, each by the commit its head
407
+ // is at, to name commits by.
408
+ const OPEN_PULLS = 100
409
+ const OPEN_PULLS_QUERY = `query($owner: String!, $name: String!) {
410
+ repository(owner: $owner, name: $name) {
411
+ pullRequests(states: OPEN, first: ${OPEN_PULLS}, orderBy: { field: UPDATED_AT, direction: DESC }) { nodes { number headRefOid } }
412
+ }
413
+ }`
414
+ export async function openPullHeads(fullName: string, token: string, fetchImpl: typeof fetch = globalThis.fetch) {
415
+ const [owner, name] = fullName.split('/') as [string, string]
416
+ const data = await githubGraphql(OPEN_PULLS_QUERY, { owner, name }, token, fetchImpl) as
417
+ { repository?: { pullRequests?: { nodes?: ({ number?: unknown; headRefOid?: unknown } | null)[] } } | null }
418
+ return { pulls: (data?.repository?.pullRequests?.nodes ?? []).flatMap(node => Number.isSafeInteger(node?.number) && (node!.number as number) > 0
419
+ && typeof node!.headRefOid === 'string' && SHA.test(node!.headRefOid) ? [{ number: node!.number as number, sha: node!.headRefOid }] : []) }
420
+ }
421
+
422
+ // Where `--all` reads on from, as a request names them (`from`): as many
423
+ // commit ids, each once, as branches are read at first; null for none, or
424
+ // for one that isn't a commit id.
425
+ export function historyStarts(from: string): string[] | null {
426
+ const starts = [...new Set(from.split(','))]
427
+ return starts.length <= ALL_BRANCHES && starts.every(sha => SHA.test(sha)) ? starts : null
428
+ }