@preventive/triage 1.0.0-alpha.77 → 1.0.0-alpha.79

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 (63) hide show
  1. package/common/line-diff.d.ts +2 -0
  2. package/common/line-diff.js +54 -0
  3. package/common/managed/dependency-routes.js +25 -0
  4. package/common/managed/finding-values.d.ts +2 -2
  5. package/common/managed/finding-values.js +128 -34
  6. package/common/managed/routes.js +9 -12
  7. package/common/pretty-json.js +95 -0
  8. package/common/pretty-print.d.ts +1 -0
  9. package/common/pretty-print.js +6 -0
  10. package/common/whitespace-insensitive.js +19 -0
  11. package/out/activity.js +2 -2
  12. package/out/{chunk-OCE6KQGJ.js → chunk-26W3E5JE.js} +1 -1
  13. package/out/chunk-3S4YWYOM.js +1 -0
  14. package/out/{chunk-OQS2USZM.js → chunk-55YIWY3H.js} +1 -1
  15. package/out/{chunk-IVDE66N5.js → chunk-6VXEPL32.js} +1 -1
  16. package/out/{chunk-XVKDPU4D.js → chunk-6Y6PZ2BU.js} +1 -1
  17. package/out/{chunk-S5PPXPAT.js → chunk-ATT2QA77.js} +1 -1
  18. package/out/{chunk-2V6Q4ZOZ.js → chunk-B64CTMVU.js} +1 -1
  19. package/out/{chunk-EXQQ5VQJ.js → chunk-BEKYZCPX.js} +1 -1
  20. package/out/{chunk-S2ZIKK45.js → chunk-EEJA7JBI.js} +1 -1
  21. package/out/{chunk-4IW3VD3H.js → chunk-FSU2PLJL.js} +1 -1
  22. package/out/{chunk-N7TD27UJ.js → chunk-IIJK4F4U.js} +1 -1
  23. package/out/{chunk-I6UQQKAH.js → chunk-LVSLM7HB.js} +1 -1
  24. package/out/{chunk-T6EXDRB7.js → chunk-MKX6JODK.js} +1 -1
  25. package/out/chunk-NTJJIEHS.js +259 -0
  26. package/out/{chunk-NEFCZAIY.js → chunk-PKLVXUEI.js} +1 -1
  27. package/out/chunk-QBIUW5EF.js +2 -0
  28. package/out/{chunk-ADMVRLNP.js → chunk-QD3IBSF4.js} +1 -1
  29. package/out/{chunk-GSNSP3EF.js → chunk-RPNO56H2.js} +1 -1
  30. package/out/{chunk-QBFT2DDR.js → chunk-UR4WYMIP.js} +1 -1
  31. package/out/{chunk-5DWOFBKS.js → chunk-V43XH2JQ.js} +1 -1
  32. package/out/{chunk-UH6NZBSU.js → chunk-VHEXSGGP.js} +1 -1
  33. package/out/chunk-XLX6XXJF.js +1 -0
  34. package/out/{chunk-BXQCCW7F.js → chunk-XM4RLC4A.js} +1 -1
  35. package/out/chunk-Z54AXVCK.js +3 -0
  36. package/out/client-managed-import.js +1 -1
  37. package/out/client-managed.js +4 -4
  38. package/out/compare.js +14 -14
  39. package/out/dialogs.js +37 -37
  40. package/out/graph.js +1 -1
  41. package/out/index.html +9 -7
  42. package/out/scan.js +2 -2
  43. package/out/terminal.js +7 -7
  44. package/out/view.css +1 -1
  45. package/out/view.js +8 -8
  46. package/package.json +8 -2
  47. package/server-managed/dependency-review-comments.ts +17 -10
  48. package/server-managed/http.ts +83 -19
  49. package/server-managed/npm-delta-worker.js +58 -12
  50. package/server-managed/npm-delta.ts +52 -28
  51. package/server-managed/npm-kept.ts +11 -1
  52. package/server-managed/pretty-copies.ts +22 -0
  53. package/server-managed/pretty-format.d.ts +3 -0
  54. package/server-managed/pretty-format.js +13 -0
  55. package/server-managed/pretty-print.ts +34 -24
  56. package/server-managed/public-workspace.ts +1 -1
  57. package/server-managed/team-reports.ts +25 -15
  58. package/out/chunk-G6YPDPW7.js +0 -2
  59. package/out/chunk-JCIIBLKR.js +0 -1
  60. package/out/chunk-SDLETN3Z.js +0 -3
  61. package/out/chunk-WGQ7D5DB.js +0 -1
  62. package/out/chunk-Z6DL5PPO.js +0 -255
  63. /package/out/{chunk-Z667U2UJ.js → chunk-SZWPYLPC.js} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.77",
3
+ "version": "1.0.0-alpha.79",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -173,6 +173,9 @@
173
173
  "server-managed/npm-patch-paths.ts",
174
174
  "server-managed/npm-patch.ts",
175
175
  "server-managed/package-entry-points.ts",
176
+ "server-managed/pretty-copies.ts",
177
+ "server-managed/pretty-format.d.ts",
178
+ "server-managed/pretty-format.js",
176
179
  "server-managed/pretty-print.ts",
177
180
  "server-managed/pull-reviews.ts",
178
181
  "server-managed/rename-diff.ts",
@@ -294,6 +297,7 @@
294
297
  "common/github-issue-labels.js",
295
298
  "common/github-issue-labels.d.ts",
296
299
  "common/gzip.js",
300
+ "common/pretty-json.js",
297
301
  "common/pretty-print.d.ts",
298
302
  "common/pretty-print.js",
299
303
  "common/line-diff.d.ts",
@@ -301,6 +305,7 @@
301
305
  "common/linked-workspace-groups.js",
302
306
  "common/managed/agent-tasks.ts",
303
307
  "common/managed/comments.ts",
308
+ "common/managed/dependency-routes.js",
304
309
  "common/managed/directory-packages.ts",
305
310
  "common/managed/finding-detail.d.ts",
306
311
  "common/managed/finding-detail.js",
@@ -343,6 +348,7 @@
343
348
  "common/stasis-tgz.js",
344
349
  "common/utf8.d.ts",
345
350
  "common/utf8.js",
351
+ "common/whitespace-insensitive.js",
346
352
  "common/workspace-app.js",
347
353
  "common/workspace-groups.js",
348
354
  "risk/index.js",
@@ -446,7 +452,7 @@
446
452
  "@exodus/stasis": "1.0.0-rc.10",
447
453
  "@exodus/stasis-core": "1.0.0-rc.10",
448
454
  "@preventive/archive": "^1.4.1",
449
- "@preventive/compare": "^1.2.15",
455
+ "@preventive/compare": "^1.3.0",
450
456
  "@preventive/diff": "^1.1.1",
451
457
  "@preventive/lockfile": "^1.3.1",
452
458
  "@preventive/publishers": "^1.1.0",
@@ -14,7 +14,7 @@ import type { PullDependencies } from './pull-dependencies.ts'
14
14
  import { ACCEPTING, askedOf, basesOf, comparedWith, latestOf, reviewsByVersion, reviewsOf } from './pull-dependency-reviews.ts'
15
15
  import { eachOf } from './queue.ts'
16
16
  import type { PublishedReview, RepoReviewState } from './repository-dependency-reviews.ts'
17
- import { type DependencyReviewEntry, type ReviewedBase, type ReviewedDependencies, askReviewed } from './reviewed-dependencies.ts'
17
+ import { type DependencyReviewEntry, type ReviewVerdict, type ReviewedBase, type ReviewedDependencies, askReviewed } from './reviewed-dependencies.ts'
18
18
 
19
19
  const FORMAT_AT_ONCE = 8
20
20
  // The longest comment told, past which none is.
@@ -78,6 +78,9 @@ export function withFormatted<T extends DependencyReview>(reviewed: ReviewedDepe
78
78
  // before a latest not accepting it, whatever that was compared with, as it
79
79
  // holds them all.
80
80
  interface Own { review: PublishedReview; pkgs: LockedPackage[] }
81
+ // What a verdict does to a version's review, as pull-dependency-reviews.ts
82
+ // stancesOf counts it: passes it, holds it rejected, or passes it by none.
83
+ const effectOf = (status: ReviewVerdict) => ACCEPTING.has(status) ? 'passes' : status === 'reject' ? 'holds' : 'withholds'
81
84
  function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string, any: boolean, bases: Map<string, ReviewedBase>): Map<string, Own> {
82
85
  // Theirs by the version they are of, each version probed once.
83
86
  const theirs = reviewsByVersion(reviews.filter(review => review.id !== undefined && review.reviewer === user))
@@ -106,14 +109,16 @@ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: str
106
109
  // there, as copying it would but repeat what `user` posted there, or undo a
107
110
  // later word of theirs holding it: the host's `lookup` passes it already; or
108
111
  // `user`'s own comments there (of `commented`, the reviews its comments
109
- // make) stand where it does, by their latest of it, the first of those as
110
- // late (as pull-dependency-reviews.ts stancesOf reads them), with its
111
- // verdict, or, later than it, not accepting what it accepts. Where their
112
- // latest comment stands elsewhere, an older one with its verdict leaves it
113
- // in: posted again, it stands. A version `lookup` fails to answer of keeps
114
- // its review. Where the host reads reviews of comments (`parseComments`),
115
- // what a review was compared with is its to weigh, so one compared with any
116
- // version is given.
112
+ // make) stand on it, by their latest of it, the first of those as late (as
113
+ // pull-dependency-reviews.ts stancesOf reads them), as it does (effectOf):
114
+ // accepting it with nits or without alike, as a host may read one verdict of
115
+ // a comment for each version it tells, which posting it again would but
116
+ // repeat. Or, later than it, they don't accept what it accepts, but where
117
+ // those as late tell its verdict too, posted beside another of an older
118
+ // review, which, standing first, posting it again sets right. A version
119
+ // `lookup` fails to answer of keeps its review. Where the host reads reviews
120
+ // of comments (`parseComments`), what a review was compared with is its to
121
+ // weigh, so one compared with any version is given.
117
122
  export async function formattedPull(reviewed: ReviewedDependencies | null, db: Pick<DependencyReviewStore, 'listOwnDependencyReviewsById'>, user: string,
118
123
  told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = [],
119
124
  bases: Map<string, ReviewedBase> = new Map()): Promise<string | null> {
@@ -126,7 +131,9 @@ export async function formattedPull(reviewed: ReviewedDependencies | null, db: P
126
131
  const made = reviewsOf(pkg, there)
127
132
  if (made.length === 0) return false
128
133
  const stance = latestOf(made)
129
- return stance.status === review.status || (stance.time > review.time && !ACCEPTING.has(stance.status) && ACCEPTING.has(review.status))
134
+ if (effectOf(stance.status) === effectOf(review.status)) return true
135
+ return stance.time > review.time && !ACCEPTING.has(stance.status) && ACCEPTING.has(review.status)
136
+ && !made.some(one => one.time === stance.time && one.status === review.status)
130
137
  }
131
138
  const ids = [...mine].filter(([, { review, pkgs }]) => pkgs.some(pkg => !passed.has(askedOf(pkg)[0]) && !posted(review, pkg))).map(([id]) => id)
132
139
  if (ids.length === 0) return null
@@ -89,7 +89,8 @@
89
89
  // GET /api/bundles/<id>/validation → its last validation the reader may see, else none; POST validates it anew: its own code
90
90
  // as GitHub has it at its commit, its dependencies as upstream's packages have them, those covering every file | 401/403/404/409/422/429/502
91
91
  // GET /api/bundles/<id>/download → authorized original upload | 401/404
92
- // GET /api/bundles/<id>/pretty?path=&hash= → one of its files pretty-printed, Brotli-encoded | 400/401/404/409/413/422/429
92
+ // GET /api/bundles/<id>/pretty?path=&hash= → one of its files pretty-printed, `{ text, blank }` (its layout blank lines),
93
+ // Brotli-encoded JSON | 400/401/404/409/413/422/429
93
94
  // GET /api/bundles/<id>/pretty?other= → the files that changed between it and another bundle, both sides' pretty-printed,
94
95
  // Brotli-encoded ndjson | 400/401/404/422/503
95
96
  // GET /api/bundles/<id>/rename-diff?path=&hash=&other=&otherPath=&otherHash= → a JavaScript file diffed with another
@@ -134,7 +135,7 @@
134
135
  // GET /api/npm/pretty?name=&version= → every one of its files that needs it pretty-printed, Brotli-encoded ndjson | 400/401/404/413/429/502/503
135
136
  // GET /api/npm/pretty?name=&version=&otherVersion= → the files that changed between it and another version, both sides'
136
137
  // pretty-printed, Brotli-encoded ndjson | 400/401/404/413/429/502/503
137
- // GET /api/npm/pretty?name=&version=&path=&hash= → one of its files pretty-printed, Brotli-encoded | 400/401/404/409/413/422/429/502/503
138
+ // GET /api/npm/pretty?name=&version=&path=&hash= → one of its files pretty-printed, as a bundle's is, Brotli-encoded JSON | 400/401/404/409/413/422/429/502/503
138
139
  // GET /api/npm/rename-diff?name=&version=&path=&hash=&otherVersion=&otherPath=&otherHash= → a JavaScript file diffed with
139
140
  // another version's, both pretty-printed, renamed names hidden, whitespace changes shown and hidden | 400/401/404/409/413/422/429/502/503/504
140
141
  // GET /api/npm/rename-diff?name=&version=&otherVersion= → every pair of their JavaScript files the viewer diffs so,
@@ -143,7 +144,7 @@
143
144
  // or with otherVersion (empty) of the version against no files, each added, as Review reads one with no base; and
144
145
  // with runs=1 those in types alone but for what runs, Brotli-encoded ndjson | 400/401/404/413/429/501/502/503
145
146
  // GET /api/npm/delta?name=&version=&otherVersion= → the lines a version adds and removes against another, or `(empty)`, and
146
- // those but for declaration files changed in types alone, where any are, and whether binary files changed
147
+ // those of each file as Compare draws it with the fewest (`best`), and whether binary files changed
147
148
  // | 400/401/404/413/422/429/502/503/504
148
149
  // GET /api/npm/risk?name=&version=&otherVersion= → what calls for a look at a version, as risk tells it, against another where given | 400/401/404/413/429/502
149
150
  // POST /api/auth/logout → same-origin + CSRF, drops the session (and any view)
@@ -157,7 +158,7 @@ import { setTimeout as delay } from 'node:timers/promises'
157
158
  import { type KeptStore, REPOSITORY_READ_KEPT_MS, authoredCommitStore, branchTipStore, bundleValidationStore, codeHeadStore, codeTreeStore, commitPullStore, githubTagStore, historyChangeStore, historyPageStore, historySquashStore, historyTreeStore,
158
159
  issueListStore, lockfileReadStore,
159
160
  npmDeltaStore, npmPublishTimeStore, npmVersionDeltaStore, npmVersionStore, ownKeptPrunes, patchStore, pullDependencyStore, pullListStore, repositoryReadStore, reviewBaselineStore, riskLineStore,
160
- scanReadStore, stasisDependencyStore } from './npm-kept.ts'
161
+ scanReadStore, stasisDependencyStore, teamDependencyStore } from './npm-kept.ts'
161
162
  import { plainObject } from './npm-manifest.ts'
162
163
  import { type NpmDelta, deltaKey, keptNpmDeltas, keptVersionDeltas, npmDelta, versionDeltaKey } from './npm-delta.ts'
163
164
  import { ADVISORIES_TIMEOUT_MS, fetchBundleAdvisories } from './bundle-advisories.ts'
@@ -280,6 +281,7 @@ import { npmProvenance } from './npm-provenance.ts'
280
281
  import { npmReadyScanDownload, npmReadyScanDownloads, npmRisk, npmRiskRemoved } from './npm-risk.ts'
281
282
  import { NpmRiskError } from '../risk/index.js'
282
283
  import { type ComparedSide, type PrettyCache, PrettyError, type PrettyRequest, compared, prettyRequest, prettyText } from './pretty-print.ts'
284
+ import { npmCopies } from './pretty-copies.ts'
283
285
  import { renameDiffOf, renameDiffRequest, renamedPairs } from './rename-diff.ts'
284
286
  import { runsAsked, typeOnlyFiles } from './type-only.ts'
285
287
  import { comparisonBody, emptySide, npmComparedSide, patchedVersionBody } from './comparison.ts'
@@ -2913,7 +2915,11 @@ async function handleRepositoryLockfiles(res: ServerResponse, deps: ManagedHttpD
2913
2915
  // once, GitHub asked nothing of them; each read with GitHub has its access
2914
2916
  // checked again after (readWholeRepositoryOf), and the reader's session
2915
2917
  // before each line, their team and grants before each telling a
2916
- // repository's.
2918
+ // repository's. Each repository's lines, once all were told, are kept for
2919
+ // its reader (teamDependencyStore, keptTeamRepository); with `kept=1`, those
2920
+ // kept of the repositories it reads are told first, together, one line each
2921
+ // (`{ repoId, kept, branch, pulls, dependencies }`, `kept` when they were
2922
+ // read), before it is read again, for the tab to show them meanwhile.
2917
2923
  const TEAM_REPOSITORIES_AT_ONCE = 4
2918
2924
  const TEAM_DEPENDENCIES_MS = 240_000
2919
2925
  const TEAM_PULL_PAGES = 20
@@ -2943,7 +2949,9 @@ async function handleTeamDependencies(res: ServerResponse, deps: ManagedHttpDeps
2943
2949
  const every = { branch: query.get('branches') === 'all', draft: query.get('drafts') === 'all' }
2944
2950
  const named = query.get('repoIds')
2945
2951
  const only = named === null ? null : new Set(named.split(',').map(Number))
2946
- if (only && (only.size === 0 || only.size > 1000 || [...only].some(id => !Number.isSafeInteger(id) || id <= 0))) { sendJson(res, 400, { error: 'bad-request' }); return }
2952
+ if ((only && (only.size === 0 || only.size > 1000 || [...only].some(id => !Number.isSafeInteger(id) || id <= 0))) || !['1', null].includes(query.get('kept'))) {
2953
+ sendJson(res, 400, { error: 'bad-request' }); return
2954
+ }
2947
2955
  const snapshot = await teamSnapshot(deps.db, s.session.id, teamId)
2948
2956
  const repoIds = [...new Set(snapshot.repositories.map(repo => repo.repoId))].filter(id => !only || only.has(id))
2949
2957
  const grants = await repositoryGrants(deps, s.user)
@@ -2961,8 +2969,10 @@ async function handleTeamDependencies(res: ServerResponse, deps: ManagedHttpDeps
2961
2969
  if (now?.user.id !== s.user.id || !roleAtLeast(now.user.role, 'view')) stopped = true
2962
2970
  const telling = lines.filter(line => line.repoId !== undefined && (line['branch'] || line['dependencies'])).map(line => line.repoId!)
2963
2971
  if (!stopped && telling.length > 0 && !await stillReads(now!.user, telling)) stopped = true
2964
- // With the app's users its reviewers are, as a repository's activity is told.
2965
- for (const line of lines) if (stopped || !await out.write(line['branch'] || line['dependencies'] ? await withAppUsers(deps.db, line) : line)) stopped = true
2972
+ // With the app's users its reviewers are, as a repository's activity is
2973
+ // told, those of lines told together looked up at once.
2974
+ const shown = stopped ? [] : await Promise.all(lines.map(line => line['branch'] || line['dependencies'] ? withAppUsers(deps.db, line) : line))
2975
+ for (const line of shown) if (stopped || !await out.write(line)) stopped = true
2966
2976
  if (stopped) out.cut()
2967
2977
  return !stopped
2968
2978
  }
@@ -2982,7 +2992,8 @@ async function handleTeamDependencies(res: ServerResponse, deps: ManagedHttpDeps
2982
2992
  if ('error' in access || !setting?.enabled) answered.push({ repoId, branch: null })
2983
2993
  else reading.push({ access, setting })
2984
2994
  }
2985
- if (answered.length > 0 && !await send(...answered)) return
2995
+ const kept = query.get('kept') === '1' ? await keptTeamLines(deps, reading, every) : []
2996
+ if (answered.length + kept.length > 0 && !await send(...answered, ...kept)) return
2986
2997
  const done = await eachOf(reading, TEAM_REPOSITORIES_AT_ONCE, ({ access, setting }) => stopped || Date.now() > deadline ? Promise.resolve(false)
2987
2998
  : teamRepositoryDependencies(deps, access, setting, deadline, send, () => wholeRepositoryAccess(deps, cookie, access.repo.repoId), every))
2988
2999
  if (stopped) return
@@ -3021,13 +3032,66 @@ async function handleTeamReviewChanges(req: IncomingMessage, res: ServerResponse
3021
3032
  sendJson(res, 200, { now, versions: changed.map(({ name, version }) => [name, version]) })
3022
3033
  }
3023
3034
 
3035
+ // What a team's Dependencies keeps of a repository it told whole to a
3036
+ // reader (teamDependencyStore): its default branch's line, its pull
3037
+ // requests' dependencies told (those GitHub failed left out, as still to be
3038
+ // told), and the lines their versions change, each once. By the reader and
3039
+ // their role, the repository, its review's setting, so that one set anew
3040
+ // tells none kept before, and what was asked (`every`).
3041
+ type KeptTeamRepository = { branch: object; pulls: object; dependencies: object[]; deltas: unknown[] }
3042
+ const TEAM_KEPT_VERSION = 1
3043
+ const teamKeptKey = (user: StoredUser, repoId: number, setting: RepoDependencyReview, every: TeamEvery) =>
3044
+ JSON.stringify([TEAM_KEPT_VERSION, user.id, user.role, repoId, setting, every.branch, every.draft])
3045
+ const keptTeamStore = (deps: ManagedHttpDeps) => teamDependencyStore<KeptTeamRepository>(deps.db, deps.config.debug)
3046
+
3047
+ // The lines kept of those of `reading` its reader was told whole before,
3048
+ // one a repository, in one read of the database: `kept` when its read began.
3049
+ async function keptTeamLines(deps: ManagedHttpDeps, reading: { access: WholeAccess; setting: RepoDependencyReview }[], every: TeamEvery): Promise<TeamDependencyLine[]> {
3050
+ if (reading.length === 0) return []
3051
+ const keys = reading.map(({ access, setting }) => teamKeptKey(access.user, access.repo.repoId, setting, every))
3052
+ const hits = await keptTeamStore(deps).readMany(keys)
3053
+ return reading.flatMap(({ access }, at) => {
3054
+ const hit = hits.get(keys[at]!)
3055
+ const value = hit?.value as Partial<KeptTeamRepository> | undefined
3056
+ if (!hit || !plainObject(value?.branch) || !plainObject(value.pulls) || !Array.isArray(value.dependencies)) return []
3057
+ return [{ repoId: access.repo.repoId, kept: hit.at, branch: value.branch, pulls: value.pulls, dependencies: value.dependencies,
3058
+ ...Array.isArray(value.deltas) && value.deltas.length > 0 ? { deltas: value.deltas } : {} }]
3059
+ })
3060
+ }
3061
+
3062
+ // The repository a read told `told` of, kept as told whole (KeptTeamRepository),
3063
+ // as of when it `began`; one told no review in effect, or why it couldn't be
3064
+ // read, kept no more, lest a reader be shown what no longer reads.
3065
+ async function keepTeamRepository(deps: ManagedHttpDeps, key: string, told: TeamDependencyLine[], began: number) {
3066
+ const store = keptTeamStore(deps)
3067
+ const head = told.find(line => line['branch'] !== undefined || line['error'] !== undefined)
3068
+ if (!head?.['branch'] || !plainObject(head['pulls'])) { await store.remove(key); return }
3069
+ const dependencies = told.flatMap(line => Array.isArray(line['dependencies']) ? line['dependencies'] as { error?: unknown }[] : []).filter(answer => answer.error === undefined)
3070
+ const deltas = new Map<string, unknown>()
3071
+ for (const line of told) {
3072
+ for (const delta of Array.isArray(line['deltas']) ? line['deltas'] as unknown[][] : []) deltas.set(JSON.stringify(delta.slice(0, 3)), delta)
3073
+ }
3074
+ await store.write(key, { branch: head['branch'] as object, pulls: head['pulls'], dependencies, deltas: [...deltas.values()] }, began)
3075
+ }
3076
+
3024
3077
  // A repository's lines of its team's Dependencies, as handleTeamDependencies
3025
- // tells them; whether all were written, none left for its time.
3078
+ // tells them; whether all were written, none left for its time. Kept for its
3079
+ // reader once all were (keepTeamRepository), what was kept before kept still
3080
+ // where they weren't.
3026
3081
  async function teamRepositoryDependencies(deps: ManagedHttpDeps, access: WholeAccess, setting: RepoDependencyReview, deadline: number,
3027
3082
  send: (...lines: TeamDependencyLine[]) => Promise<boolean>, reauthorize: () => Promise<WholeAccess | Refusal>, every: TeamEvery = DEFAULT_ONLY): Promise<boolean> {
3028
3083
  // The Stasis builds its answers want, asked for a batch of pull requests at a time, its default branch's with the first.
3029
3084
  const wants: StasisWant[] = []
3030
- try { return await teamRepositoryLines(deps, access, setting, deadline, send, reauthorize, wants, every) } finally { stasisReader(deps).build(wants) }
3085
+ const began = Date.now(), told: TeamDependencyLine[] = []
3086
+ const telling = (...lines: TeamDependencyLine[]) => {
3087
+ told.push(...lines)
3088
+ return send(...lines)
3089
+ }
3090
+ try {
3091
+ const whole = await teamRepositoryLines(deps, access, setting, deadline, telling, reauthorize, wants, every)
3092
+ if (whole) await keepTeamRepository(deps, teamKeptKey(access.user, access.repo.repoId, setting, every), told, began)
3093
+ return whole
3094
+ } finally { stasisReader(deps).build(wants) }
3031
3095
  }
3032
3096
  async function teamRepositoryLines(deps: ManagedHttpDeps, access: WholeAccess, setting: RepoDependencyReview, deadline: number,
3033
3097
  send: (...lines: TeamDependencyLine[]) => Promise<boolean>, reauthorize: () => Promise<WholeAccess | Refusal>, wants: StasisWant[], every: TeamEvery): Promise<boolean> {
@@ -5441,7 +5505,7 @@ const MAX_ASKED_DELTAS = 50
5441
5505
  const DELTAS_AT_ONCE = 2
5442
5506
  // A version as npmDelta takes it: its integrity, and its files, loaded as
5443
5507
  // they are asked for and released once read.
5444
- const deltaSide = (doc: NpmVersionDocument) => ({ integrity: doc.dist.integrity, files: async () => {
5508
+ const deltaSide = (doc: NpmVersionDocument, npm?: CacheStorage) => ({ integrity: doc.dist.integrity, copies: npm ? npmCopies(npm, doc) : null, files: async () => {
5445
5509
  const load = loadNpmFiles(doc)
5446
5510
  try { return await load.result } finally { load.release() }
5447
5511
  } })
@@ -5479,10 +5543,10 @@ async function handleNpmDeltas(req: IncomingMessage, res: ServerResponse, deps:
5479
5543
  isPrivate = doc.private
5480
5544
  oldPrivate = old?.private === true
5481
5545
  const patched = patch && await (patches.get(patch.hash) ?? patches.set(patch.hash, npmPatchOf(deps, cookie, patch)).get(patch.hash)!)
5482
- const side = deltaSide(doc)
5546
+ const side = deltaSide(doc, deps.npmCacheStorage)
5483
5547
  if (patched && 'error' in patched) line = { ...asOne, error: patched.error, status: patched.status }
5484
5548
  else {
5485
- const delta = await npmDelta(old ? deltaSide(old) : null,
5549
+ const delta = await npmDelta(old ? deltaSide(old, deps.npmCacheStorage) : null,
5486
5550
  patched ? { integrity: `${side.integrity} patch:${patch.hash}`, files: async () => patchedFiles(await side.files(), patched.files) } : side, kept)
5487
5551
  if (!patched && !doc.private && !old?.private) await byVersions.write(versionDeltaKey(doc.name, doc.version, old?.name ?? name, old?.version ?? '(empty)'), delta, Date.now())
5488
5552
  line = { ...asOne, ...delta }
@@ -5642,12 +5706,12 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
5642
5706
  }
5643
5707
  if (path === NPM_PROVENANCE_PATH) { await reply(doc.private, { name, version: doc.version, provenance: await provenanceOf() }); return }
5644
5708
  // The lines it changes against `otherVersion`, or `(empty)`, its whole
5645
- // package's, and those but for declaration files changed in types alone
5646
- // (npm-delta.ts), as a list of versions wanting reviews tells them.
5709
+ // package's, and those of each file at its fewest (npm-delta.ts), as a
5710
+ // list of versions wanting reviews tells them.
5647
5711
  if (path === NPM_DELTA_PATH) {
5648
5712
  const old = otherSpec === '(empty)' ? null : await otherDoc()
5649
5713
  dropIdle(res)
5650
- const delta = await npmDelta(old ? deltaSide(old) : null, deltaSide(doc), npmDeltaStore<NpmDelta>(deps.db, deps.config.debug))
5714
+ const delta = await npmDelta(old ? deltaSide(old, deps.npmCacheStorage) : null, deltaSide(doc, deps.npmCacheStorage), npmDeltaStore<NpmDelta>(deps.db, deps.config.debug))
5651
5715
  await reply(doc.private || old?.private === true, { name, version: doc.version, otherVersion: old?.version ?? null, ...delta })
5652
5716
  return
5653
5717
  }
@@ -5693,7 +5757,7 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
5693
5757
  if (!deps.prettyCache) { sendJson(res, 503, { error: 'unavailable' }); return }
5694
5758
  const copy = await deps.prettyCache.npm(doc, file)
5695
5759
  if (!(await recheck(doc.private))) { copy.stream.destroy(); return }
5696
- await sendEncoded(req, res, copy, 'text/plain; charset=utf-8', prettySource(file))
5760
+ await sendEncoded(req, res, copy, 'application/json', prettySource(file))
5697
5761
  return
5698
5762
  }
5699
5763
  // Against another version, the pairs of its files that changed that the
@@ -6084,7 +6148,7 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
6084
6148
  if (part !== 'pretty') { await handleBundleCache(req, res, deps, session, id, bundleCache && (rec => bundleCache.open(rec, part as BundleCachePart))); return }
6085
6149
  const file = prettyRequest(url.searchParams)
6086
6150
  if (!file) { sendJson(res, 400, { error: 'bad-file' }); return }
6087
- await handleBundleCache(req, res, deps, session, id, prettyCache && (rec => prettyCache.bundle(rec, file)), 'text/plain; charset=utf-8', prettySource(file))
6151
+ await handleBundleCache(req, res, deps, session, id, prettyCache && (rec => prettyCache.bundle(rec, file)), 'application/json', prettySource(file))
6088
6152
  return
6089
6153
  }
6090
6154
  if (path === BUNDLE_CREATE_PATH) {
@@ -1,23 +1,69 @@
1
1
  // The lines a package's files change from one side to another (npm-delta.ts),
2
2
  // as @preventive/compare's compareTrees counts them (git's --numstat), off
3
3
  // the server's event loop: of its text files, renames found as git finds
4
- // them, a side not there empty; and, apart, those of its changes it stamps
5
- // `typeOnly`, declaration files changed in types alone.
4
+ // them, a side not there empty; and each file's fewest (`best`), as Compare
5
+ // can draw it: as published, without type-only and whitespace changes, or
6
+ // pretty-printed too: by Compare's copies where kept (`copies`), else made and
7
+ // told (`made`), as `complete` where none was left for want of time.
6
8
  import { parentPort, workerData } from 'node:worker_threads'
7
9
  import { compareTrees } from '@preventive/compare'
10
+ import { changeBlocks, indentHiddenBlocks, withSharedBlankLines } from '../common/line-diff.js'
11
+ import { jsonPrinted, prettyJsonText } from '../common/pretty-json.js'
12
+ import { prettyExtension, printableSize } from '../common/pretty-print.js'
13
+ import { whitespaceInsensitive } from '../common/whitespace-insensitive.js'
14
+ import { prettyFormat } from './pretty-format.js'
15
+
16
+ const { base, copies, other, prettyUntil } = workerData
17
+ const kept = new Map(copies.map(([at, path, copy]) => [`${at}\0${path}`, copy])), made = []
18
+ const NONE = { additions: 0, deletions: 0 }
19
+ const least = (a, b) => (b.additions < a.additions || (b.additions === a.additions && b.deletions < a.deletions) ? b : a)
20
+ const counted = (before, after, insensitive) => (insensitive ? indentHiddenBlocks(before, after) : changeBlocks(before, after))
21
+ .reduce((sum, { a0, a1, b0, b1 }) => ({ additions: sum.additions + b1 - b0, deletions: sum.deletions + a1 - a0 }), NONE)
22
+
23
+ // A side's file (`at` 0 the base, 1 the other) as Compare's pretty-print toggle prints it, or null.
24
+ async function printed(at, path, text) {
25
+ const copy = kept.get(`${at}\0${path}`)
26
+ if (copy) return copy
27
+ try {
28
+ if (!printableSize(text)) return null
29
+ const extension = prettyExtension(path), json = jsonPrinted(path) ? prettyJsonText(text, { width: 0 }) : null
30
+ if (json !== null) return { text: json, blank: [] }
31
+ const result = extension && await prettyFormat(text, extension)
32
+ if (!result || 'error' in result) return null
33
+ made.push([at, path, result])
34
+ return result
35
+ } catch {
36
+ return null
37
+ }
38
+ }
8
39
 
9
40
  const tree = files => files.map(([name, data]) => ({ name, data }))
10
- const changes = compareTrees(tree(workerData.base), tree(workerData.other), { paths: 'keys', lines: true, renames: true })
11
- const answer = { additions: 0, deletions: 0, typeAdditions: 0, typeDeletions: 0, typeFiles: 0 }
12
- for (const change of changes) {
41
+ const best = { ...NONE }, printing = [], total = { ...NONE }
42
+ for (const change of compareTrees(tree(base), tree(other), { paths: 'keys', lines: true, renames: true })) {
13
43
  if (change.binary) continue
14
- answer.additions += change.insertions ?? 0
15
- answer.deletions += change.deletions ?? 0
16
- if (change.typeOnly !== true) continue
17
- answer.typeAdditions += change.insertions ?? 0
18
- answer.typeDeletions += change.deletions ?? 0
19
- answer.typeFiles++
44
+ const published = { additions: change.insertions ?? 0, deletions: change.deletions ?? 0 }
45
+ const after = change.new?.data ?? '', before = change.old?.data ?? ''
46
+ const insensitive = before !== '' && after !== '' && whitespaceInsensitive(change.old.path, before) && whitespaceInsensitive(change.new.path, after)
47
+ // Additions less deletions is the same for any diff, so one with none of either is at its least.
48
+ const fewest = change.typeOnly ? NONE : insensitive && published.additions && published.deletions ? least(published, counted(before, after, true)) : published
49
+ for (const [sum, count] of [[total, published], [best, fewest]]) {
50
+ sum.additions += count.additions
51
+ sum.deletions += count.deletions
52
+ }
53
+ // Compare prints a file one side alone has only where that lengthens it.
54
+ if (fewest.additions + fewest.deletions > 0 && before !== '' && after !== '') printing.push({ from: change.old.path, to: change.new.path, before, after, insensitive, fewest })
55
+ }
56
+ // Smallest first, so the time left goes to the most files.
57
+ let complete = true
58
+ for (const file of printing.toSorted((a, b) => a.before.length + a.after.length - b.before.length - b.after.length)) {
59
+ if (Date.now() >= prettyUntil) { complete = false; break }
60
+ const [a, b] = [await printed(0, file.from, file.before), await printed(1, file.to, file.after)]
61
+ if (a === null || b === null) continue
62
+ const { before, after } = withSharedBlankLines(a.text, b.text, a.blank, b.blank)
63
+ const now = least(file.fewest, counted(before, after, file.insensitive))
64
+ best.additions += now.additions - file.fewest.additions
65
+ best.deletions += now.deletions - file.fewest.deletions
20
66
  }
21
67
  // Node worker messages have no browser target origin.
22
68
  // oxlint-disable-next-line unicorn/require-post-message-target-origin
23
- parentPort.postMessage(answer)
69
+ parentPort.postMessage({ ...total, best, complete, made })
@@ -2,33 +2,41 @@
2
2
  // its whole package's (GET /api/npm/delta), as a list of versions wanting
3
3
  // reviews tells them beside each: added and removed (`additions`,
4
4
  // `deletions`), as git's --numstat counts them, of their text files, a
5
- // renamed one diffed with what it was; and, where some of the files changed
6
- // are declaration files @preventive/compare's compareTrees proves changed in
7
- // types alone (`typeOnly`, proveTypeOnly: types and comments alone erased,
8
- // the runtime they leave as it was, an added one's empty or a single bare
9
- // `export {}`), those of the rest (`typeless`), what a reviewer may pass by
10
- // leaving those out; and whether a binary file, which they count none of,
5
+ // renamed one diffed with what it was; each file's fewest as Compare can
6
+ // draw it (`best`); and whether a binary file, which they count none of,
11
7
  // was added, removed or changed (`binary`), one moved as it was not. Worked
12
8
  // out in a worker, off the event loop, as many at once per process as
13
9
  // MAX_ACTIVE, both sides' files read together only once their turn has come,
14
10
  // those waiting past MAX_WAITING refused, each waiting a minute at most and
15
11
  // counting in a minute at most; one asked again meanwhile sharing the
16
12
  // first's; and kept by both sides' integrities, in this instance and beyond
17
- // it (`kept`), what a version holds never changing. Access is the caller's
18
- // to check.
13
+ // it (`kept`), what a version holds never changing, but for one whose copies
14
+ // weren't all printed in time (`partial`). Its pretty-printed copies are
15
+ // Compare's, read and kept as Compare keeps them (`copies`). Access is the
16
+ // caller's to check.
19
17
  import { createHash } from 'node:crypto'
18
+ import { layoutBlankList, prettyExtension } from '../common/pretty-print.js'
20
19
  import { type KeptStore, VERSION_DELTA_KEPT_MS } from './npm-kept.ts'
21
20
  import { type Lru, lru } from './lru.ts'
22
21
  import { NpmPackageError, type NpmPackageFile, npmFileText } from './npm-packages.ts'
22
+ import { PRETTY_VERSION, type PrettyCopy } from './pretty-format.js'
23
+ import type { KeptCopies } from './pretty-copies.ts'
24
+ import { eachOf } from './queue.ts'
23
25
  import { workerTurns } from './worker-turns.ts'
24
26
 
25
- export interface NpmDelta { additions: number; deletions: number; typeless: { additions: number; deletions: number } | null; binary: boolean }
27
+ export interface NpmDelta { additions: number; deletions: number; best: { additions: number; deletions: number }; binary: boolean; partial?: true }
26
28
 
27
29
  const MAX_ACTIVE = 2
28
30
  const MAX_WAITING = 64
29
31
  const DELTA_TIMEOUT_MS = 60_000
32
+ // No file is begun pretty-printing in this last part of it, as one may take seconds.
33
+ const PRETTY_MARGIN_MS = 15_000
30
34
  // The text the two sides may hold together, past which none is counted.
31
35
  const MAX_TEXT_LENGTH = 64 * 1024 * 1024
36
+ // Bumped when what a delta counts changes; its keys carry it and PRETTY_VERSION, so none counted otherwise is read.
37
+ const DELTA_VERSION = 1
38
+ const COUNTING = `v${DELTA_VERSION}.${PRETTY_VERSION}`
39
+ const COPIES_AT_ONCE = 8
32
40
 
33
41
  const deltas: Lru<NpmDelta> = lru(20_000)
34
42
  const working = new Map<string, Promise<NpmDelta>>()
@@ -37,22 +45,25 @@ const workers = workerTurns({ what: 'package delta', active: MAX_ACTIVE, waiting
37
45
 
38
46
  const lines = (told: unknown): told is { additions: number; deletions: number } => typeof told === 'object' && told !== null
39
47
  && Number.isSafeInteger((told as { additions?: unknown }).additions) && Number.isSafeInteger((told as { deletions?: unknown }).deletions)
40
- // A delta as kept, none where it isn't one, or was kept before it told of
41
- // binary files.
48
+ // A delta as kept, none where it isn't one, or is partial.
42
49
  function deltaOf(told: unknown): NpmDelta | null {
43
50
  if (!lines(told)) return null
44
- const { typeless, binary } = told as { typeless?: unknown; binary?: unknown }
45
- return (typeless === null || lines(typeless)) && typeof binary === 'boolean' ? { additions: told.additions, deletions: told.deletions, typeless, binary } : null
51
+ const { best, binary, partial } = told as { best?: unknown; binary?: unknown; partial?: unknown }
52
+ return lines(best) && typeof binary === 'boolean' && partial === undefined
53
+ ? { additions: told.additions, deletions: told.deletions, best: { additions: best.additions, deletions: best.deletions }, binary } : null
46
54
  }
47
55
 
48
- type Counted = { additions: number; deletions: number; typeAdditions: number; typeDeletions: number; typeFiles: number }
49
- const isCounted = (told: unknown): told is Counted => typeof told === 'object' && told !== null
50
- && ['additions', 'deletions', 'typeAdditions', 'typeDeletions', 'typeFiles'].every(key => Number.isSafeInteger((told as Record<string, unknown>)[key]))
56
+ // A copy by side (0 the base, 1 the other) and path, as the worker reads and makes them.
57
+ type SideCopy = [number, string, PrettyCopy]
58
+ type Counted = Omit<NpmDelta, 'binary' | 'partial'> & { complete: boolean; made: SideCopy[] }
59
+ const isCounted = (told: unknown): told is Counted => lines(told) && lines((told as { best?: unknown }).best)
60
+ && typeof (told as { complete?: unknown }).complete === 'boolean' && Array.isArray((told as { made?: unknown }).made)
61
+ const isCopy = (copy: unknown): copy is PrettyCopy => typeof (copy as { text?: unknown } | null)?.text === 'string' && layoutBlankList((copy as { blank?: unknown }).blank) !== null
51
62
 
52
- // What the worker counts of `base` against `other`, each its text files' paths and texts.
53
- function counted(base: [string, string][], other: [string, string][], deadline: number): Promise<Counted> {
63
+ // What the worker counts of `base` against `other`, each its text files' paths and texts, given the copies kept.
64
+ function counted(base: [string, string][], other: [string, string][], copies: SideCopy[], deadline: number): Promise<Counted> {
54
65
  return workers.run(new URL('./npm-delta-worker.js', import.meta.url), {
55
- workerData: { base, other }, execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1536 },
66
+ workerData: { base, other, copies, prettyUntil: deadline - PRETTY_MARGIN_MS }, execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1536 },
56
67
  }, told => (isCounted(told) ? told : null), deadline)
57
68
  }
58
69
 
@@ -100,15 +111,15 @@ function binaryChanged(olds: NpmPackageFile[], news: NpmPackageFile[]): boolean
100
111
  })
101
112
  }
102
113
 
103
- type Side = { integrity: string; files: () => Promise<NpmPackageFile[]> }
114
+ type Side = { integrity: string; files: () => Promise<NpmPackageFile[]>; copies?: KeptCopies | null }
104
115
  // A delta's key: the integrities of the version it is against, or none, and
105
116
  // of the version.
106
- export const deltaKey = (base: string | null, other: string) => `${base ?? '(empty)'}\0${other}`
117
+ export const deltaKey = (base: string | null, other: string) => `${COUNTING}\0${base ?? '(empty)'}\0${other}`
107
118
  // The same of two public versions by their names and versions (`(empty)`
108
119
  // for none), as npm never gives one other files: its key in
109
120
  // npmVersionDeltaStore.
110
121
  export const versionDeltaKey = (name: string, version: string, otherName: string, otherVersion: string) =>
111
- `${name}@${version}\0${otherVersion === '(empty)' ? '(empty)' : `${otherName}@${otherVersion}`}`
122
+ `${COUNTING}\0${name}@${version}\0${otherVersion === '(empty)' ? '(empty)' : `${otherName}@${otherVersion}`}`
112
123
  // Those of `keys` (versionDeltaKey) kept, by key, as of `now`: one kept past
113
124
  // VERSION_DELTA_KEPT_MS not, though no write has pruned it yet.
114
125
  export async function keptVersionDeltas(keys: string[], kept: KeptStore<NpmDelta>, now = Date.now()): Promise<Map<string, NpmDelta>> {
@@ -152,11 +163,21 @@ export async function keptNpmDeltas(sides: [string | null, string][], kept: Kept
152
163
  return found
153
164
  }
154
165
 
155
- // As kept, else its turn awaited, then both sides' files read, counted and kept.
166
+ // Those kept of the printable files both sides have, changed, by side and path.
167
+ async function keptCopies(sides: (Side | null)[], files: Map<string, Uint8Array>[]): Promise<SideCopy[]> {
168
+ const changed = [...files[1]!].filter(([path, bytes]) => prettyExtension(path) !== null && files[0]!.has(path) && !same(files[0]!.get(path)!, bytes))
169
+ const asked = changed.flatMap(([path]) => [0, 1].map(at => [at, path] as const)).filter(([at]) => sides[at]?.copies)
170
+ const found = await eachOf(asked, COPIES_AT_ONCE, async ([at, path]) => [at, path, await sides[at]!.copies!.kept(path, files[at]!.get(path)!).catch(() => null)] as const)
171
+ return found.filter((copy): copy is SideCopy => copy[2] !== null)
172
+ }
173
+
174
+ // As kept, else its turn awaited, then both sides' files read, counted and
175
+ // kept, the copies it printed kept for Compare.
156
176
  async function worked(key: string, base: Side | null, other: Side, kept: KeptStore<NpmDelta> | null): Promise<NpmDelta> {
157
177
  const known = deltaOf((await kept?.read(key))?.value)
158
178
  if (known) { deltas.set(key, known); return known }
159
- const delta = await workers.inTurn(Date.now() + DELTA_TIMEOUT_MS, async (): Promise<NpmDelta> => {
179
+ const sides = [base, other]
180
+ const [delta, made, files] = await workers.inTurn(Date.now() + DELTA_TIMEOUT_MS, async () => {
160
181
  // Its turn held till both sides are read, or have failed.
161
182
  const [baseRead, otherRead] = await Promise.allSettled([base ? base.files() : Promise.resolve(null), other.files()])
162
183
  if (baseRead.status === 'rejected') throw baseRead.reason
@@ -164,11 +185,14 @@ async function worked(key: string, base: Side | null, other: Side, kept: KeptSto
164
185
  const [olds, news] = [texts(baseRead.value), texts(otherRead.value)]
165
186
  if (olds.length + news.length > MAX_TEXT_LENGTH) throw new NpmPackageError(413, 'package-too-large')
166
187
  const binary = binaryChanged(olds.binaries, news.binaries)
167
- const told = await counted(olds.read, news.read, Date.now() + DELTA_TIMEOUT_MS)
168
- return { additions: told.additions, deletions: told.deletions,
169
- typeless: told.typeFiles > 0 ? { additions: told.additions - told.typeAdditions, deletions: told.deletions - told.typeDeletions } : null, binary }
188
+ const byPath = [baseRead.value ?? [], otherRead.value].map(side => new Map(side.filter(file => file.link === undefined).map(file => [file.path, file.bytes])))
189
+ const told = await counted(olds.read, news.read, await keptCopies(sides, byPath), Date.now() + DELTA_TIMEOUT_MS)
190
+ const counts: NpmDelta = { additions: told.additions, deletions: told.deletions, best: told.best, binary, ...told.complete ? {} : { partial: true as const } }
191
+ return [counts, told.made, byPath] as const
170
192
  })
171
193
  deltas.set(key, delta)
172
- await kept?.write(key, delta, Date.now())
194
+ if (!delta.partial) await kept?.write(key, delta, Date.now())
195
+ await eachOf(made.filter(([at, path, copy]) => sides[at]?.copies && files[at]?.has(path) && isCopy(copy)), COPIES_AT_ONCE,
196
+ ([at, path, copy]) => sides[at]!.copies!.keep(path, files[at]!.get(path)!, copy))
173
197
  return delta
174
198
  }
@@ -16,7 +16,9 @@
16
16
  // lockfiles add (pull-dependencies.ts), and the lockfiles a commit lists and
17
17
  // each one's packages, as its dependency review reads them
18
18
  // (commit-lockfiles.ts); and the commit the code viewer keeps its
19
- // directories at, for as long as it does (codeHeadStore). Each store removes
19
+ // directories at, for as long as it does (codeHeadStore); and what a team's
20
+ // Dependencies tab was last told of each repository, by its reader, for a
21
+ // week (teamDependencyStore). Each store removes
20
22
  // its own rows kept longer than that as it writes, at most once an hour a
21
23
  // database (pruneKept), so that rows no read will take again don't pile up.
22
24
  // The database is an optimization: a failure reads as a miss, and writes
@@ -243,6 +245,14 @@ export const patchStore = (db: UpstreamCacheStore, debug = false): KeptStore<Kep
243
245
  // what its reader could check and the rules they were made by: kept a month
244
246
  // after they were made, as what they check never changes.
245
247
  export const bundleValidationStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'bundles/validations', HISTORY_PAGE_KEPT_MS, debug)
248
+ // What a team's Dependencies tab (http.ts handleTeamDependencies) was last
249
+ // told whole of a repository, by its reader, the repository, its review's
250
+ // setting and what was asked: its default branch's line and its pull
251
+ // requests' dependencies, sent first as kept while they are read again, then
252
+ // replaced. Each kept TEAM_DEPENDENCIES_KEPT_MS, as one a week old still
253
+ // shows a reader more than nothing while it is read.
254
+ export const TEAM_DEPENDENCIES_KEPT_MS = 7 * 24 * 60 * 60_000
255
+ export const teamDependencyStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'teams/dependencies', TEAM_DEPENDENCIES_KEPT_MS, debug)
246
256
  // What a repository's stasis.config.json has Stasis reach at a commit
247
257
  // (stasis-dependencies.ts): the versions, never the lockfile, by the
248
258
  // repository, the commit and the file's path, kept as its history's pages are.
@@ -0,0 +1,22 @@
1
+ // A public version's pretty-printed copies as Compare keeps them (pretty-print.ts), by its files'
2
+ // paths and bytes, for a delta to read and keep (npm-delta.ts); none for a private version.
3
+ import { prettyExtension } from '../common/pretty-print.js'
4
+ import { encodeBrotli } from './brotli.ts'
5
+ import type { CacheStorage } from './cache-storage.ts'
6
+ import type { NpmVersionDocument } from './npm-packages.ts'
7
+ import type { PrettyCopy } from './pretty-format.js'
8
+ import { keep, kept, npmFileHash, prettyCopy, prettyFile } from './pretty-print.ts'
9
+
10
+ export interface KeptCopies { kept(path: string, bytes: Uint8Array): Promise<PrettyCopy | null>; keep(path: string, bytes: Uint8Array, copy: PrettyCopy): Promise<void> }
11
+
12
+ export function npmCopies(npm: CacheStorage, doc: NpmVersionDocument): KeptCopies | null {
13
+ if (doc.private) return null
14
+ const file = async (path: string, bytes: Uint8Array) => prettyFile({ path, hash: await npmFileHash(bytes), extension: prettyExtension(path) ?? '' })
15
+ return {
16
+ async kept(path, bytes) {
17
+ const copy = await kept(async () => npm.open(await file(path, bytes)))
18
+ return copy && prettyCopy(copy)
19
+ },
20
+ keep: (path, bytes, copy) => keep(async () => npm.put(await file(path, bytes), await encodeBrotli(Buffer.from(JSON.stringify(copy))))),
21
+ }
22
+ }
@@ -0,0 +1,3 @@
1
+ export const PRETTY_VERSION: number
2
+ export interface PrettyCopy { text: string; blank: number[] }
3
+ export function prettyFormat(text: string, extension: string): Promise<PrettyCopy | { error: 'unsupported' | 'unformattable' | 'pretty-mismatch' }>