@preventive/triage 1.0.0-alpha.60 → 1.0.0-alpha.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/common/default-scan-models.ts +6 -5
- package/common/managed/comments.ts +9 -0
- package/out/activity.js +1 -1
- package/out/chunk-6CCSTJWB.js +1 -0
- package/out/{chunk-VZJIHHTQ.js → chunk-B3FNMHOE.js} +1 -1
- package/out/chunk-BNH52UHC.js +2 -0
- package/out/chunk-BRO77PQY.js +42 -0
- package/out/chunk-GRGIZOTP.js +4 -0
- package/out/chunk-JJK5OZG2.js +15 -0
- package/out/chunk-OFZYEWBH.js +244 -0
- package/out/{chunk-YGRRXC2L.js → chunk-OIERSXON.js} +1 -1
- package/out/{chunk-TZS7KERJ.js → chunk-QCOGVL37.js} +1 -1
- package/out/{chunk-6VDDCFHT.js → chunk-W3QFV4SP.js} +1 -1
- package/out/chunk-W6VOKW2N.js +12 -0
- package/out/chunk-ZQNEWVGG.js +1 -0
- package/out/client-managed.js +2 -2
- package/out/compare.js +19 -14
- package/out/dialogs.js +38 -38
- package/out/graph.js +12 -12
- package/out/index.html +5 -5
- package/out/scan.js +1 -1
- package/out/terminal.js +12 -12
- package/out/view.css +1 -1
- package/out/view.js +4 -4
- package/package.json +9 -6
- package/server-managed/activity.ts +23 -43
- package/server-managed/agent-merges.ts +2 -2
- package/server-managed/blob-store.ts +10 -1
- package/server-managed/bundle-advisories.ts +3 -2
- package/server-managed/bundle-advisory-inventory.ts +1 -1
- package/server-managed/bundle-build-worker.js +41 -6
- package/server-managed/bundle-build.ts +18 -10
- package/server-managed/bundle-cache.ts +29 -41
- package/server-managed/bundle-catalog.ts +11 -11
- package/server-managed/bundle-commits.ts +9 -16
- package/server-managed/bundle-dependency-reviews.ts +5 -11
- package/server-managed/bundle-summary-cache.ts +23 -14
- package/server-managed/bundle-validation.ts +2 -1
- package/server-managed/combined.ts +1 -5
- package/server-managed/comments.ts +15 -28
- package/server-managed/commit-coauthors.ts +4 -5
- package/server-managed/commit-lockfiles.ts +6 -5
- package/server-managed/comparison.ts +3 -5
- package/server-managed/config.ts +1 -2
- package/server-managed/db-methods.ts +163 -244
- package/server-managed/db-neon.ts +82 -178
- package/server-managed/db-schema.ts +15 -0
- package/server-managed/db.ts +5 -11
- package/server-managed/dependabot-access.ts +2 -1
- package/server-managed/dependabot-alerts.ts +7 -12
- package/server-managed/dependency-review-comments.ts +7 -13
- package/server-managed/dependency-reviews.ts +14 -15
- package/server-managed/github-accounts.ts +4 -5
- package/server-managed/github-actions.ts +6 -6
- package/server-managed/github-app.ts +19 -48
- package/server-managed/github-graphql.ts +5 -2
- package/server-managed/github-issue-links.ts +62 -42
- package/server-managed/github-issue-oauth.ts +7 -24
- package/server-managed/github-issues.ts +9 -7
- package/server-managed/github-link-oauth.ts +7 -20
- package/server-managed/github-oauth.ts +38 -12
- package/server-managed/github-pulls.ts +37 -26
- package/server-managed/github-requests.ts +21 -8
- package/server-managed/github-values.ts +26 -0
- package/server-managed/history-windows.ts +7 -7
- package/server-managed/http.ts +495 -554
- package/server-managed/index.ts +6 -6
- package/server-managed/link-reports.ts +6 -19
- package/server-managed/lockfile-scope.ts +1 -1
- package/server-managed/management.ts +14 -3
- package/server-managed/npm-delta.ts +22 -57
- package/server-managed/npm-insights.ts +31 -26
- package/server-managed/npm-kept.ts +9 -8
- package/server-managed/npm-loads.ts +2 -7
- package/server-managed/npm-manifest.ts +6 -4
- package/server-managed/npm-packages.ts +17 -9
- package/server-managed/npm-patch.ts +8 -16
- package/server-managed/npm-provenance.ts +12 -8
- package/server-managed/npm-risk.ts +9 -7
- package/server-managed/object-storage-disk.ts +2 -3
- package/server-managed/object-storage-vercel.ts +15 -11
- package/server-managed/object-storage.ts +7 -0
- package/server-managed/pretty-print.ts +8 -19
- package/server-managed/public-workspace.ts +50 -46
- package/server-managed/pull-comment-reviews.ts +2 -2
- package/server-managed/pull-dependencies.ts +20 -31
- package/server-managed/pull-dependency-reviews.ts +17 -24
- package/server-managed/pull-reviews.ts +4 -7
- package/server-managed/queue.ts +14 -0
- package/server-managed/release-commits.ts +9 -8
- package/server-managed/rename-diff.ts +17 -60
- package/server-managed/report-migration.ts +5 -8
- package/server-managed/report-sources.ts +6 -10
- package/server-managed/report-store.ts +2 -10
- package/server-managed/repository-actions.ts +7 -8
- package/server-managed/repository-agents.ts +31 -57
- package/server-managed/repository-aliases.ts +3 -9
- package/server-managed/repository-browser.ts +18 -16
- package/server-managed/repository-changes.ts +33 -37
- package/server-managed/repository-code.ts +5 -5
- package/server-managed/repository-dependency-reviews.ts +6 -13
- package/server-managed/repository-discovery.ts +2 -1
- package/server-managed/repository-history.ts +47 -51
- package/server-managed/repository-issues.ts +59 -30
- package/server-managed/repository-pulls.ts +7 -12
- package/server-managed/repository-pulse.ts +51 -45
- package/server-managed/repository-risk-assess.ts +5 -2
- package/server-managed/repository-risk-audit.ts +1 -1
- package/server-managed/repository-risk-read.ts +6 -6
- package/server-managed/repository-risk.ts +32 -40
- package/server-managed/repository-squashes.ts +7 -15
- package/server-managed/request-timing.ts +1 -1
- package/server-managed/sql.ts +18 -0
- package/server-managed/storage-encryption.ts +5 -7
- package/server-managed/team-app.ts +4 -7
- package/server-managed/team-npm-scopes.ts +5 -8
- package/server-managed/team-reports.ts +15 -15
- package/server-managed/type-only-proof.js +108 -0
- package/server-managed/type-only-worker.js +26 -14
- package/server-managed/type-only.ts +72 -62
- package/server-managed/uploads.ts +3 -3
- package/server-managed/upstream-cache.ts +5 -7
- package/server-managed/worker-turns.ts +76 -0
- package/server-managed/workspace-shares.ts +1 -2
- package/out/chunk-2SY4PYUQ.js +0 -4
- package/out/chunk-4HI2MSAV.js +0 -17
- package/out/chunk-4TQKM3JC.js +0 -42
- package/out/chunk-EEQHVKR3.js +0 -1
- package/out/chunk-HNQNDNIE.js +0 -12
- package/out/chunk-OFPDMZJF.js +0 -244
- package/out/chunk-OQRSIBSC.js +0 -1
- package/out/chunk-YTO6AQZM.js +0 -2
|
@@ -48,7 +48,7 @@ export function auditLockfiles(source: AuditSource, memory: Lru<{ at: number; au
|
|
|
48
48
|
// The audit of a lockfile's `packages`, by its `key` as kept (`memory`, then
|
|
49
49
|
// the source's), else asked and kept; null where it locks none to ask of, or
|
|
50
50
|
// once `signal` aborts.
|
|
51
|
-
|
|
51
|
+
async function auditLockfile(source: AuditSource, memory: Lru<{ at: number; audit: Audit }>, signal: AbortSignal, key: string,
|
|
52
52
|
packages: readonly LockedPackage[]): Promise<Audit | null> {
|
|
53
53
|
let kept = memory.get(key)
|
|
54
54
|
if (!kept || !isFresh(kept)) {
|
|
@@ -19,7 +19,7 @@ import type { KeptStore } from './npm-kept.ts'
|
|
|
19
19
|
import { inTurns } from './queue.ts'
|
|
20
20
|
import { type WorkflowsRead, lastingRead, readActions } from './repository-actions.ts'
|
|
21
21
|
import { type RiskFailure, failureOf } from './repository-risk-assess.ts'
|
|
22
|
-
import type { RepositoryRiskLine, RepositoryRiskRepo } from './repository-risk.ts'
|
|
22
|
+
import type { LockfileLine, RepositoryRiskLine, RepositoryRiskRepo } from './repository-risk.ts'
|
|
23
23
|
|
|
24
24
|
// The formats of npm's ecosystem, as findRepoLockfiles names them, and those
|
|
25
25
|
// of them read here.
|
|
@@ -39,7 +39,6 @@ export type LockfileRead = { packages: LockedPackage[] } | RiskFailure
|
|
|
39
39
|
// them to check again before they are told (`recheck`), or why they couldn't
|
|
40
40
|
// be had.
|
|
41
41
|
export type DependabotRead = { alerts: DependabotAlert[]; recheck?(): Promise<void> } | RiskFailure
|
|
42
|
-
type LockfileLine = Extract<RepositoryRiskLine, { type: 'lockfile' }>
|
|
43
42
|
export type RepositoryFailure = Extract<RepositoryRiskLine, { type: 'repo'; error: string }>
|
|
44
43
|
|
|
45
44
|
// A repository opened at its default branch's head (`commit`): its lockfiles,
|
|
@@ -59,7 +58,7 @@ export interface OpenedRepository {
|
|
|
59
58
|
|
|
60
59
|
// What a repository is read with: the scan's source and caches, and its
|
|
61
60
|
// signal.
|
|
62
|
-
|
|
61
|
+
interface RepositoryReading<R extends RepositoryRiskRepo> {
|
|
63
62
|
source: { open(repo: R): Promise<OpenedRepository>; listings?: KeptStore<ListedLockfile[]>; lockfiles?: KeptStore<LockfileRead>; actionFiles?: KeptStore<WorkflowsRead> }
|
|
64
63
|
caches: { listings: Lru<ListedLockfile[]>; lockfiles: Lru<LockfileRead>; actionFiles: Lru<WorkflowsRead> }
|
|
65
64
|
signal: AbortSignal
|
|
@@ -152,8 +151,9 @@ async function readDependabot(opened: OpenedRepository, paths: readonly string[]
|
|
|
152
151
|
export async function readRepository<R extends RepositoryRiskRepo>(reading: RepositoryReading<R>, repo: R): Promise<RepositoryRead | RepositoryFailure | null> {
|
|
153
152
|
const listed = await listLockfiles(reading, repo)
|
|
154
153
|
if (!listed || 'type' in listed) return listed
|
|
155
|
-
const
|
|
156
|
-
const
|
|
154
|
+
const { opened } = listed
|
|
155
|
+
const alerting = readDependabot(opened, repo.paths)
|
|
156
|
+
const { workflows } = opened
|
|
157
157
|
const acting = workflows ? keptRead(reading.caches.actionFiles, reading.source.actionFiles, `${repo.repoId}@${opened.commit}`,
|
|
158
158
|
() => readActions({ workflows, file: path => opened.file(path) }), lastingRead) : Promise.resolve(null)
|
|
159
159
|
acting.catch(() => {})
|
|
@@ -166,5 +166,5 @@ export async function readRepository<R extends RepositoryRiskRepo>(reading: Repo
|
|
|
166
166
|
}
|
|
167
167
|
const dependabot = await alerting
|
|
168
168
|
const actions = await acting
|
|
169
|
-
return reading.signal.aborted ? null : { commit:
|
|
169
|
+
return reading.signal.aborted ? null : { commit: opened.commit, lockfiles, dependabot, actions, recheck: () => opened.recheck() }
|
|
170
170
|
}
|
|
@@ -27,44 +27,35 @@
|
|
|
27
27
|
// Actions are told once its lockfiles are, the references they make
|
|
28
28
|
// resolved as the scan goes on (repository-actions.ts).
|
|
29
29
|
import type { LockfileFormat } from '@preventive/upstream/github.js'
|
|
30
|
-
import { type Severity, npmMalwareAdvisory } from '../risk/index.js'
|
|
30
|
+
import { type ActionsSource, type Severity, npmMalwareAdvisory } from '../risk/index.js'
|
|
31
31
|
import { isNpmPackageName, isNpmPackageSpec } from '../common/managed/npm-packages.js'
|
|
32
|
-
import type { NpmVersionDocument } from './npm-packages.ts'
|
|
33
32
|
import { type Lru, lru } from './lru.ts'
|
|
34
33
|
import type { KeptStore } from './npm-kept.ts'
|
|
35
34
|
import { MAX_SPARE_ASSESSMENTS } from './npm-risk.ts'
|
|
36
35
|
import type { LockedPackage } from './locked-packages.ts'
|
|
37
36
|
import { type Queue, inTurns, queue } from './queue.ts'
|
|
38
37
|
import { type DownloadsSource, readyingDownloads } from './scan-downloads.ts'
|
|
39
|
-
import { type AssessedPackage, type
|
|
38
|
+
import { type AssessedPackage, type AssessingSource, BUSY_RETRIES, BUSY_WAIT_MS, RISK_KEPT_MS, type RiskFailure, assessPackage, failureOf, isBusy } from './repository-risk-assess.ts'
|
|
40
39
|
import { type AdvisoryRow, type Audit, type AuditSource, auditLockfiles } from './repository-risk-audit.ts'
|
|
41
40
|
import { type DependabotRead, type ListedLockfile, type LockfileRead, type OpenedRepository, type RepositoryFailure, type RepositoryRead, SCAN_READ_KEPT_MS,
|
|
42
41
|
readRepository } from './repository-risk-read.ts'
|
|
43
42
|
import { type DependabotAlert, alertVersions } from './dependabot-alerts.ts'
|
|
44
|
-
import type { ActionsSource } from '../risk/index.js'
|
|
45
43
|
import { type ActionAnswers, type ActionLine, type ActionRef, type WorkflowLine, type WorkflowsLine, type WorkflowsRead, actionsLines, answerWeight,
|
|
46
44
|
lockedNames, resolvingActions } from './repository-actions.ts'
|
|
47
45
|
|
|
48
46
|
export { RISK_KEPT_MS, highestSeverity } from './repository-risk-assess.ts'
|
|
49
|
-
export {
|
|
47
|
+
export { SCAN_READ_KEPT_MS } from './repository-risk-read.ts'
|
|
50
48
|
|
|
51
49
|
// A repository to read: where `paths` are given, a team's directories in it,
|
|
52
50
|
// only the lockfiles in them or above them, as a workspace's root lockfile
|
|
53
51
|
// locks them too.
|
|
54
52
|
export interface RepositoryRiskRepo { repoId: number; fullName: string; paths?: readonly string[] }
|
|
55
53
|
|
|
56
|
-
|
|
54
|
+
interface RepositoryRiskSource<R extends RepositoryRiskRepo> extends AuditSource, AssessingSource {
|
|
57
55
|
repos(): Promise<R[]>
|
|
58
56
|
open(repo: R): Promise<OpenedRepository>
|
|
59
57
|
// Whether a team lists a package's scope, its own packages.
|
|
60
58
|
teamScoped(name: string): Promise<boolean>
|
|
61
|
-
// npm's document of a version; an NpmPackageError where npm has none.
|
|
62
|
-
version(name: string, version: string, signal: AbortSignal): Promise<NpmVersionDocument>
|
|
63
|
-
assess(doc: NpmVersionDocument, teamScoped: boolean, signal: AbortSignal): Promise<Assessment>
|
|
64
|
-
// A version npm has no document of, as risk tells one npm removed: its
|
|
65
|
-
// malware alone, its package taken down by npm; an NpmRiskError where
|
|
66
|
-
// nothing tells of it (npm-risk.ts npmRiskRemoved).
|
|
67
|
-
removed(name: string, version: string, teamScoped: boolean, signal: AbortSignal): Promise<Assessment>
|
|
68
59
|
// Where risk lines are kept beyond this instance, as RiskCaches keeps them
|
|
69
60
|
// in it (npm-kept.ts riskLineStore, the database's).
|
|
70
61
|
risks?: KeptStore<RiskLine>
|
|
@@ -90,13 +81,11 @@ export interface RepositoryRiskSource<R extends RepositoryRiskRepo> extends Audi
|
|
|
90
81
|
actionLines?: KeptStore<ActionLine>
|
|
91
82
|
}
|
|
92
83
|
|
|
93
|
-
|
|
94
|
-
|
|
95
84
|
// A Dependabot alert as a scan tells it: with the versions of its package
|
|
96
85
|
// the lockfile it is of locks that it covers, none where it is of none read
|
|
97
86
|
// (a package.json, bun's lockfile), and whether it is of malware, by the rule
|
|
98
87
|
// upstream tells an advisory's by (risk's npmMalwareAdvisory).
|
|
99
|
-
|
|
88
|
+
type DependabotAlertRow = DependabotAlert & { versions: string[]; malware: boolean }
|
|
100
89
|
|
|
101
90
|
// A risk line is of npm's package of its name and version, or, with an
|
|
102
91
|
// `integrity`, of a mirror's that its lockfiles hold to it; its `score` risk's
|
|
@@ -122,7 +111,7 @@ export type RepositoryRiskLine =
|
|
|
122
111
|
export interface ScanProgress { repos: ToldRepository[] }
|
|
123
112
|
interface ToldRepository { id: number; name: string; paths: readonly string[] | null; lockfiles: string[]; actions?: ActionRef[] }
|
|
124
113
|
|
|
125
|
-
type RiskLine = Extract<RepositoryRiskLine, { type: 'risk' }>
|
|
114
|
+
export type RiskLine = Extract<RepositoryRiskLine, { type: 'risk' }>
|
|
126
115
|
|
|
127
116
|
// What scans keep between them, in this instance's memory: a repository's
|
|
128
117
|
// lockfiles as listed at a commit, and a lockfile's packages by its blob,
|
|
@@ -132,7 +121,7 @@ type RiskLine = Extract<RepositoryRiskLine, { type: 'risk' }>
|
|
|
132
121
|
// of a package changes in time (a deprecation, its age, its downloads). A
|
|
133
122
|
// lockfile's, and its packages' lines, are told only once access to its
|
|
134
123
|
// repository is checked as when it was read.
|
|
135
|
-
|
|
124
|
+
interface RiskCaches {
|
|
136
125
|
listings: Lru<ListedLockfile[]>
|
|
137
126
|
lockfiles: Lru<LockfileRead>
|
|
138
127
|
risks: Lru<{ at: number; line: RiskLine }>
|
|
@@ -191,7 +180,7 @@ const seenKey = (pkg: AssessedPackage) => `${pkg.name}@${pkg.version}\0${pkg.int
|
|
|
191
180
|
|
|
192
181
|
// A package's key, as its risk line is kept: its name, version and a
|
|
193
182
|
// mirror's integrity, and whether a team lists its scope.
|
|
194
|
-
const riskKey = (pkg: AssessedPackage, teamScoped: boolean) => `${pkg
|
|
183
|
+
const riskKey = (pkg: AssessedPackage, teamScoped: boolean) => `${seenKey(pkg)}\0${teamScoped}`
|
|
195
184
|
// Whether a line kept `at` is told as it is: within RISK_KEPT_MS, and kept
|
|
196
185
|
// since risk told a score (assessNpm `score`).
|
|
197
186
|
const isFresh = ({ at, line }: { at: number; line: RiskLine }) => Date.now() - at < RISK_KEPT_MS && ('error' in line || typeof line.score === 'number')
|
|
@@ -289,7 +278,7 @@ function assessLater(scan: Scan, packages: LockedPackage[]) {
|
|
|
289
278
|
if (fresh.length > 0) scan.lookups.add(fresh)
|
|
290
279
|
}
|
|
291
280
|
|
|
292
|
-
type LockfileLine = Extract<RepositoryRiskLine, { type: 'lockfile' }>
|
|
281
|
+
export type LockfileLine = Extract<RepositoryRiskLine, { type: 'lockfile' }>
|
|
293
282
|
|
|
294
283
|
// A lockfile's advisories line, of its audit (repository-risk-audit.ts auditLockfile).
|
|
295
284
|
const advisoriesLine = ({ repo, path }: LockfileLine, audit: Audit) => ({ type: 'advisories', repo, path, ...Array.isArray(audit) ? { advisories: audit } : audit } as const)
|
|
@@ -418,6 +407,26 @@ function leftOver(scan: Scan): AssessedPackage[][] {
|
|
|
418
407
|
return [scan.stale.filter(pkg => !dev(pkg)), [...scan.dev.values(), ...scan.stale.filter(dev)]]
|
|
419
408
|
}
|
|
420
409
|
|
|
410
|
+
// The scan's work, behind its lines (repositoryRiskLines), `done` last, its
|
|
411
|
+
// lines closed once it ends, its failure given to `fail`.
|
|
412
|
+
async function runScan(scan: Scan, fail: (error: unknown) => void) {
|
|
413
|
+
try {
|
|
414
|
+
// Those with no risk line kept assessed first, as their lockfiles are read,
|
|
415
|
+
await assessing(scan, async assess => {
|
|
416
|
+
const looking = lookUp(scan, assess)
|
|
417
|
+
// stopped at once where reading fails;
|
|
418
|
+
try { await readRepositories(scan) } catch (error) { fail(error) } finally { scan.lookups.close() }
|
|
419
|
+
await looking
|
|
420
|
+
})
|
|
421
|
+
// then those told stale, and those only devDependencies need, in turn.
|
|
422
|
+
for (const left of leftOver(scan)) {
|
|
423
|
+
if (!scan.signal.aborted && left.length > 0) await assessing(scan, assess => { assess(left); return Promise.resolve() })
|
|
424
|
+
}
|
|
425
|
+
await scan.actions?.close()
|
|
426
|
+
if (!scan.signal.aborted) scan.lines.add({ type: 'done' })
|
|
427
|
+
} catch (error) { fail(error) } finally { scan.lines.close() }
|
|
428
|
+
}
|
|
429
|
+
|
|
421
430
|
// The scan's lines, in the order they are found: the repositories first,
|
|
422
431
|
// then each repository's lockfiles and their packages once read and access
|
|
423
432
|
// is checked again, and each package's risk: as kept, however old, at once
|
|
@@ -446,27 +455,10 @@ export async function* repositoryRiskLines<R extends RepositoryRiskRepo>(source:
|
|
|
446
455
|
answers: caches.actionAnswers, store: source.actionLines }) : null
|
|
447
456
|
const scan: Scan = { source, caches, signal: running, lines, lookups: queue(running), seen: new Map(), dev: new Map(), stale: [], told: new Map(), actions,
|
|
448
457
|
audits: inTurns(AUDITS_AT_ONCE) }
|
|
458
|
+
// A failure of the scan itself kept, to throw once the lines before it are
|
|
459
|
+
// told, and the scan stopped.
|
|
449
460
|
const failed: unknown[] = []
|
|
450
|
-
void (
|
|
451
|
-
try {
|
|
452
|
-
// Those with no risk line kept assessed first, as their lockfiles are read,
|
|
453
|
-
await assessing(scan, async assess => {
|
|
454
|
-
const looking = lookUp(scan, assess)
|
|
455
|
-
// stopped at once where reading fails;
|
|
456
|
-
try { await readRepositories(scan) } catch (error) { failed.push(error); stopped.abort() } finally { scan.lookups.close() }
|
|
457
|
-
await looking
|
|
458
|
-
})
|
|
459
|
-
// then those told stale, and those only devDependencies need, in turn.
|
|
460
|
-
for (const left of leftOver(scan)) {
|
|
461
|
-
if (!running.aborted && left.length > 0) await assessing(scan, assess => { assess(left); return Promise.resolve() })
|
|
462
|
-
}
|
|
463
|
-
await actions?.close()
|
|
464
|
-
if (!running.aborted) scan.lines.add({ type: 'done' })
|
|
465
|
-
} catch (error) {
|
|
466
|
-
failed.push(error)
|
|
467
|
-
stopped.abort()
|
|
468
|
-
} finally { scan.lines.close() }
|
|
469
|
-
})()
|
|
461
|
+
void runScan(scan, error => { failed.push(error); stopped.abort() })
|
|
470
462
|
try {
|
|
471
463
|
let done = false
|
|
472
464
|
for (let line = await scan.lines.take(); line !== undefined; line = await scan.lines.take()) {
|
|
@@ -2,10 +2,9 @@
|
|
|
2
2
|
// viewer's Commits tab draws them (repository-history.ts), each looked up
|
|
3
3
|
// with GraphQL once and kept by its commit.
|
|
4
4
|
import { linkNoreplyUsers } from './github-accounts.ts'
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
const SHA = /^[a-f\d]{40}$/u
|
|
5
|
+
import { githubGraphql, notFound } from './github-graphql.ts'
|
|
6
|
+
import { SHA } from './github-values.ts'
|
|
7
|
+
import { COMMIT_FRAGMENT, type GraphCommit, type HistoryCommit, commitActors, commitIds, commitsQuery, graphCommit, inBatches, variablesOf } from './repository-history.ts'
|
|
9
8
|
|
|
10
9
|
// A pull request squashed into a commit of the default branch's history
|
|
11
10
|
// (`merge`): its number, the commit its head was at when merged (`head`,
|
|
@@ -35,17 +34,13 @@ const MAX_SQUASHED = 100
|
|
|
35
34
|
// Looked up of an answer's commits not yet kept, at most, the newest first;
|
|
36
35
|
// in queries of as many commits, or pull requests (their commits' lines
|
|
37
36
|
// counted, as a history's are), as many at once.
|
|
38
|
-
|
|
37
|
+
const MAX_SQUASH_LOOKUPS = 500
|
|
39
38
|
const SQUASH_COMMITS = 100
|
|
40
39
|
const SQUASH_PULLS = 5
|
|
41
40
|
const SQUASH_PARALLEL = 4
|
|
42
41
|
|
|
43
42
|
// The merged pull request that brought each commit in, `c<n>` the `n`th's.
|
|
44
|
-
const mergedPullsQuery = (count: number) =>
|
|
45
|
-
repository(owner: $owner, name: $name) {
|
|
46
|
-
${Array.from({ length: count }, (_, at) => `c${at}: object(oid: $o${at}) { ... on Commit { associatedPullRequests(first: 1) { nodes { number mergeCommit { oid } } } } }`).join('\n ')}
|
|
47
|
-
}
|
|
48
|
-
}`
|
|
43
|
+
const mergedPullsQuery = (count: number) => commitsQuery(count, 'c', 'associatedPullRequests(first: 1) { nodes { number mergeCommit { oid } } }')
|
|
49
44
|
// Each pull request's head when merged and its latest commits, `p<n>` the `n`th's.
|
|
50
45
|
const squashedQuery = (count: number) => `query($owner: String!, $name: String!, ${variablesOf('n', count, 'Int!')}) {
|
|
51
46
|
repository(owner: $owner, name: $name) {
|
|
@@ -57,9 +52,6 @@ ${COMMIT_FRAGMENT}`
|
|
|
57
52
|
type MergedPulls = { repository?: Record<string, { associatedPullRequests?: { nodes?: ({ number?: unknown; mergeCommit?: { oid?: unknown } | null } | null)[] } } | null> | null }
|
|
58
53
|
type SquashedPage = { repository?: Record<string, { headRefOid?: unknown; commits?: { totalCount?: unknown; nodes?: ({ commit?: GraphCommit | null } | null)[] } } | null> | null }
|
|
59
54
|
|
|
60
|
-
// A pull request or commit GitHub has none of, as one deleted: its field null.
|
|
61
|
-
const notFound = (error: GraphqlError) => error?.type === 'NOT_FOUND'
|
|
62
|
-
|
|
63
55
|
// Each repository's lookup of squashed pull requests going on, by its full
|
|
64
56
|
// name: one at a time, those asking meanwhile waiting on it, and their
|
|
65
57
|
// commits it doesn't look up looked up once it is done.
|
|
@@ -129,8 +121,8 @@ async function lookUpSquashes(fullName: string, token: string, unknown: HistoryC
|
|
|
129
121
|
else merged.push({ commit, number })
|
|
130
122
|
}
|
|
131
123
|
await inBatches(asked, SQUASH_COMMITS, SQUASH_PARALLEL, async batch => {
|
|
132
|
-
const data = await githubGraphql(mergedPullsQuery(batch.length), { owner, name, ...
|
|
133
|
-
|
|
124
|
+
const data = await githubGraphql(mergedPullsQuery(batch.length), { owner, name, ...commitIds(batch.map(commit => commit.sha)) }, token, fetchImpl,
|
|
125
|
+
notFound) as MergedPulls
|
|
134
126
|
for (const [at, commit] of batch.entries()) {
|
|
135
127
|
const node = data?.repository?.[`c${at}`]
|
|
136
128
|
if (!node) continue
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Where a request's time goes, told back in its Server-Timing header, which
|
|
2
2
|
// DevTools shows beside the request: the database's statements and the time
|
|
3
3
|
// spent in its operations (sql.ts), new pooled connections and their
|
|
4
|
-
// handshakes (db-neon.ts), GitHub's calls (github-
|
|
4
|
+
// handshakes (db-neon.ts), GitHub's calls (github-requests.ts githubJson), and
|
|
5
5
|
// the whole, from the handler's start to its answer's head; an instance's
|
|
6
6
|
// first request marked cold. Counts and durations alone, nothing of what was
|
|
7
7
|
// asked; a streamed answer's head tells what was known as it was written.
|
package/server-managed/sql.ts
CHANGED
|
@@ -5,6 +5,11 @@ import type { ManagedDb } from './db-methods.ts'
|
|
|
5
5
|
import { countStatement, timed } from './request-timing.ts'
|
|
6
6
|
|
|
7
7
|
type MaybePromise<T> = T | Promise<T>
|
|
8
|
+
|
|
9
|
+
// Rows a statement gathered into one JSON array value (json_group_array): its
|
|
10
|
+
// text on SQLite, parsed already on Postgres, where none gather as NULL.
|
|
11
|
+
export const jsonRows = <T>(value: unknown): T[] => value == null ? [] : (typeof value === 'string' ? JSON.parse(value) : value) as T[]
|
|
12
|
+
|
|
8
13
|
export interface ManagedSql {
|
|
9
14
|
prepare(sql: string): {
|
|
10
15
|
get(...params: unknown[]): MaybePromise<unknown>
|
|
@@ -51,6 +56,19 @@ export function scopeManagedMethods(methods: ManagedDb, driver: ManagedSqlDriver
|
|
|
51
56
|
return Object.fromEntries(entries) as ManagedDb
|
|
52
57
|
}
|
|
53
58
|
|
|
59
|
+
// A SQLite bootstrap step's own transaction, begun by `begin`, rolled back
|
|
60
|
+
// where `work` (or its commit) throws.
|
|
61
|
+
export function sqliteTransaction(db: DatabaseSync, begin: 'BEGIN' | 'BEGIN IMMEDIATE', work: () => void): void {
|
|
62
|
+
db.exec(begin)
|
|
63
|
+
try {
|
|
64
|
+
work()
|
|
65
|
+
db.exec('COMMIT')
|
|
66
|
+
} catch (err) {
|
|
67
|
+
db.exec('ROLLBACK')
|
|
68
|
+
throw err
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
54
72
|
export function createSqliteDriver(db: DatabaseSync): ManagedSqlDriver {
|
|
55
73
|
let queue = Promise.resolve()
|
|
56
74
|
let closed = false
|
|
@@ -5,17 +5,12 @@ import { type StorageKey, decryptStorageStream, encryptStorageStream, wrapStorag
|
|
|
5
5
|
import { ENCRYPTED_CACHE_PREFIX, type ObjectStorage, type RawObject, type RawObjectStorage, deleteObjects, objectPath, openObjectVersion } from './object-storage.ts'
|
|
6
6
|
import { type StorageDb, type StorageEncryptionState, type StorageRow, type StorageRowKind, dataKeyIdentity, unwrapDataKey } from './storage-db.ts'
|
|
7
7
|
import { PUBLIC_CACHE_PREFIX, inspectStorageObject, masterKeyCache, storageOwner, storageRowPaths, verifyStoragePayload } from './storage-payload.ts'
|
|
8
|
+
import { readBytes } from './blob-store.ts'
|
|
8
9
|
|
|
9
10
|
const STORAGE_WRITE_MS = 180_000
|
|
10
11
|
export const STORAGE_UPLOAD_TTL_MS = 86_400_000
|
|
11
12
|
export const STORAGE_DISABLED_TTL_MS = 5_000
|
|
12
13
|
|
|
13
|
-
async function readBytes(stored: Awaited<ReturnType<ObjectStorage['open']>>): Promise<Buffer | null> {
|
|
14
|
-
if (!stored) return null
|
|
15
|
-
const parts: Buffer[] = []
|
|
16
|
-
try { for await (const part of stored.stream) parts.push(Buffer.from(part)); return Buffer.concat(parts) }
|
|
17
|
-
finally { stored.stream.destroy() }
|
|
18
|
-
}
|
|
19
14
|
function logicalKey(identity: string) {
|
|
20
15
|
objectPath(identity)
|
|
21
16
|
if (identity.startsWith(ENCRYPTED_CACHE_PREFIX)) throw new Error('Encrypted cache paths are internal')
|
|
@@ -226,7 +221,10 @@ export async function createEncryptedObjectStorage(raw: RawObjectStorage, db: St
|
|
|
226
221
|
}
|
|
227
222
|
return {
|
|
228
223
|
open,
|
|
229
|
-
|
|
224
|
+
async get(identity) {
|
|
225
|
+
const stored = await open(identity)
|
|
226
|
+
return stored ? readBytes(stored) : null
|
|
227
|
+
},
|
|
230
228
|
async exists(identity) {
|
|
231
229
|
logicalKey(identity)
|
|
232
230
|
const owner = storageOwner(identity), state = await mode()
|
|
@@ -21,6 +21,7 @@ import type { ManagedDb, TeamReportAccessSnapshot, UserTeam } from './db.ts'
|
|
|
21
21
|
import type { WorkspaceShareSnapshot } from './workspace-shares.ts'
|
|
22
22
|
import { TeamReportsError, loadTeamSummary } from './team-reports.ts'
|
|
23
23
|
import { teamAppSummaryKey } from './team-app-summaries.ts'
|
|
24
|
+
import { eachOf } from './queue.ts'
|
|
24
25
|
|
|
25
26
|
export type { TeamAppMetadata }
|
|
26
27
|
export interface TeamWorkspaceSummary { app: TeamAppMetadata; empty: readonly string[] }
|
|
@@ -141,13 +142,9 @@ export async function teamAppStates(db: ManagedDb, store: BlobStore, sessionId:
|
|
|
141
142
|
// once, in one statement.
|
|
142
143
|
const unknown = missing.filter(([key, team]) => !caches.get(db)?.has(key) && published(team).length > 0).map(([key]) => key)
|
|
143
144
|
for (const [key, summary] of unknown.length > 0 ? await storedSummaries(db, unknown) : []) remember(db, key, summary)
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
const [key, team] = missing[next++]!
|
|
148
|
-
states.set(key, await classify(db, store, key, team, () => db.getTeamReportAccessSnapshot(sessionId, Date.now(), team.id), false))
|
|
149
|
-
}
|
|
150
|
-
}))
|
|
145
|
+
await eachOf(missing, CLASSIFY_CONCURRENCY, async ([key, team]) => {
|
|
146
|
+
states.set(key, await classify(db, store, key, team, () => db.getTeamReportAccessSnapshot(sessionId, Date.now(), team.id), false))
|
|
147
|
+
})
|
|
151
148
|
return states
|
|
152
149
|
}
|
|
153
150
|
|
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
// managers may read any. Hidden teams grant nothing, as for their content.
|
|
4
4
|
import { MAX_TEAM_NPM_SCOPES, normalizeNpmScope } from '../common/managed/npm-packages.js'
|
|
5
5
|
import type { Role } from '../common/managed/roles.ts'
|
|
6
|
-
import {
|
|
7
|
-
import { ManagedMutationError } from './management.ts'
|
|
8
|
-
import type
|
|
6
|
+
import { reviewsIn } from './dependency-reviews.ts'
|
|
7
|
+
import { ManagedMutationError, sessionAdmin } from './management.ts'
|
|
8
|
+
import { type ManagedSql, jsonRows } from './sql.ts'
|
|
9
9
|
|
|
10
10
|
export const TEAM_NPM_SCOPE_SCHEMA = `
|
|
11
11
|
CREATE TABLE IF NOT EXISTS managed_team_npm_scope (
|
|
@@ -58,10 +58,7 @@ export function teamNpmScopeMethods(db: ManagedSql): TeamNpmScopeStore {
|
|
|
58
58
|
return result
|
|
59
59
|
},
|
|
60
60
|
async setTeamNpmScopes(sessionId, teamId, input) {
|
|
61
|
-
|
|
62
|
-
WHERE s.id = ? AND s.expires_at > ?`).get(sessionId, Date.now()) as { role: string } | undefined
|
|
63
|
-
if (!user) throw new ManagedMutationError(401, 'unauthenticated')
|
|
64
|
-
if (user.role !== 'admin') throw new ManagedMutationError(403, 'forbidden')
|
|
61
|
+
await sessionAdmin(db, sessionId)
|
|
65
62
|
const scopes = parseTeamNpmScopes(input)
|
|
66
63
|
if (!await db.prepare('SELECT id FROM managed_team WHERE id = ?').get(teamId)) return null
|
|
67
64
|
const current = (await db.prepare('SELECT scope FROM managed_team_npm_scope WHERE team_id = ?').all(teamId) as { scope: string }[]).map(row => row.scope)
|
|
@@ -102,5 +99,5 @@ async function npmReviewReader(db: ManagedSql, sessionId: string, viewerSessionI
|
|
|
102
99
|
WHERE tu.user_id = v.id) x) AS scopes,
|
|
103
100
|
CASE WHEN EXISTS (SELECT 1 FROM managed_team t JOIN managed_user u ON u.id = v.id WHERE t.id = ? AND ${reviewsIn(false)}) THEN 1 ELSE 0 END AS readsTeam
|
|
104
101
|
FROM reader v`).get(sessionId, now, viewerSessionId, viewerSessionId, now, teamId) as { id: string; role: Role; scopes: unknown; readsTeam: unknown } | undefined
|
|
105
|
-
return row ? { id: row.id, role: row.role, scopes:
|
|
102
|
+
return row ? { id: row.id, role: row.role, scopes: jsonRows<string>(row.scopes), readsTeam: Number(row.readsTeam) === 1 } : null
|
|
106
103
|
}
|
|
@@ -133,8 +133,9 @@ function withoutTree(report: TeamReport): string | null {
|
|
|
133
133
|
})
|
|
134
134
|
return `${JSON.stringify(report.id)}:${JSON.stringify(Object.fromEntries(files))}`
|
|
135
135
|
}
|
|
136
|
-
|
|
137
|
-
|
|
136
|
+
// The snapshot's reports, read WORKSPACE_READS_AT_ONCE at a time, in its
|
|
137
|
+
// order, their findings' IDs backfilled.
|
|
138
|
+
async function readWorkspaceReports(store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<TeamReport[]> {
|
|
138
139
|
const reports: TeamReport[] = []
|
|
139
140
|
let inputBytes = 0, next = 0
|
|
140
141
|
// Bound both remote reads and raw buffers, retaining stable report order for
|
|
@@ -157,6 +158,11 @@ async function buildTeamWorkspace(db: ManagedDb, store: BlobStore, snapshot: Tea
|
|
|
157
158
|
}
|
|
158
159
|
}))
|
|
159
160
|
for (const result of results) if (result.status === 'rejected') throw result.reason
|
|
161
|
+
return reports
|
|
162
|
+
}
|
|
163
|
+
async function buildTeamWorkspace(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<EncodedWorkspace & { visible: Visibility }> {
|
|
164
|
+
if (snapshot.reports.length > MAX_REPORT_QUERY_COUNT || snapshot.reports.reduce((n, r) => n + r.byteSize, 0) > MAX_REPORT_QUERY_BYTES) throw new TeamReportsError(413, 'batch-too-large')
|
|
165
|
+
const reports = await readWorkspaceReports(store, snapshot)
|
|
160
166
|
const globalLinks = snapshot.linkRevision ? await db.getEnabledLinkGroups(snapshot.linkRevision) : []
|
|
161
167
|
const groups = reports.flatMap(report => groupsOf(report.data).map(group => group.map(f => projectFinding(f, report.data as Finding)!)))
|
|
162
168
|
// Unknown IDs can connect known findings. App findings link to the inputs
|
|
@@ -275,18 +281,14 @@ export async function loadTeamReports(db: ManagedDb, store: BlobStore, snapshot:
|
|
|
275
281
|
return body.reports
|
|
276
282
|
}
|
|
277
283
|
async function teamVisibility(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<Visibility> {
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
// another request. Authorization uses this load's result in either case.
|
|
282
|
-
visible = (await loadTeamWorkspace(db, store, snapshot)).visible
|
|
283
|
-
}
|
|
284
|
-
return visible
|
|
284
|
+
// A large snapshot may deliberately remain uncached, or be evicted by
|
|
285
|
+
// another request. Authorization uses this load's result in either case.
|
|
286
|
+
return caches.get(db)?.get(workspaceKey(snapshot)) ?? (await loadTeamWorkspace(db, store, snapshot)).visible
|
|
285
287
|
}
|
|
288
|
+
// The findings `visible`'s reports show, each once.
|
|
289
|
+
const findingIdsOf = (visible: Visibility) => new Set([...visible.values()].flatMap(report => [...report.ids]))
|
|
286
290
|
export async function teamWorkspaceFindingIds(db: ManagedDb, store: BlobStore, snapshot: TeamReportAccessSnapshot): Promise<Set<string>> {
|
|
287
|
-
|
|
288
|
-
for (const report of (await teamVisibility(db, store, snapshot)).values()) for (const id of report.ids) ids.add(id)
|
|
289
|
-
return ids
|
|
291
|
+
return findingIdsOf(await teamVisibility(db, store, snapshot))
|
|
290
292
|
}
|
|
291
293
|
|
|
292
294
|
// What a focused team's annotations are at, for the snapshot reading them, as
|
|
@@ -337,9 +339,7 @@ export async function loadTeamAnnotations(db: ManagedDb, store: BlobStore, snaps
|
|
|
337
339
|
if (reportId !== null && !snapshot.reports.some(r => r.id === reportId)) throw new TeamReportsError(404, 'no-report')
|
|
338
340
|
const workspace = await teamVisibility(db, store, snapshot)
|
|
339
341
|
const visible = reportId === null ? workspace : new Map([[reportId, workspace.get(reportId)!]])
|
|
340
|
-
const all =
|
|
341
|
-
for (const report of visible.values()) for (const id of report.ids) ids.add(id)
|
|
342
|
-
for (const report of workspace.values()) for (const id of report.ids) all.add(id)
|
|
342
|
+
const all = findingIdsOf(workspace), ids = findingIdsOf(visible)
|
|
343
343
|
const revision = await teamAnnotationRevision(db, snapshot, [...all])
|
|
344
344
|
const { triage, comments, issues: savedIssues } = await db.getAnnotations([...ids])
|
|
345
345
|
const issues = Object.fromEntries(visibleManagedIssues(savedIssues, snapshot)
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Whether a pair of a comparison's files changed in types alone (type-only.ts),
|
|
2
|
+
// told in a worker (type-only-worker.js): each a file a side, `{ path, text }`,
|
|
3
|
+
// a side not there null, its path as it is, which says what a file is.
|
|
4
|
+
//
|
|
5
|
+
// typeOnlyStamped: as @preventive/compare's compareTrees stamps a change
|
|
6
|
+
// `typeOnly`. Two paths pair as one change wherever compareTrees takes them
|
|
7
|
+
// for a rename at all; where it doesn't, the pair is types only where each of
|
|
8
|
+
// its two changes is: the file gone erasing whole, and the one come erasing
|
|
9
|
+
// whole or leaving a single bare `export {}`, which nothing loaded before.
|
|
10
|
+
//
|
|
11
|
+
// typeOnlyRuns: one it doesn't stamp may still hold types alone but for what
|
|
12
|
+
// runs on each side, each side there a declaration file proveTypeOnly proves,
|
|
13
|
+
// its runtime what changed: a module load added, gone or another, or a file
|
|
14
|
+
// added or removed that loads one, as a zod schema's declarations do. Told
|
|
15
|
+
// then are the lines that hold what runs on each side (`runs` the base's,
|
|
16
|
+
// `otherRuns` the other's, none for a side not there), for the viewer to diff
|
|
17
|
+
// those alone with its types set aside: the hashbang, each statement Node's
|
|
18
|
+
// type stripping leaves to run (a module load, `export {}`, `export default`
|
|
19
|
+
// of a name), and each comment it keeps that may be one a tool reads (a
|
|
20
|
+
// triple-slash directive, a source map or source URL pragma), told wide of
|
|
21
|
+
// the proof's own grammar for them, so none it reads is ever set aside. A
|
|
22
|
+
// line holding any of it is told whole; a range is `[from, to)` of lines
|
|
23
|
+
// counted from zero, as the viewer splits a text at `\n`. None are told of
|
|
24
|
+
// a pair where a diff of those lines would not show what changed: a
|
|
25
|
+
// triple-slash comment that leads one side, where a directive steers, and
|
|
26
|
+
// stands below a statement on the other, where it is prose, its line the same
|
|
27
|
+
// on both (`moved`). Its diff is drawn whole, as one not proven is.
|
|
28
|
+
import { stripTypeScriptTypes } from 'node:module'
|
|
29
|
+
import { compareTrees, proveTypeOnly } from '@preventive/compare'
|
|
30
|
+
import { parseSync } from 'oxc-parser'
|
|
31
|
+
|
|
32
|
+
// A declaration file as compareTrees takes one: `.d.ts`, `.d.mts`, `.d.cts`,
|
|
33
|
+
// and `.d.css.ts` for a `.css` file's.
|
|
34
|
+
const DECLARATION = /\.d\.(?:[^./]+\.)?[cm]?ts$/u
|
|
35
|
+
// A comment that may be a directive (`/// <reference .../>`) or a pragma
|
|
36
|
+
// (`//# sourceMappingURL=`, and its legacy `//@` and block forms).
|
|
37
|
+
const STEERING = /^\/(?:\/\/|[/*][#@])/u
|
|
38
|
+
const BLANK = /^\s*$/u
|
|
39
|
+
|
|
40
|
+
const tree = file => (file ? [{ name: file.path, data: file.text }] : [])
|
|
41
|
+
|
|
42
|
+
export function typeOnlyStamped(from, to) {
|
|
43
|
+
const changes = compareTrees(tree(from), tree(to), { paths: 'keys', lines: false, renames: Number.MIN_VALUE })
|
|
44
|
+
return changes.length > 0 && changes.every(change => change.typeOnly === true)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The lines of a text proven to hold types alone but for what runs that hold
|
|
48
|
+
// any of that, as merged ranges (`lines`), and its triple-slash comments, by
|
|
49
|
+
// whether each leads it (`leading`, `below`). Stripping blanks what it erases
|
|
50
|
+
// in place, each character to a blank, so a statement it leaves blank is
|
|
51
|
+
// erased and one it leaves anything of runs, as the proof found, and a comment
|
|
52
|
+
// it leaves is kept; what it reads starts past a byte order mark, and so do
|
|
53
|
+
// the offsets in its tree.
|
|
54
|
+
function runLines(text) {
|
|
55
|
+
const shift = text.startsWith('') ? 1 : 0
|
|
56
|
+
const body = text.slice(shift)
|
|
57
|
+
const code = stripTypeScriptTypes(body, { mode: 'strip' })
|
|
58
|
+
const { program, comments } = parseSync('file.ts', body, { lang: 'ts', sourceType: 'module' })
|
|
59
|
+
const kept = ({ start, end }) => code.slice(start, end)
|
|
60
|
+
const steering = comments.filter(comment => STEERING.test(kept(comment)))
|
|
61
|
+
const spans = [...program.hashbang ? [program.hashbang] : [], ...program.body.filter(statement => !BLANK.test(kept(statement))), ...steering]
|
|
62
|
+
const starts = [0]
|
|
63
|
+
for (let at = text.indexOf('\n'); at !== -1; at = text.indexOf('\n', at + 1)) starts.push(at + 1)
|
|
64
|
+
// The line an offset of the text is on: the last whose start is at most it.
|
|
65
|
+
const lineAt = offset => {
|
|
66
|
+
let high = starts.length - 1, low = 0
|
|
67
|
+
while (low < high) {
|
|
68
|
+
const mid = Math.ceil((low + high) / 2)
|
|
69
|
+
if (starts[mid] <= offset) low = mid
|
|
70
|
+
else high = mid - 1
|
|
71
|
+
}
|
|
72
|
+
return low
|
|
73
|
+
}
|
|
74
|
+
const ranges = []
|
|
75
|
+
for (const { start, end } of spans.toSorted((a, b) => a.start - b.start)) {
|
|
76
|
+
const from = lineAt(shift + start), to = lineAt(shift + Math.max(start, end - 1)) + 1
|
|
77
|
+
const last = ranges.at(-1)
|
|
78
|
+
if (last && from <= last[1]) last[1] = Math.max(last[1], to)
|
|
79
|
+
else ranges.push([from, to])
|
|
80
|
+
}
|
|
81
|
+
// Its triple-slash comments, by their text: those that lead it, before its
|
|
82
|
+
// first statement, where alone a directive steers, and those below one.
|
|
83
|
+
const first = program.body[0]?.start ?? Infinity
|
|
84
|
+
const slashed = leads => new Set(steering.filter(comment => (comment.start < first) === leads).map(kept).filter(comment => comment.startsWith('///')))
|
|
85
|
+
return { lines: ranges, leading: slashed(true), below: slashed(false) }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Whether a triple-slash comment that leads `one` side stands only below a
|
|
89
|
+
// statement on the `other`: a directive that steers on one alone, though its
|
|
90
|
+
// line reads the same on both.
|
|
91
|
+
const moved = (one, other) => [...one.leading].some(comment => !other.leading.has(comment) && other.below.has(comment))
|
|
92
|
+
|
|
93
|
+
// `{ runs, otherRuns }` where each side there is a declaration file proven to
|
|
94
|
+
// hold types alone but for what runs, and no directive steers on one side
|
|
95
|
+
// alone unseen (`moved`); else false, and where the proof throws, as no
|
|
96
|
+
// check should. Asked of a pair not stamped, which always runs some.
|
|
97
|
+
export function typeOnlyRuns(from, to) {
|
|
98
|
+
const sides = [from, to].filter(file => file !== null)
|
|
99
|
+
if (sides.length === 0 || !sides.every(file => DECLARATION.test(file.path))) return false
|
|
100
|
+
try {
|
|
101
|
+
if (!sides.every(file => proveTypeOnly(file.text).proven)) return false
|
|
102
|
+
const [base, other] = [from, to].map(file => (file ? runLines(file.text) : null))
|
|
103
|
+
if (base && other && (moved(base, other) || moved(other, base))) return false
|
|
104
|
+
return { runs: base?.lines ?? [], otherRuns: other?.lines ?? [] }
|
|
105
|
+
} catch {
|
|
106
|
+
return false
|
|
107
|
+
}
|
|
108
|
+
}
|
|
@@ -1,19 +1,31 @@
|
|
|
1
1
|
// Which of a comparison's pairs of files changed in types alone (type-only.ts),
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
2
|
+
// off the server's event loop, as type-only-proof.js tells each. Told first,
|
|
3
|
+
// `{ stamped }`, is whether each is stamped, by pair: what runs is worked out
|
|
4
|
+
// after, so that it cannot cost a stamp the worker's deadline, however long
|
|
5
|
+
// one file's takes. Then, where asked for (`runsUntil` a time, not null),
|
|
6
|
+
// what runs of each pair not stamped, `{ at, runs, otherRuns }` as each is
|
|
7
|
+
// found, the smallest files first, so that one that takes long keeps the
|
|
8
|
+
// fewest waiting, and none begun once `runsUntil` has come. Last, its answer,
|
|
9
|
+
// by pair: `true`, `{ runs, otherRuns }` for one that holds types alone but
|
|
10
|
+
// for what runs, or `false`, as for one not asked for or not come to.
|
|
9
11
|
import { parentPort, workerData } from 'node:worker_threads'
|
|
10
|
-
import {
|
|
12
|
+
import { typeOnlyRuns, typeOnlyStamped } from './type-only-proof.js'
|
|
11
13
|
|
|
12
|
-
const
|
|
13
|
-
const answer = workerData.pairs.map(([from, to]) => {
|
|
14
|
-
const changes = compareTrees(tree(from), tree(to), { paths: 'keys', lines: false, renames: Number.MIN_VALUE })
|
|
15
|
-
return changes.length > 0 && changes.every(change => change.typeOnly === true)
|
|
16
|
-
})
|
|
14
|
+
const { pairs, runsUntil } = workerData
|
|
17
15
|
// Node worker messages have no browser target origin.
|
|
18
16
|
// oxlint-disable-next-line unicorn/require-post-message-target-origin
|
|
19
|
-
parentPort.postMessage(
|
|
17
|
+
const tell = told => parentPort.postMessage(told)
|
|
18
|
+
const answer = pairs.map(([from, to]) => typeOnlyStamped(from, to))
|
|
19
|
+
tell({ stamped: answer })
|
|
20
|
+
if (runsUntil !== null) {
|
|
21
|
+
const size = ([from, to]) => (from?.text.length ?? 0) + (to?.text.length ?? 0)
|
|
22
|
+
const rest = [...pairs.keys()].filter(at => !answer[at]).toSorted((a, b) => size(pairs[a]) - size(pairs[b]))
|
|
23
|
+
for (const at of rest) {
|
|
24
|
+
if (Date.now() >= runsUntil) break
|
|
25
|
+
const runs = typeOnlyRuns(...pairs[at])
|
|
26
|
+
if (!runs) continue
|
|
27
|
+
answer[at] = runs
|
|
28
|
+
tell({ at, ...runs })
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
tell(answer)
|