@preventive/triage 1.0.0-alpha.71 → 1.0.0-alpha.73

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 (145) hide show
  1. package/common/bundle-sources.d.ts +2 -0
  2. package/common/bundle-sources.js +19 -2
  3. package/common/finding-duplicates.js +5 -0
  4. package/common/finding-filters.js +45 -4
  5. package/common/line-diff.d.ts +2 -2
  6. package/common/line-diff.js +20 -8
  7. package/common/managed/finding-detail.js +1 -1
  8. package/common/managed/review-view-routes.js +23 -0
  9. package/common/managed/risk-routes.js +30 -0
  10. package/common/managed/routes.js +11 -6
  11. package/common/managed/team-app.d.ts +8 -6
  12. package/common/managed/team-app.js +15 -3
  13. package/common/stasis-files.d.ts +5 -0
  14. package/common/stasis-files.js +20 -0
  15. package/common/stasis-tgz.d.ts +6 -0
  16. package/common/stasis-tgz.js +27 -0
  17. package/common/workspace-app.js +20 -0
  18. package/out/activity.js +2 -4
  19. package/out/{chunk-2F3CYNPZ.js → chunk-2IHCVA3Y.js} +1 -1
  20. package/out/{chunk-HAZKDK4M.js → chunk-2V6Q4ZOZ.js} +1 -1
  21. package/out/{chunk-RRBIJL2B.js → chunk-4IW3VD3H.js} +1 -1
  22. package/out/chunk-4YZOXAXR.js +2 -0
  23. package/out/chunk-5NUDNLJA.js +6 -0
  24. package/out/chunk-5YP7P5KA.js +1 -0
  25. package/out/chunk-6VOB5WXX.js +2 -0
  26. package/out/chunk-74JZTGTO.js +11 -0
  27. package/out/chunk-7YFJUT2P.js +1 -0
  28. package/out/chunk-A4BBBHQU.js +1 -0
  29. package/out/{chunk-4ISO5F7Y.js → chunk-ADMVRLNP.js} +1 -1
  30. package/out/chunk-BIWPZT4E.js +52 -0
  31. package/out/{chunk-HETCVNO4.js → chunk-BLPHP4U3.js} +1 -1
  32. package/out/{chunk-Y5ZHFNBD.js → chunk-BXQCCW7F.js} +1 -1
  33. package/out/{chunk-JFL7WLRV.js → chunk-CU3FPB3P.js} +1 -1
  34. package/out/chunk-CXVBTUK3.js +4 -0
  35. package/out/{chunk-M37X4LCF.js → chunk-EXQQ5VQJ.js} +1 -1
  36. package/out/{chunk-NXATZJQ2.js → chunk-GSNSP3EF.js} +1 -1
  37. package/out/chunk-GV5U7OLP.js +40 -0
  38. package/out/{chunk-JOXLZXMI.js → chunk-GX5UXWT4.js} +1 -1
  39. package/out/{chunk-YF4M5OCI.js → chunk-I6UQQKAH.js} +1 -1
  40. package/out/{chunk-UCP3JRE2.js → chunk-LVW7WWV4.js} +1 -1
  41. package/out/chunk-NEFCZAIY.js +11 -0
  42. package/out/{chunk-TOXMUOIW.js → chunk-OQS2USZM.js} +1 -1
  43. package/out/chunk-PQPKHAI5.js +15 -0
  44. package/out/chunk-PX5DLFSD.js +1 -0
  45. package/out/chunk-QBFT2DDR.js +1 -0
  46. package/out/{chunk-GZ46SSTF.js → chunk-RGNF4OH6.js} +1 -1
  47. package/out/chunk-RLLA4GHZ.js +1 -0
  48. package/out/chunk-ROHACH7V.js +3 -0
  49. package/out/chunk-ROWUGPID.js +1 -0
  50. package/out/{chunk-QMVOEBWC.js → chunk-S2ZIKK45.js} +1 -1
  51. package/out/chunk-SSPDMA6D.js +1 -0
  52. package/out/chunk-TD7RVUTT.js +2 -0
  53. package/out/{chunk-4XIH7YTX.js → chunk-UH6NZBSU.js} +1 -1
  54. package/out/{chunk-M3Y6SLC4.js → chunk-UJP4PQJA.js} +1 -1
  55. package/out/{chunk-PAD2JHZT.js → chunk-UJSJMXEG.js} +1 -1
  56. package/out/{chunk-E3LFSUDJ.js → chunk-VYYUMYVW.js} +1 -1
  57. package/out/{chunk-VRX2APNA.js → chunk-XVKDPU4D.js} +1 -1
  58. package/out/chunk-Y2XGV3RC.js +8 -0
  59. package/out/chunk-YCEMQETS.js +255 -0
  60. package/out/client-managed-import.js +3 -3
  61. package/out/client-managed.js +30 -27
  62. package/out/compare.js +16 -25
  63. package/out/dialogs.js +38 -38
  64. package/out/graph.js +14 -14
  65. package/out/index.html +32 -52
  66. package/out/scan.js +2 -2
  67. package/out/terminal.js +239 -240
  68. package/out/view.css +1 -1
  69. package/out/view.js +15 -15
  70. package/package.json +21 -13
  71. package/risk/actions/resolve.js +56 -19
  72. package/risk/actions/uses.js +27 -9
  73. package/risk/actions/workflow.js +75 -2
  74. package/risk/files/characters.js +11 -0
  75. package/risk/files/hosts.js +4 -4
  76. package/risk/files/readability.js +5 -2
  77. package/risk/files/runs-code.js +12 -25
  78. package/risk/files/script.js +141 -19
  79. package/risk/files/source-map-link.js +43 -0
  80. package/risk/index.d.ts +24 -7
  81. package/risk/index.js +1 -0
  82. package/risk/npm/assess.js +1 -1
  83. package/risk/npm/compare.js +9 -30
  84. package/risk/npm/diff.js +1 -1
  85. package/risk/npm/held.js +6 -2
  86. package/risk/npm/registry.js +5 -2
  87. package/risk/npm/tarball.js +79 -22
  88. package/server-managed/bundle-advisories.ts +12 -36
  89. package/server-managed/bundle-build-worker.js +29 -11
  90. package/server-managed/bundle-build.ts +4 -3
  91. package/server-managed/bundle-cache.ts +53 -13
  92. package/server-managed/bundle.ts +45 -13
  93. package/server-managed/comparison.ts +3 -3
  94. package/server-managed/db-methods.ts +54 -17
  95. package/server-managed/db-neon.ts +9 -2
  96. package/server-managed/db-schema.ts +12 -2
  97. package/server-managed/db.ts +4 -1
  98. package/server-managed/dependency-reviews.ts +8 -5
  99. package/server-managed/github-errors.ts +22 -0
  100. package/server-managed/github-requests.ts +4 -2
  101. package/server-managed/http.ts +336 -76
  102. package/server-managed/management.ts +10 -4
  103. package/server-managed/npm-delta.ts +17 -2
  104. package/server-managed/npm-kept.ts +6 -0
  105. package/server-managed/npm-packages.ts +30 -29
  106. package/server-managed/npm-patch.ts +9 -9
  107. package/server-managed/package-entry-points.ts +54 -6
  108. package/server-managed/pull-dependencies.ts +4 -1
  109. package/server-managed/rename-diff-worker.js +11 -7
  110. package/server-managed/rename-diff.ts +5 -4
  111. package/server-managed/report-opening.ts +77 -0
  112. package/server-managed/report-sources.ts +2 -1
  113. package/server-managed/repository-aliases.ts +34 -0
  114. package/server-managed/repository-browser.ts +87 -32
  115. package/server-managed/repository-code.ts +6 -3
  116. package/server-managed/repository-dependency-reviews.ts +21 -0
  117. package/server-managed/repository-issues.ts +15 -9
  118. package/server-managed/repository-risk-read.ts +50 -4
  119. package/server-managed/repository-risk.ts +9 -2
  120. package/server-managed/stasis-config.ts +97 -5
  121. package/server-managed/stasis-dependencies.ts +7 -4
  122. package/server-managed/team-reports.ts +5 -3
  123. package/server-managed/type-only-proof.js +26 -4
  124. package/server-managed/upstream-cache.ts +18 -12
  125. package/server-managed/workspace-shares.ts +4 -4
  126. package/out/chunk-2HGKTQ5Q.js +0 -52
  127. package/out/chunk-45HTR22K.js +0 -4
  128. package/out/chunk-4RS3NDOG.js +0 -1
  129. package/out/chunk-7GJNLCXF.js +0 -15
  130. package/out/chunk-CGRIZ5M5.js +0 -1
  131. package/out/chunk-CQIT5UNK.js +0 -1
  132. package/out/chunk-D6NVKGGG.js +0 -10
  133. package/out/chunk-DTAR2BB6.js +0 -247
  134. package/out/chunk-MPXVKVPF.js +0 -3
  135. package/out/chunk-NB4JBTKK.js +0 -2
  136. package/out/chunk-QPGM3DTI.js +0 -42
  137. package/out/chunk-VFWMQ3LG.js +0 -2
  138. package/out/chunk-VG5RH6KN.js +0 -2
  139. package/out/chunk-WFDXHPT2.js +0 -12
  140. package/out/chunk-WMFDQS2L.js +0 -11
  141. package/out/chunk-WREU7JAG.js +0 -1
  142. /package/out/{chunk-JMG5DXII.js → chunk-7HP2VYIC.js} +0 -0
  143. /package/out/{chunk-HOB3YPS5.js → chunk-K4XJHM2T.js} +0 -0
  144. /package/out/{chunk-4EMM6UCD.js → chunk-QI66YA4F.js} +0 -0
  145. /package/out/{chunk-G3LY2FV4.js → chunk-WCDYSIKG.js} +0 -0
@@ -1,9 +1,9 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import type { ManagedConfig } from './config.ts'
3
3
  import type { SelectedRepo } from './db.ts'
4
- import { type GithubIdentity, READ_PERMISSIONS, githubRepoPermission, githubUserIdentity, repoAccessToken } from './github-app.ts'
5
- import { GithubApiError } from './github-errors.ts'
6
- import { encodedPath, githubJson, onTokenRejected, repoApi } from './github-requests.ts'
4
+ import { type GithubIdentity, READ_PERMISSIONS, githubRepoPermission, githubUserIdentity, publicRepositoryName, repoAccessToken } from './github-app.ts'
5
+ import { GithubApiError, isGithubMoved } from './github-errors.ts'
6
+ import { GITHUB_API, encodedPath, githubJson, onTokenRejected, repoApi } from './github-requests.ts'
7
7
  import { SHA } from './github-values.ts'
8
8
  import { MAX_PACKAGE_BYTES, readConfigEntryPoints, readPackageEntryPoints } from './package-entry-points.ts'
9
9
  import { MAX_STASIS_CONFIG_BYTES, STASIS_CONFIG } from './stasis-config.ts'
@@ -41,6 +41,16 @@ export function scopedDirectory(path: string, scopes: (string | null)[]): Reposi
41
41
 
42
42
  interface RepositoryBrowserUser { githubUserId: number | null; token: string | null }
43
43
 
44
+ // Told of a repository GitHub renamed or transferred since it was connected,
45
+ // once a reader has named it as GitHub names it now (`repo`, its `fullName`
46
+ // and `htmlUrl`): its name before (`from`), and whether GitHub still sends
47
+ // that name to it (`redirected`), as it does unless another repository has
48
+ // taken the name since. For the name to be kept (http.ts).
49
+ export type RepositoryRenamed = (repo: SelectedRepo, from: string, redirected: boolean) => Promise<void>
50
+
51
+ // A repository's page on GitHub, by its name.
52
+ export const githubRepositoryUrl = (fullName: string) => `https://github.com/${fullName}`
53
+
44
54
  function credentialFailure(err: unknown): err is GithubApiError {
45
55
  return err instanceof GithubApiError && ([401, 404].includes(err.status) || err.message === 'github-status-403')
46
56
  }
@@ -74,16 +84,20 @@ function verdictCache(config: ManagedConfig, user: RepositoryBrowserUser, repo:
74
84
  if (!(keepMs > 0)) return null
75
85
  const kept = accessVerdicts.get(fetchImpl) ?? new Map<string, AccessVerdict>()
76
86
  accessVerdicts.set(fetchImpl, kept)
77
- // The token hashed with the rest, never kept as it is.
78
- const key = createHash('sha256').update(JSON.stringify([user.githubUserId, user.token, repo.repoId, repo.fullName.toLowerCase(), repo.installationId, config.githubAppId])).digest('hex')
87
+ // The token hashed with the rest, never kept as it is; the repository by
88
+ // its name as the reader names it now (currentMetadata).
89
+ const keyed = () => createHash('sha256').update(JSON.stringify([user.githubUserId, user.token, repo.repoId, repo.fullName.toLowerCase(), repo.installationId,
90
+ config.githubAppId])).digest('hex')
79
91
  return {
80
92
  get() {
93
+ const key = keyed()
81
94
  const verdict = kept.get(key)
82
95
  if (verdict && verdict.until > Date.now()) return verdict
83
96
  kept.delete(key)
84
97
  return undefined
85
98
  },
86
99
  set(verdict) {
100
+ const key = keyed()
87
101
  kept.delete(key)
88
102
  kept.set(key, { ...verdict, until: Date.now() + keepMs, userToken: user.token ? hashed(user.token) : null })
89
103
  while (kept.size > MAX_ACCESS_VERDICTS) kept.delete(kept.keys().next().value!)
@@ -93,8 +107,11 @@ function verdictCache(config: ManagedConfig, user: RepositoryBrowserUser, repo:
93
107
 
94
108
  // Create once per HTTP request. Coalesce concurrent credential lookups, and
95
109
  // keep GitHub's answer on each user's access to each repository a while
96
- // (verdictCache), never sharing credentials or answers across users.
97
- export function createRepositoryBrowser(config: ManagedConfig, user: RepositoryBrowserUser, fetchImpl: typeof fetch = globalThis.fetch) {
110
+ // (verdictCache), never sharing credentials or answers across users. A
111
+ // repository GitHub renamed or transferred is read by the name GitHub gives
112
+ // it now, `renamed` told (currentMetadata).
113
+ export function createRepositoryBrowser(config: ManagedConfig, user: RepositoryBrowserUser, fetchImpl: typeof fetch = globalThis.fetch,
114
+ renamed?: RepositoryRenamed) {
98
115
  const tokens = new Map<number, Promise<string | null>>()
99
116
  let identity: Promise<GithubIdentity> | undefined
100
117
  // The user as GitHub tells them, asked once a request.
@@ -109,6 +126,9 @@ export function createRepositoryBrowser(config: ManagedConfig, user: RepositoryB
109
126
  return identity
110
127
  }
111
128
  return {
129
+ // A reader of `repo`, which, where GitHub renamed or transferred it,
130
+ // names `repo` as GitHub does now (its `fullName` and `htmlUrl`), for the
131
+ // reads a request makes of it beside the reader's.
112
132
  reader(repo: SelectedRepo) {
113
133
  const installationToken = () => {
114
134
  if (repo.installationId == null) return Promise.resolve(null)
@@ -124,7 +144,7 @@ export function createRepositoryBrowser(config: ManagedConfig, user: RepositoryB
124
144
  // Its Dependabot alerts, with the token of the installation GitHub tells
125
145
  // covers it, where the user's own access lets them see them
126
146
  // (dependabot-access.ts).
127
- return repositoryReader(repo, user.token, installationToken, getIdentity, fetchImpl, verdictCache(config, user, repo, fetchImpl)).then(reader => ({ ...reader,
147
+ return repositoryReader(repo, user.token, installationToken, getIdentity, fetchImpl, verdictCache(config, user, repo, fetchImpl), renamed).then(reader => ({ ...reader,
128
148
  dependabotAlerts: () => appDependabotAlerts(config, repo, { identity: getIdentity, permission: reader.permission }, fetchImpl) }))
129
149
  },
130
150
  }
@@ -151,27 +171,51 @@ export async function repositoryTreeFiles(fullName: string, token: string | null
151
171
 
152
172
  type Access = { data: RepoMetadata; token: string | null; level: string | null }
153
173
 
174
+ // The metadata of `repo` as GitHub has it now (`metadata`, of a URL): asked by
175
+ // its name, else, where GitHub moved that name (a rename or a transfer:
176
+ // github-moved) or names another repository by it since, by its id,
177
+ // which neither changes. Where GitHub names it otherwise now, `repo` is named
178
+ // so, and `renamed` told. Throws where GitHub tells of no repository of its id.
179
+ async function currentMetadata(repo: SelectedRepo, metadata: (url: string) => Promise<unknown>, renamed: RepositoryRenamed | undefined): Promise<RepoMetadata> {
180
+ let movedTo: number | null = null, named: RepoMetadata | null = null
181
+ try { named = await metadata(repoApi(repo.fullName)) as RepoMetadata } catch (err) {
182
+ if (!isGithubMoved(err)) throw err
183
+ movedTo = err.movedTo
184
+ }
185
+ const data = named?.id === repo.repoId ? named : await metadata(`${GITHUB_API}/repositories/${repo.repoId}`) as RepoMetadata
186
+ if (data?.id !== repo.repoId || typeof data.full_name !== 'string') throw new GithubApiError(404, 'no-repository')
187
+ if (data.full_name !== repo.fullName) {
188
+ // Only a name of GitHub's form is ever read by, or kept.
189
+ if (publicRepositoryName(data.full_name) !== data.full_name) throw new GithubApiError(502, 'github-malformed')
190
+ const from = repo.fullName
191
+ repo.fullName = data.full_name
192
+ repo.htmlUrl = githubRepositoryUrl(data.full_name)
193
+ await renamed?.(repo, from, movedTo === repo.repoId || named?.id === repo.repoId)
194
+ }
195
+ return data
196
+ }
197
+
154
198
  // GitHub asked whether the user may read `repo`: its metadata, read with
155
199
  // `token` (the reader's credential so far), else the installation's, else
156
- // none; and of one not public, the user's permission, read with the
157
- // installation's. What it told, the token reading it, and the level asked.
200
+ // none (currentMetadata, `repo` named as GitHub names it now); and of one not
201
+ // public, the user's permission, read with the installation's. What it told,
202
+ // the token reading it, and the level asked.
158
203
  async function askAccess(repo: SelectedRepo, start: string | null, userToken: string | null, installationToken: () => Promise<string | null>,
159
- getIdentity: () => Promise<GithubIdentity>, fetchImpl: typeof fetch): Promise<Access> {
160
- const base = repoApi(repo.fullName)
204
+ getIdentity: () => Promise<GithubIdentity>, fetchImpl: typeof fetch, renamed: RepositoryRenamed | undefined): Promise<Access> {
161
205
  let token = start
162
- const metadata = async () => {
163
- try { return await githubJson(base, token, fetchImpl) }
206
+ const metadata = async (url: string) => {
207
+ try { return await githubJson(url, token, fetchImpl) }
164
208
  catch (err) {
165
209
  if (!token || !credentialFailure(err)) throw err
166
210
  const fallback = await installationToken()
167
211
  if (fallback && fallback !== token) {
168
212
  token = fallback
169
- try { return await githubJson(base, token, fetchImpl) } catch (fallbackError) { if (!credentialFailure(fallbackError)) throw fallbackError }
213
+ try { return await githubJson(url, token, fetchImpl) } catch (fallbackError) { if (!credentialFailure(fallbackError)) throw fallbackError }
170
214
  }
171
215
  // Anonymous fallback is only for unavailable credentials, never rate
172
216
  // limits, network errors, or GitHub outages.
173
217
  token = null
174
- return githubJson(base, token, fetchImpl)
218
+ return githubJson(url, token, fetchImpl)
175
219
  }
176
220
  }
177
221
  // A repository last known private asks who the user is, and mints the
@@ -186,10 +230,7 @@ async function askAccess(repo: SelectedRepo, start: string | null, userToken: st
186
230
  }
187
231
  // Stored visibility can be stale (or internal with private=false). Require
188
232
  // current, explicit public visibility or the caller's effective permission.
189
- const data = await metadata() as RepoMetadata
190
- if (data?.id !== repo.repoId || typeof data.full_name !== 'string' || data.full_name.toLowerCase() !== repo.fullName.toLowerCase()) {
191
- throw new GithubApiError(404, 'no-repository')
192
- }
233
+ const data = await currentMetadata(repo, metadata, renamed)
193
234
  if (data.private === false && data.visibility === 'public') return { data, token, level: null }
194
235
  if (!token) throw new GithubApiError(404, 'no-repository')
195
236
  const appToken = await installationToken()
@@ -200,11 +241,11 @@ async function askAccess(repo: SelectedRepo, start: string | null, userToken: st
200
241
  }
201
242
 
202
243
  // GitHub's answer as kept (verdictCache), with the credential it chose,
203
- // where that credential is still had; else asked (`ask`), and kept where it
204
- // grants access.
244
+ // where that credential is still had, and not asked afresh (`fresh`); else
245
+ // asked (`ask`), and kept where it grants access.
205
246
  async function keptAccess(verdicts: VerdictCache | null, userToken: string | null, installationToken: () => Promise<string | null>,
206
- ask: () => Promise<Access>): Promise<Access> {
207
- const kept = verdicts?.get()
247
+ ask: () => Promise<Access>, fresh = false): Promise<Access> {
248
+ const kept = fresh ? undefined : verdicts?.get()
208
249
  if (kept) {
209
250
  const credential = kept.credential === 'user' ? userToken : kept.credential === 'app' ? await installationToken() : null
210
251
  if (kept.credential === 'none' || credential) return { data: kept.data, token: credential, level: kept.level }
@@ -217,25 +258,38 @@ async function keptAccess(verdicts: VerdictCache | null, userToken: string | nul
217
258
  }
218
259
 
219
260
  async function repositoryReader(repo: SelectedRepo, userToken: string | null, installationToken: () => Promise<string | null>, getIdentity: () => Promise<GithubIdentity>, fetchImpl: typeof fetch,
220
- verdicts: VerdictCache | null) {
221
- const base = repoApi(repo.fullName)
261
+ verdicts: VerdictCache | null, renamed: RepositoryRenamed | undefined) {
222
262
  // Public reads can use the signed-in user's quota without repository grants.
223
263
  // Nonpublic reads still require the repository App and the effective-user gate,
224
264
  // whose permission level is kept (`level`).
225
265
  let level: string | null = null, token = userToken ?? await installationToken()
226
- const read = (suffix: string) => githubJson(base + suffix, token, fetchImpl)
227
- const checkAccess = async (): Promise<RepoMetadata> => {
228
- const access = await keptAccess(verdicts, userToken, installationToken, () => askAccess(repo, token, userToken, installationToken, getIdentity, fetchImpl))
266
+ const checkAccess = async (fresh = false): Promise<RepoMetadata> => {
267
+ const access = await keptAccess(verdicts, userToken, installationToken, () => askAccess(repo, token, userToken, installationToken, getIdentity, fetchImpl, renamed),
268
+ fresh)
229
269
  token = access.token
230
270
  level = access.level
231
271
  return access.data
232
272
  }
273
+ // Each read by the name GitHub gives the repository now. Access kept from
274
+ // before GitHub moved that name (verdictCache) is asked again where a read
275
+ // finds it moved, once a reader, which finds the name it has now
276
+ // (currentMetadata); the read is made again by that name.
277
+ let asking: Promise<unknown> | undefined
278
+ const read = async (suffix: string) => {
279
+ const name = repo.fullName
280
+ try { return await githubJson(repoApi(name) + suffix, token, fetchImpl) } catch (err) {
281
+ if (!isGithubMoved(err)) throw err
282
+ await (asking ??= checkAccess(true))
283
+ if (repo.fullName === name) throw err
284
+ return githubJson(repoApi(repo.fullName) + suffix, token, fetchImpl)
285
+ }
286
+ }
233
287
  const current = await checkAccess()
234
288
  const defaultBranch = typeof current.default_branch === 'string' ? current.default_branch : ''
235
289
  return {
236
290
  // Its visibility and the user's permission asked again, the user as
237
291
  // GitHub told them earlier in the request, not asked again.
238
- recheckAccess: checkAccess,
292
+ recheckAccess: () => checkAccess(),
239
293
  // Server-only credential, selected by the same live visibility/permission
240
294
  // gate as directory browsing. Never included in an HTTP response.
241
295
  readToken: () => token,
@@ -286,9 +340,10 @@ async function repositoryReader(repo: SelectedRepo, userToken: string | null, in
286
340
  && item.type === 'file' && !item.submodule_git_url && typeof item.size === 'number' && item.size >= 0 && item.size <= maxBytes
287
341
  && typeof item.sha === 'string' && /^[a-f\d]{40}$/iu.test(item.sha))
288
342
  // The entries stasis.config.json lists are suggested before any guess:
289
- // a build takes them alone, with their options there.
343
+ // a build takes them alone, with their options there. Its patterns
344
+ // are matched in this listing, and the trees it names.
290
345
  const config = listed(STASIS_CONFIG, MAX_STASIS_CONFIG_BYTES)
291
- const configEntryPoints = config ? await readConfigEntryPoints(config.sha, path, read) : []
346
+ const configEntryPoints = config ? await readConfigEntryPoints(config.sha, path, read, data) : []
292
347
  if (configEntryPoints.length > 0) return { entries, limited: data.length >= 1000, configEntryPoints }
293
348
  const manifest = listed('package.json', MAX_PACKAGE_BYTES)
294
349
  // Both optional suggestions, read together: neither fails, each
@@ -46,8 +46,11 @@ interface RepositoryCodeInput { repoId: number; repo: string; commit: string; pa
46
46
 
47
47
  // A package's refusals, as a directory's: past the bounds, or an archive
48
48
  // @preventive/archive refuses, as it does one holding a symlink that climbs
49
- // past the repository's root, or an absolute one.
50
- const DIRECTORY_ERRORS: Record<string, [number, string]> = { 'package-too-large': [413, 'directory-too-large'], 'bad-tarball': [422, 'directory-unreadable'] }
49
+ // past the repository's root, or an absolute one, or one readNpmTar does as
50
+ // installers would lay it out other than as one set of files, which GitHub's
51
+ // archives, under one top directory with no hard links, never are.
52
+ const DIRECTORY_ERRORS: Record<string, [number, string]> = { 'package-too-large': [413, 'directory-too-large'], 'bad-tarball': [422, 'directory-unreadable'],
53
+ 'tarball-conflict': [422, 'directory-unreadable'] }
51
54
  const directoryError = (err: unknown) => {
52
55
  const as = err instanceof NpmPackageError ? DIRECTORY_ERRORS[err.message] : undefined
53
56
  return as ? new NpmPackageError(...as) : err
@@ -78,7 +81,7 @@ export function loadRepositoryCodeBody(input: RepositoryCodeInput, tarball: (sym
78
81
 
79
82
  // The form of the bodies kept, bumped as what a body holds changes
80
83
  // (npmFileRows): one kept in another is none to read.
81
- const KEPT_CODE_VERSION = 1
84
+ const KEPT_CODE_VERSION = 2
82
85
  // The largest body kept. Source text runs, as brotli's JSON, to a third of
83
86
  // its bytes or less, and a directory's binary files are named, not held, so
84
87
  // this keeps one of some 200 MiB of text: nearly every directory that opens
@@ -62,6 +62,10 @@ export interface RepositoryDependencyReviewStore {
62
62
  // Which of `users` publish reviews to a team counting for repository
63
63
  // `repoId`, whose reviews its pull requests' comments make count.
64
64
  listRepoReviewers(repoId: number, users: string[]): Promise<Set<string>>
65
+ // Those of `versions` whose reviews published to a team counting for any of
66
+ // `repoIds` were published, to it or to one more team, or revoked, at
67
+ // `since` or after, each once.
68
+ changedReviewVersions(repoIds: number[], since: number, versions: ReviewedVersionKey[]): Promise<ReviewedVersionKey[]>
65
69
  }
66
70
 
67
71
  type SettingRow = { repoId: number; enabled: number; required: number; since: string | null; lockfiles: string | null }
@@ -148,6 +152,23 @@ export function repositoryDependencyReviewMethods(db: ManagedSql): RepositoryDep
148
152
  WHERE u.id IN (${users.map(() => '?').join(',')}) AND ${reviewsIn(true)} AND ${COUNTING_TEAM}`).all(...users, repoId) as { id: string }[]
149
153
  return new Set(rows.map(row => row.id))
150
154
  },
155
+ async changedReviewVersions(repoIds, since, versions) {
156
+ if (repoIds.length === 0) return []
157
+ const found = new Map<string, ReviewedVersionKey>()
158
+ for (let at = 0; at < versions.length; at += VERSIONS_AT_ONCE) {
159
+ const asked = versions.slice(at, at + VERSIONS_AT_ONCE)
160
+ const keys = new Set(asked.map(({ name, version }) => `${name}@${version}`))
161
+ const [names, numbers] = [[...new Set(asked.map(({ name }) => name))], [...new Set(asked.map(({ version }) => version))]]
162
+ const rows = await db.prepare(`SELECT DISTINCT r.package AS name, r.version FROM managed_dependency_review r
163
+ WHERE r.ecosystem = 'npm' AND r.published_at IS NOT NULL AND (r.published_at >= ? OR r.shared_at >= ? OR r.revoked_at >= ?)
164
+ AND r.package IN (${names.map(() => '?').join(',')}) AND r.version IN (${numbers.map(() => '?').join(',')})
165
+ AND EXISTS (SELECT 1 FROM managed_dependency_review_team rt JOIN managed_team t ON t.id = rt.team_id JOIN managed_team_repo tr ON tr.team_id = t.id
166
+ WHERE rt.review_id = r.id AND t.hidden = 0 AND t.dependency_review = 1 AND tr.repo_id IN (${repoIds.map(() => '?').join(',')}))`)
167
+ .all(since, since, since, ...names, ...numbers, ...repoIds) as ReviewedVersionKey[]
168
+ for (const row of rows) if (keys.has(`${row.name}@${row.version}`)) found.set(`${row.name}@${row.version}`, row)
169
+ }
170
+ return [...found.values()]
171
+ },
151
172
  async repoDependencyReviewState(repoId, user, versions, read) {
152
173
  const now = read === undefined ? await readSetting(repoId) : read
153
174
  if (!now?.enabled) return null
@@ -67,7 +67,7 @@ type Node = ReviewNode & { number?: unknown; title?: unknown; createdAt?: unknow
67
67
  isDraft?: unknown; reviewDecision?: unknown; additions?: unknown; deletions?: unknown; headRefName?: unknown; baseRefName?: unknown; baseRefOid?: unknown; isCrossRepository?: unknown
68
68
  commits?: { nodes?: { commit?: { statusCheckRollup?: { state?: unknown } | null } | null }[] }
69
69
  files?: { totalCount?: unknown; nodes?: ({ path?: unknown } | null)[] } | null }
70
- type Page = { repository?: { open?: { totalCount?: unknown }; closed?: { totalCount?: unknown }; page?: Connection<Node> } | null }
70
+ type Page = { repository?: { open?: { totalCount?: unknown }; closed?: { totalCount?: unknown }; page?: Connection<Node>; defaultBranchRef?: { name?: unknown } | null } | null }
71
71
 
72
72
  const REVIEWS: Record<string, string> = { APPROVED: 'approved', CHANGES_REQUESTED: 'changes', REVIEW_REQUIRED: 'required' }
73
73
  const CHECKS: Record<string, string> = { SUCCESS: 'success', FAILURE: 'failure', ERROR: 'failure', PENDING: 'pending', EXPECTED: 'pending' }
@@ -230,14 +230,16 @@ export async function repositoryIssues(fullName: string, token: string, kind: Is
230
230
  // A page of the open pull requests a team's Dependencies reads (http.ts
231
231
  // teamOpenPulls), those carrying `$labels` alone where it names some: each by
232
232
  // what its card there and its popup's heading tell (its number, title and
233
- // author, when it was opened and last updated, whether it is a draft), the
234
- // files by which whether it changes a lockfile is told, and its base's and
235
- // head's commits, by which what its lockfiles add is read, with the branches
236
- // they are of (commitsOf). Nothing else a tile shows (its labels, comments,
233
+ // author, when it was opened and last updated, whether it is a draft, the
234
+ // branch it is to merge into), the files by which whether it changes a
235
+ // lockfile is told, and its base's and head's commits, by which what its
236
+ // lockfiles add is read, with the branches they are of (commitsOf); and the
237
+ // repository's default branch, by its name. Nothing else a tile shows (its labels, comments,
237
238
  // size, checks, reviews, threads and comments), which GitHub is slow enough
238
239
  // to gather for fifty of a large repository's to fail the page.
239
240
  const openPullsQuery = (labelled: boolean) => `query($owner: String!, $name: String!, $first: Int!, $after: String${labelled ? ', $labels: [String!]' : ''}) {
240
241
  repository(owner: $owner, name: $name) {
242
+ defaultBranchRef { name }
241
243
  page: pullRequests(states: [OPEN], first: $first, after: $after, ${labelled ? 'labels: $labels, ' : ''}orderBy: { field: UPDATED_AT, direction: DESC }) {
242
244
  pageInfo { hasNextPage endCursor }
243
245
  nodes { number title createdAt updatedAt author { ${ACTOR} } state isDraft baseRefOid headRefOid baseRefName headRefName isCrossRepository ${files} }
@@ -245,7 +247,7 @@ const openPullsQuery = (labelled: boolean) => `query($owner: String!, $name: Str
245
247
  }
246
248
  }`
247
249
  // What a kept page of them was read as: kept ones read before differ.
248
- export const OPEN_PULLS_READ = 1
250
+ export const OPEN_PULLS_READ = 2
249
251
  // How many a page asks for: ISSUES_PAGE, then, where GitHub fails to answer
250
252
  // that many in its time, fewer, and fewer again.
251
253
  export const OPEN_PULLS_SIZES = [ISSUES_PAGE, 20, 5]
@@ -256,7 +258,8 @@ const tooSlow = (err: unknown) => err instanceof GithubApiError && SLOW.has(err.
256
258
 
257
259
  // A page of the repository's open pull requests, the latest updated first,
258
260
  // after the page `after` ended (null for the first), those carrying `label`
259
- // alone where it names one: its `items`, their commits (`commits`, commitsOf)
261
+ // alone where it names one: its `items`, their commits (`commits`, commitsOf),
262
+ // the repository's default branch (`defaultBranch`, null where it tells none)
260
263
  // and, where more follow, the cursor reading them (`after`). As many as
261
264
  // `size` asked for, then, GitHub too slow to answer, as many as each smaller
262
265
  // of OPEN_PULLS_SIZES, the last one's failure the read's; how many were
@@ -281,7 +284,10 @@ async function openPullsPage(fullName: string, token: string, after: string | nu
281
284
  const next = info?.hasNextPage === true && typeof info.endCursor === 'string' && ISSUES_CURSOR.test(info.endCursor) ? info.endCursor : null
282
285
  const pulls = (repository.page?.nodes ?? []).flatMap(node => {
283
286
  const named = itemOf(node)
284
- return node && named ? [{ node, tile: { ...named, createdAt: timeOf(node.createdAt), updatedAt: timeOf(node.updatedAt), ...pullState(node.state, node.isDraft), ...lockfileTouched(node) } }] : []
287
+ const base = nameOf(node?.baseRefName)
288
+ return node && named ? [{ node, tile: { ...named, createdAt: timeOf(node.createdAt), updatedAt: timeOf(node.updatedAt), ...pullState(node.state, node.isDraft),
289
+ ...base ? { base } : {}, ...lockfileTouched(node) } }] : []
285
290
  })
286
- return { items: pulls.map(({ tile }) => tile), commits: pulls.flatMap(({ node, tile }) => commitsOf(tile.number, node)), more: next !== null, after: next, size: first }
291
+ return { items: pulls.map(({ tile }) => tile), commits: pulls.flatMap(({ node, tile }) => commitsOf(tile.number, node)), defaultBranch: nameOf(repository.defaultBranchRef?.name),
292
+ more: next !== null, after: next, size: first }
287
293
  }
@@ -4,8 +4,10 @@
4
4
  // each read for its packages (@preventive/lockfile), and access to it checked
5
5
  // again before they are told (`recheck`); and its Dependabot alerts, open or dismissed, of
6
6
  // npm's, where the source asks them (dependabot-alerts.ts), asked meanwhile
7
- // and never kept, a failure to have them its own, and its GitHub Actions
8
- // (repository-actions.ts). A listing is kept by the commit it was listed at,
7
+ // and never kept, a failure to have them its own, its GitHub Actions
8
+ // (repository-actions.ts), and what Stasis reaches of each of its
9
+ // stasis.config.json files, where the source reads them
10
+ // (StasisConfigsRead). A listing is kept by the commit it was listed at,
9
11
  // its Actions' files too, and a lockfile's packages by its blob: in the
10
12
  // instance's memory, and the source's `listings`, `actionFiles` and
11
13
  // `lockfiles` for SCAN_READ_KEPT_MS, so that only opening a repository and
@@ -20,6 +22,9 @@ import { inTurns } from './queue.ts'
20
22
  import { type WorkflowsRead, lastingRead, readActions } from './repository-actions.ts'
21
23
  import { type RiskFailure, failureOf } from './repository-risk-assess.ts'
22
24
  import type { LockfileLine, RepositoryRiskLine, RepositoryRiskRepo } from './repository-risk.ts'
25
+ import type { StasisDependency } from './bundle-build.ts'
26
+ import { isStasisConfig } from './lockfile-scope.ts'
27
+ import type { StasisRead } from './stasis-dependencies.ts'
23
28
 
24
29
  // The formats of npm's ecosystem, as findRepoLockfiles names them, and those
25
30
  // of them read here.
@@ -40,6 +45,20 @@ export type LockfileRead = { packages: LockedPackage[] } | RiskFailure
40
45
  // be had.
41
46
  export type DependabotRead = { alerts: DependabotAlert[]; recheck?(): Promise<void> } | RiskFailure
42
47
  export type RepositoryFailure = Extract<RepositoryRiskLine, { type: 'repo'; error: string }>
48
+ // What Stasis reaches of a stasis.config.json, as a dependency review's
49
+ // build of it tells (stasis-dependencies.ts): the versions it installs
50
+ // (`dependencies`), that its build is still to be made (`pending`), or why it
51
+ // failed.
52
+ export type StasisConfigRow = { path: string } & ({ dependencies: StasisDependency[] } | { pending: true } | RiskFailure)
53
+ // A repository's stasis.config.json files, those of its `paths` alone, each
54
+ // what Stasis reaches of it, or why they couldn't be listed.
55
+ export type StasisConfigsRead = { configs: StasisConfigRow[] } | RiskFailure
56
+
57
+ // A config's row of its read: a failed build told by its code (`detail`).
58
+ export function stasisConfigRow(path: string, read: StasisRead): StasisConfigRow {
59
+ if (read.status === 'ready') return { path, dependencies: read.dependencies }
60
+ return read.status === 'pending' ? { path, pending: true } : { path, error: 'stasis-failed', detail: read.error }
61
+ }
43
62
 
44
63
  // A repository opened at its default branch's head (`commit`): its lockfiles,
45
64
  // as findRepoLockfiles lists them, each with its blob's id, and a file's
@@ -54,6 +73,12 @@ export interface OpenedRepository {
54
73
  dependabot?(): Promise<AlertsRead>
55
74
  // Its workflows' paths, none where it has none.
56
75
  workflows?(): Promise<string[]>
76
+ // Its files' paths at `commit`, of which its stasis.config.json files are
77
+ // told (isStasisConfig); and what Stasis reaches of the one at `config`,
78
+ // as a dependency review's reader has it (stasis-dependencies.ts), its
79
+ // build asked for where none is kept yet, never waited for.
80
+ files?(): Promise<string[]>
81
+ stasis?(config: string): Promise<StasisRead>
57
82
  }
58
83
 
59
84
  // What a repository is read with: the scan's source and caches, and its
@@ -74,6 +99,8 @@ export interface RepositoryRead {
74
99
  dependabot: DependabotRead | null
75
100
  // Its Actions' files, where it lists its workflows.
76
101
  actions: WorkflowsRead | null
102
+ // Its stasis.config.json files, where it has some and the source reads them.
103
+ stasis: StasisConfigsRead | null
77
104
  recheck(): Promise<void>
78
105
  }
79
106
 
@@ -143,8 +170,25 @@ async function readDependabot(opened: OpenedRepository, paths: readonly string[]
143
170
  }
144
171
  }
145
172
 
173
+ // A repository's stasis.config.json files of its `paths` (RepositoryRiskRepo),
174
+ // as its lockfiles are, each what Stasis reaches of it; or why they couldn't
175
+ // be listed; null where it has none, or the source reads none.
176
+ async function readStasis(opened: OpenedRepository, paths: readonly string[] | undefined): Promise<StasisConfigsRead | null> {
177
+ const { files, stasis } = opened
178
+ if (!files || !stasis) return null
179
+ let configs
180
+ try { configs = (await files()).filter(path => isStasisConfig(path) && lockfileOf(path, paths)) } catch (error) {
181
+ return failureOf(error, 'listing its stasis.config.json files')
182
+ }
183
+ if (configs.length === 0) return null
184
+ return { configs: await Promise.all(configs.map(async path => {
185
+ try { return stasisConfigRow(path, await stasis(path)) } catch (error) { return { path, ...failureOf(error) } }
186
+ })) }
187
+ }
188
+
146
189
  // A repository read: its lockfiles listed and read, a few at once, its
147
- // Dependabot alerts asked and its Actions read meanwhile; its line telling why where listing
190
+ // Dependabot alerts asked, its Actions read and its stasis.config.json files
191
+ // asked meanwhile; its line telling why where listing
148
192
  // failed; null where the scan stopped. A test's
149
193
  // fixture or example its reader refuses (isTestFixture) is left out, as a
150
194
  // test may keep one so on purpose.
@@ -153,6 +197,7 @@ export async function readRepository<R extends RepositoryRiskRepo>(reading: Repo
153
197
  if (!listed || 'type' in listed) return listed
154
198
  const { opened } = listed
155
199
  const alerting = readDependabot(opened, repo.paths)
200
+ const reaching = readStasis(opened, repo.paths)
156
201
  const { workflows } = opened
157
202
  const acting = workflows ? keptRead(reading.caches.actionFiles, reading.source.actionFiles, `${repo.repoId}@${opened.commit}`,
158
203
  () => readActions({ workflows, file: path => opened.file(path) }), lastingRead) : Promise.resolve(null)
@@ -166,5 +211,6 @@ export async function readRepository<R extends RepositoryRiskRepo>(reading: Repo
166
211
  }
167
212
  const dependabot = await alerting
168
213
  const actions = await acting
169
- return reading.signal.aborted ? null : { commit: opened.commit, lockfiles, dependabot, actions, recheck: () => opened.recheck() }
214
+ const stasis = await reaching
215
+ return reading.signal.aborted ? null : { commit: opened.commit, lockfiles, dependabot, actions, stasis, recheck: () => opened.recheck() }
170
216
  }
@@ -25,7 +25,12 @@
25
25
  // lockfile locks that it covers, for the page to blend them into npm's; one
26
26
  // whose alerts couldn't be had tells why, and the scan goes on. Its GitHub
27
27
  // Actions are told once its lockfiles are, the references they make
28
- // resolved as the scan goes on (repository-actions.ts).
28
+ // resolved as the scan goes on (repository-actions.ts). And what Stasis
29
+ // reaches of each of its stasis.config.json files, as its dependency review
30
+ // has a build tell it (stasis-dependencies.ts), told once its lockfiles are:
31
+ // the versions a build installs, or that it is still to be made, which isn't
32
+ // waited for, its page asking for it again (GET
33
+ // /api/admin/repositories/risk/stasis), or why it failed.
29
34
  import type { LockfileFormat } from '@preventive/upstream/github.js'
30
35
  import { type ActionsSource, type Severity, npmMalwareAdvisory } from '../risk/index.js'
31
36
  import { isNpmPackageName, isNpmPackageSpec } from '../common/managed/npm-packages.js'
@@ -38,7 +43,7 @@ import { type DownloadsSource, readyingDownloads } from './scan-downloads.ts'
38
43
  import { type AssessedPackage, type AssessingSource, BUSY_RETRIES, BUSY_WAIT_MS, RISK_KEPT_MS, type RiskFailure, assessPackage, failureOf, isBusy } from './repository-risk-assess.ts'
39
44
  import { type AdvisoryRow, type Audit, type AuditSource, auditLockfiles } from './repository-risk-audit.ts'
40
45
  import { type DependabotRead, type ListedLockfile, type LockfileRead, type OpenedRepository, type RepositoryFailure, type RepositoryRead, SCAN_READ_KEPT_MS,
41
- readRepository } from './repository-risk-read.ts'
46
+ type StasisConfigsRead, readRepository } from './repository-risk-read.ts'
42
47
  import { type DependabotAlert, alertVersions } from './dependabot-alerts.ts'
43
48
  import { type ActionAnswers, type ActionLine, type ActionRef, type WorkflowLine, type WorkflowsLine, type WorkflowsRead, actionsLines, answerWeight,
44
49
  lockedNames, resolvingActions } from './repository-actions.ts'
@@ -98,6 +103,7 @@ export type RepositoryRiskLine =
98
103
  & ({ published: string | null; severity: Severity | null; score: number; findings: { id: string; severity: Severity; takenDown?: true }[] } | RiskFailure))
99
104
  | ({ type: 'advisories'; repo: number; path: string } & ({ advisories: AdvisoryRow[] } | RiskFailure))
100
105
  | ({ type: 'dependabot'; repo: number } & ({ alerts: DependabotAlertRow[] } | RiskFailure))
106
+ | ({ type: 'stasis'; repo: number } & StasisConfigsRead)
101
107
  | WorkflowsLine | WorkflowLine | ActionLine
102
108
  | { type: 'done' }
103
109
  // The scan stopped for its part's time (repositoryRiskLines `partMs`), what
@@ -330,6 +336,7 @@ async function tellRepository(scan: Scan, repo: RepositoryRiskRepo, read: Audite
330
336
  scan.lines.add(line)
331
337
  if ('packages' in line) assessLater(scan, line.packages)
332
338
  }
339
+ if (read.stasis) scan.lines.add({ type: 'stasis', repo: repo.repoId, ...read.stasis })
333
340
  const refs = read.actions ? tellActions(scan, repo, read.actions, lockfiles) : []
334
341
  for (const [at, { line }] of lockfiles.entries()) {
335
342
  if (scan.signal.aborted) return
@@ -1,6 +1,9 @@
1
+ import { entryGlob, hasNodeModulesSegment, isGlobPattern, sortedByPath } from '@exodus/stasis-core/util'
2
+
1
3
  // stasis.config.json's `entries`, as Stasis reads them (src/cmd/bundle-options.js's
2
4
  // readConfigEntries, which is not a public package export): the entries it
3
- // names, each a path relative to the file's directory. Their options are
5
+ // names, each a path relative to the file's directory, or a glob pattern
6
+ // naming the files it matches there in its place. Their options are
4
7
  // Stasis's: buildGitHubBundle builds the entries the stasis.config.json in its
5
8
  // directory names with their options there, and refuses what it can't build.
6
9
  export const STASIS_CONFIG = 'stasis.config.json'
@@ -24,10 +27,29 @@ export function configEntryKey(directory: string, entry: string): string | null
24
27
  return parts.slice(base.length).join('/') || '.'
25
28
  }
26
29
 
30
+ // The entries a stasis.config.json names, in its order, each by the key of
31
+ // `entries` naming it (`entry`), as a path from its directory (`key`): by its
32
+ // path, or as a glob pattern (`pattern`) naming the paths it matches there in
33
+ // its place, none in a node_modules. Of a pattern's syntax, a `*` within a
34
+ // name is told here, and nothing else: one of none but other syntax
35
+ // (`app/[id].ts`) names its path, as Stasis takes one matching nothing; one
36
+ // holding a `**`, or other syntax beside a `*` (`src/*.{js,ts}`), none here.
37
+ export type ConfigEntry = { entry: string; key: string; pattern: boolean }
38
+ export type ConfigEntries = { file: string; entries: ConfigEntry[] }
39
+
40
+ // How a key of `entries` is told here: a glob pattern (stasis-core's
41
+ // isGlobPattern) by its `*`s where it holds no other syntax, none a `**`, and
42
+ // doesn't end in a `/`, which would match directories alone; one of other
43
+ // syntax but no `*` as its path; any other, not at all.
44
+ function patternKind(entry: string): 'path' | 'pattern' | 'none' {
45
+ if (!isGlobPattern(entry) || !entry.includes('*')) return 'path'
46
+ return /\*\*|[?[{]|[!+@*]\(/u.test(entry) || entry.endsWith('/') ? 'none' : 'pattern'
47
+ }
48
+
27
49
  // The entries the stasis.config.json in `directory` whose text is `text`
28
- // names, each as a path from there; null where it has no `entries`. One whose
29
- // entries Stasis can't tell throws.
30
- export function parseStasisConfig(text: string, directory = ''): Set<string> | null {
50
+ // names; null where it has no `entries`. One whose entries Stasis can't tell
51
+ // throws.
52
+ export function parseStasisConfig(text: string, directory = ''): ConfigEntries | null {
31
53
  const file = directory ? `${directory}/${STASIS_CONFIG}` : STASIS_CONFIG
32
54
  let config: unknown
33
55
  try { config = JSON.parse(text) } catch (cause) { throw new Error(`${file} is not valid JSON`, { cause }) }
@@ -35,14 +57,84 @@ export function parseStasisConfig(text: string, directory = ''): Set<string> | n
35
57
  if (entries === undefined) return null
36
58
  if (!plainObject(entries)) throw new Error(`${file}: entries must be an object of each entry's stasis bundle options`)
37
59
  const named = new Map<string, string>()
60
+ const told: ConfigEntry[] = []
38
61
  for (const entry of Object.keys(entries)) {
39
62
  const what = `${file}: entries ${JSON.stringify(entry)}`
40
63
  const key = configEntryKey(directory, entry)
41
64
  if (key === null) throw new Error(`${what}: an entry must be a path relative to the directory of ${STASIS_CONFIG}, within it`)
65
+ // Stasis's refusal of a `.` or `..` in a pattern, as it globs one.
66
+ if (isGlobPattern(entry)) entryGlob(what, entry)
67
+ // Two keys of one path name it twice; two of one pattern match the same
68
+ // paths, or both name the path they are, matching none.
42
69
  if (named.has(key)) throw new Error(`${what} names the same entry as ${JSON.stringify(named.get(key))}`)
43
70
  named.set(key, entry)
71
+ const kind = patternKind(entry)
72
+ if (kind !== 'none') told.push({ entry, key, pattern: kind === 'pattern' })
73
+ }
74
+ return { file, entries: told }
75
+ }
76
+
77
+ // A name as a pattern's part matches it, as Node's glob does: each `*` any
78
+ // run of characters, but a leading one never a leading `.`.
79
+ function partMatcher(part: string): (name: string) => boolean {
80
+ if (!part.includes('*')) return name => name === part
81
+ const text = part.split('*').map(literal => literal.replaceAll(/[$()*+./?[\\\]^{|}]/gu, '\\$&')).join('.*')
82
+ const matcher = new RegExp(`^${part.startsWith('*') ? '(?!\\.)' : ''}${text}$`, 'su')
83
+ return name => matcher.test(name)
84
+ }
85
+
86
+ const matchesPath = (pattern: string, path: string) => {
87
+ const parts = path.split('/'), patternParts = pattern.split('/')
88
+ return !hasNodeModulesSegment(path) && parts.length === patternParts.length && patternParts.every((part, i) => partMatcher(part)(parts[i]!))
89
+ }
90
+
91
+ const twice = (file: string, { entry }: ConfigEntry, { entry: first }: ConfigEntry, path: string) =>
92
+ new Error(`${file}: entries ${JSON.stringify(entry)} names the same entry as ${JSON.stringify(first)}: ${path}`)
93
+
94
+ // Whether `config` names `path`, a path from the file's directory: by its
95
+ // path, or by a pattern matching it. Stasis refuses a config naming an entry
96
+ // twice: where a pattern matches one named by its path, or two match it, it
97
+ // throws.
98
+ export function namesEntry({ file, entries }: ConfigEntries, path: string): boolean {
99
+ const naming = entries.filter(({ key, pattern }) => pattern ? matchesPath(key, path) : key === path)
100
+ if (naming.length > 1) throw twice(file, naming[1]!, naming[0]!, path)
101
+ return naming.length > 0
102
+ }
103
+
104
+ // A directory's listing, as a glob reads it: each of its names, and whether
105
+ // it is a directory's, which it may descend into.
106
+ export type ConfigListing = readonly { name: string; directory: boolean }[]
107
+
108
+ // The paths `pattern` matches, as Stasis sorts them, as a glob over the
109
+ // listings `list` gives finds them: a directory's too at its last part, none
110
+ // in a node_modules.
111
+ async function globbed(pattern: string, list: (directory: string) => Promise<ConfigListing | null>): Promise<string[]> {
112
+ const parts = pattern.split('/')
113
+ let found = ['']
114
+ for (const [i, part] of parts.entries()) {
115
+ const last = i === parts.length - 1, matches = partMatcher(part)
116
+ const listings = await Promise.all(found.map(list))
117
+ found = found.flatMap((directory, j) => (listings[j] ?? []).filter(({ name, directory: isDirectory }) =>
118
+ name !== 'node_modules' && (last || isDirectory) && matches(name)).map(({ name }) => directory ? `${directory}/${name}` : name))
119
+ }
120
+ return sortedByPath(found)
121
+ }
122
+
123
+ // The entries `config` names, each as a path from the file's directory, in
124
+ // its order: a pattern's matches, as `list` lists each directory under it
125
+ // ('' for its own, null for none), in its place. One matching none names its
126
+ // own path, no file's it would match, so none here. One named twice is
127
+ // refused, as Stasis does.
128
+ export async function configEntries({ file, entries }: ConfigEntries, list: (directory: string) => Promise<ConfigListing | null>): Promise<string[]> {
129
+ const named = new Map<string, ConfigEntry>()
130
+ for (const told of entries) {
131
+ for (const path of told.pattern ? await globbed(told.key, list) : [told.key]) {
132
+ const first = named.get(path)
133
+ if (first !== undefined) throw twice(file, told, first, path)
134
+ named.set(path, told)
135
+ }
44
136
  }
45
- return new Set(named.keys())
137
+ return [...named.keys()]
46
138
  }
47
139
 
48
140
  // Whether the stasis.config.json whose text is `text` names the lockfiles Stasis