@preventive/upstream 1.12.0 → 1.13.0

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 (52) hide show
  1. package/advisories.d.ts +125 -89
  2. package/cargo.d.ts +59 -35
  3. package/cocoapods.d.ts +44 -57
  4. package/electron.d.ts +35 -25
  5. package/git.d.ts +25 -16
  6. package/github/write.d.ts +60 -29
  7. package/github.d.ts +207 -193
  8. package/npm.d.ts +150 -87
  9. package/package.d.ts +30 -16
  10. package/package.json +1 -1
  11. package/rubygems.d.ts +22 -9
  12. package/semver.d.ts +40 -19
  13. package/soldeer.d.ts +21 -12
  14. package/src/advisories/actions.js +13 -38
  15. package/src/advisories/common.js +29 -1
  16. package/src/advisories/github.js +5 -19
  17. package/src/advisories/index.js +3 -10
  18. package/src/advisories/npm.js +4 -19
  19. package/src/advisories/osv.js +19 -41
  20. package/src/advisories/packagist.js +1 -4
  21. package/src/advisories/patched.js +6 -18
  22. package/src/advisories/repos.js +8 -13
  23. package/src/advisories/rubysec.js +2 -7
  24. package/src/args.js +5 -10
  25. package/src/attributes.js +3 -4
  26. package/src/cache.js +9 -22
  27. package/src/cargo/crate.js +4 -7
  28. package/src/cargo/repos.js +1 -7
  29. package/src/cocoapods.js +3 -19
  30. package/src/download.js +4 -12
  31. package/src/electron.js +6 -8
  32. package/src/github/commit.js +1 -13
  33. package/src/github/read.js +19 -68
  34. package/src/github/write.js +0 -1
  35. package/src/http.js +2 -7
  36. package/src/lockfiles.js +3 -11
  37. package/src/npm/cacache.js +3 -8
  38. package/src/npm/registry.js +10 -4
  39. package/src/npm/repos.js +3 -15
  40. package/src/npm/tarball.js +5 -20
  41. package/src/npm/versions.js +7 -21
  42. package/src/package.js +1 -7
  43. package/src/pool.js +0 -1
  44. package/src/pypi/version.js +1 -5
  45. package/src/remote.js +4 -6
  46. package/src/rubygems/gem.js +2 -2
  47. package/src/rubygems/version.js +2 -10
  48. package/src/semver.js +3 -9
  49. package/src/soldeer.js +0 -4
  50. package/src/tree.js +14 -44
  51. package/src/weak-edges.js +0 -2
  52. package/weak-edges.d.ts +36 -24
package/src/cache.js CHANGED
@@ -6,7 +6,7 @@ import { dirname, isAbsolute, join, resolve } from 'node:path'
6
6
  import { promisify } from 'node:util'
7
7
  import { gunzip, gzip } from 'node:zlib'
8
8
 
9
- import { assertCacheName, assertDirectoryPath, assertion, isRepo } from './args.js'
9
+ import { assertArgs, assertCacheName, assertDirectoryPath, assertion, isRepo, optional } from './args.js'
10
10
  import { MAX_BYTES, decode } from './http.js'
11
11
  import { pool } from './pool.js'
12
12
 
@@ -59,13 +59,9 @@ export function setCacheDir(dir = defaultCacheDir) {
59
59
  root = resolve(dir)
60
60
  }
61
61
 
62
- // URI-encoded, so a `/` or `..` in a key stays inside one file name, then
63
- // `@` kept and `/` written `+`, as pnpm names its store: `@babel+core@7.29.7`.
64
- // encodeURIComponent writes neither `@` nor `+` bare, so no two keys meet.
65
- // Where case is not told apart (macOS, Windows), JSONStream and jsonstream
66
- // would still meet, so a capital is written `!` and the letter, and a `!`
67
- // as `!!`. A Windows device name (`con.json` is the console) has its first
68
- // letter escaped, which encodeURIComponent never does.
62
+ // URI-encoded, so a key is one file name, then `@` kept and `/` as `+`, as pnpm names its store
63
+ // (`@babel+core@7.29.7`): encodeURIComponent writes neither bare. Where case is not told apart, a capital
64
+ // is `!` and the letter, and `!` is `!!`; a Windows device name (`con.json`) has its first letter escaped.
69
65
  function cachePath(dir, key, base = root) {
70
66
  assert.ok(DIRS.has(dir) && key && typeof key === 'string', `Unexpected cache entry: ${dir}`)
71
67
  const name = encodeURIComponent(key.replace(/[!A-Z]/gu, (char) => `!${char.toLowerCase()}`)).replaceAll('%40', '@').replaceAll('%2F', '+')
@@ -105,8 +101,7 @@ export async function readCache(dir, key) {
105
101
  return path && await readRegularFile(path)
106
102
  }
107
103
 
108
- // With `compressed`, the file is decompressed first, to no more than a file
109
- // read; one that is not gzip, fails its CRC, or runs past that, is a miss.
104
+ // Decompressed to no more than a file read.
110
105
  export async function readCacheJSON(dir, key, { compressed = false } = {}) {
111
106
  const bytes = await readCache(dir, key)
112
107
  try {
@@ -136,13 +131,11 @@ export async function writeCacheJSON(dir, key, value, { compressed = false } = {
136
131
  return await writeCache(dir, key, compressed ? await compress(json) : json)
137
132
  }
138
133
 
139
- // A call's `cache` option: a store of the caller's, with read and write,
140
- // to keep what the call caches in place of the cache set; or false, for
141
- // the cache set to be read and nothing written. `cache` below is that.
134
+ // A call's `cache` option, which `cache` below is: a store of the caller's in place of the cache set, or false,
135
+ // for the cache set to be read and nothing written.
142
136
  export const assertCache = assertion('false, or a store with read and write', (value) => value === false || (typeof value?.read === 'function' && typeof value?.write === 'function'))
137
+ export const assertCacheOptions = (method, options) => assertArgs(method, options, { cache: optional(assertCache) })
143
138
 
144
- // What is kept as `dir` and `name`: in a `cache` store, else in the cache
145
- // set, as `fromDisk` and `toDisk` read and write it.
146
139
  async function read(dir, name, cache, fromDisk) {
147
140
  assert.ok(DIRS.has(dir), `Unexpected cache entry: ${dir}`)
148
141
  return cache ? await cache.read(dir, name) : await fromDisk()
@@ -156,7 +149,6 @@ async function write(dir, name, value, cache, toDisk) {
156
149
  return true
157
150
  }
158
151
 
159
- // JSON, as it is in a store, and in the cache set gzipped where `dir` is.
160
152
  const jsonFile = (dir, name) => (GZIP_DIRS.has(dir) ? { file: `${name}.json.gz`, compressed: true } : { file: `${name}.json` })
161
153
 
162
154
  export function readJSON(dir, name, cache) {
@@ -169,8 +161,7 @@ export function writeJSON(dir, name, value, cache) {
169
161
  return write(dir, name, value, cache, () => writeCacheJSON(dir, file, value, { compressed }))
170
162
  }
171
163
 
172
- // Bytes, in the cache set as `file`. A store may keep what it is given and
173
- // answer what it keeps, so bytes cross it as a copy each way; what it
164
+ // A store may keep what it is given and answer what it keeps, so bytes cross it as a copy each way; what it
174
165
  // answers that is not bytes is none.
175
166
  export async function readBytes(dir, name, file, cache) {
176
167
  const bytes = await read(dir, name, cache, () => readCache(dir, file))
@@ -180,7 +171,6 @@ export async function readBytes(dir, name, file, cache) {
180
171
 
181
172
  export const writeBytes = (dir, name, file, bytes, cache) => write(dir, name, cache ? new Uint8Array(bytes) : bytes, cache, () => writeCache(dir, file, bytes))
182
173
 
183
- // A record, kept as readJSON and writeJSON keep it, for `ttl`.
184
174
  export async function readRecord(dir, name, cache, ttl = RECORD_TTL_MS) {
185
175
  const record = await readJSON(dir, name, cache)
186
176
  const age = typeof record?.at === 'number' ? Date.now() - record.at : Number.NaN
@@ -190,14 +180,11 @@ export async function readRecord(dir, name, cache, ttl = RECORD_TTL_MS) {
190
180
 
191
181
  export const writeRecord = (dir, name, value, cache) => writeJSON(dir, name, { at: Date.now(), name, ...value }, cache)
192
182
 
193
- // Name -> the GitHub repo kept for it (readRecord), for those of `names`
194
- // that have one.
195
183
  export async function readRepos(dir, names, cache) {
196
184
  const entries = await pool(names, RECORDS_AT_ONCE, (name) => readRecord(dir, name, cache))
197
185
  return new Map(names.flatMap((name, i) => (isRepo(entries[i]?.github) ? [[name, entries[i].github]] : [])))
198
186
  }
199
187
 
200
- // An answer into `repos`, and kept (writeRecord) where it found a repo.
201
188
  export async function addRepos(dir, repos, answer, cache) {
202
189
  for (const [name, github] of answer) repos.set(name, github)
203
190
  await pool([...answer].filter(([, github]) => github), RECORDS_AT_ONCE, ([name, github]) => writeRecord(dir, name, { github }, cache))
@@ -3,8 +3,8 @@ import { readdir } from 'node:fs/promises'
3
3
  import { homedir } from 'node:os'
4
4
  import { join, resolve } from 'node:path'
5
5
 
6
- import { assertArgs, assertCrate, assertCrateName, assertCrateVersion, assertSha256, assertion, isIterable, isStrings, optional, printable, show } from '../args.js'
7
- import { assertCache, readRecord, writeRecord } from '../cache.js'
6
+ import { assertArgs, assertCrate, assertCrateName, assertCrateVersion, assertSha256, assertVersions, isIterable, isStrings, optional, printable, show } from '../args.js'
7
+ import { assertCacheOptions, readRecord, writeRecord } from '../cache.js'
8
8
  import { verifiedDownload } from '../download.js'
9
9
  import { CRATES_INDEX, CRATES_STATIC, buildUrl, encodeSegment, isNotFound, recover, request } from '../http.js'
10
10
  import { pool } from '../pool.js'
@@ -56,13 +56,12 @@ export async function verifyChecksum(name, version, checksum) {
56
56
 
57
57
  export async function getCrate(name, version, checksum) {
58
58
  assertCrate('getCrate', name, version)
59
- if (checksum !== undefined) assertSha256('getCrate', 'checksum', checksum)
59
+ optional(assertSha256)('getCrate', 'checksum', checksum)
60
60
  const expected = checksum ?? await getChecksum('getCrate', name, version)
61
61
  const locate = () => buildUrl(CRATES_STATIC, ['crates', name, `${name}-${encodeSegment(version)}.crate`])
62
62
  return await verifiedDownload({ method: 'getCrate', dir: DIR, what: `${name}@${version}`, ext: 'crate', algorithm: 'sha256', expected, local: await localPaths(name, version), locate })
63
63
  }
64
64
 
65
- // A crate's versions on crates.io, yanked or not; null where it has none.
66
65
  async function indexVersions(name, cache) {
67
66
  const kept = await readRecord(INDEX_DIR, name, cache, INDEX_TTL_MS)
68
67
  if (isStrings(kept?.published) && isStrings(kept.yanked)) return kept
@@ -77,10 +76,8 @@ async function indexVersions(name, cache) {
77
76
  return versions
78
77
  }
79
78
 
80
- const assertVersions = assertion('a non-empty array', (value) => Array.isArray(value) && value.length > 0)
81
-
82
79
  export async function yankedVersions(crates, options = {}) {
83
- assertArgs('yankedVersions', options, { cache: optional(assertCache) })
80
+ assertCacheOptions('yankedVersions', options)
84
81
  assert.ok(isIterable(crates), 'yankedVersions: crates must be an iterable of { name, versions }')
85
82
  const asked = new Map()
86
83
  for (const crate of crates) {
@@ -12,9 +12,7 @@ const PER_REQUEST = 100
12
12
  const PACE_MS = 1000 // crates.io asks for a request a second at most, and a user agent.
13
13
  const USER_AGENT = '@preventive/upstream (https://github.com/PreventiveMeasures/libraries)'
14
14
 
15
- // One request for up to a hundred crates: each name -> the GitHub repo its
16
- // `repository` names, or null where it names none. A crate crates.io
17
- // leaves out of its answer is one it does not have, null too.
15
+ // A crate crates.io leaves out of its answer is one it does not have.
18
16
  async function askCrates(method, names) {
19
17
  const url = buildUrl(CRATES_API, ['api', 'v1', 'crates'], { 'ids[]': names, per_page: PER_REQUEST })
20
18
  const answer = await request(url, { as: 'json', headers: { 'User-Agent': USER_AGENT } })
@@ -27,10 +25,6 @@ async function askCrates(method, names) {
27
25
  return found
28
26
  }
29
27
 
30
- // Name -> its GitHub repo, or null where crates.io has no such crate or it
31
- // names no GitHub repo, through the cache, or a `cache` store (readRecord):
32
- // only a repo found is kept, for a month. A failed request throws, or with
33
- // `soft` leaves its names out; `cachedOnly` asks nothing.
34
28
  export async function lookUpCrateRepos(method, names, { soft = false, cachedOnly = false, cache } = {}) {
35
29
  const repos = await readRepos(DIR, names, cache)
36
30
  if (cachedOnly) return repos
package/src/cocoapods.js CHANGED
@@ -20,11 +20,9 @@ export function specPath(name, version) {
20
20
  return ['Specs', ...shard, name, version, `${name}.podspec.json`]
21
21
  }
22
22
 
23
- // CocoaPods' spec repos, a directory each under $CP_REPOS_DIR, else
24
- // $CP_HOME_DIR/repos, else ~/.cocoapods/repos: `trunk` with the podspecs
25
- // it read off the CDN as they were served, `master` a clone of
26
- // CocoaPods/Specs, others a team's own. os.homedir() throws where there is
27
- // no home directory to be found.
23
+ // CocoaPods' spec repos, a directory each under $CP_REPOS_DIR, else $CP_HOME_DIR/repos, else ~/.cocoapods/repos:
24
+ // `trunk` with podspecs as the CDN served them, `master` a clone of CocoaPods/Specs, others a team's own.
25
+ // os.homedir() throws where there is no home directory to be found.
28
26
  async function localPaths(name, version) {
29
27
  const { CP_REPOS_DIR, CP_HOME_DIR } = process.env
30
28
  let root
@@ -44,10 +42,6 @@ const ARCHIVES = 'cocoapods/archives'
44
42
  const MAVEN_FACEBOOK = `${MAVEN_CENTRAL}/maven2/com/facebook/`
45
43
  const MAVEN_ARCHIVE = /\.(?:tar\.gz|zip)$/u
46
44
 
47
- // As the URL parser writes it back out, so that what its text is checked
48
- // for, a prefix above all, holds of what is fetched; and as buildUrl writes
49
- // it, with no query, fragment, credentials or port, and nothing in a
50
- // segment but what it lets through.
51
45
  export function isPodArchiveUrl(value) {
52
46
  const parsed = typeof value === 'string' ? URL.parse(value) : null
53
47
  if (parsed === null || parsed.toString() !== value) return false
@@ -63,13 +57,6 @@ export function isPodArchiveUrl(value) {
63
57
  }
64
58
  const assertPodArchiveUrl = assertion('an https URL of a GitHub repository\'s, with a path under it, or of a .tar.gz or a .zip under Maven Central\'s com/facebook/', isPodArchiveUrl)
65
59
 
66
- // An archive a podspec's source names by :http, held to the sha256 the
67
- // podspec gives of it: a sha1 alone, which two archives made to collide
68
- // share, is not taken. GitHub's answer for a tag's archive or a release's
69
- // asset is a redirect, to codeload.github.com or to where it keeps the
70
- // files, and Maven Central's for React Native's is one to
71
- // repo.reactnative.dev, which is followed: the bytes are held to the hash
72
- // whoever answers.
73
60
  export async function getPodArchive(url, sha256) {
74
61
  assertPodArchiveUrl('getPodArchive', 'url', url)
75
62
  assertSha256('getPodArchive', 'sha256', sha256)
@@ -79,9 +66,6 @@ export async function getPodArchive(url, sha256) {
79
66
  })
80
67
  }
81
68
 
82
- // Trunk has no hash to check a podspec against, so the caller brings one,
83
- // as Podfile.lock records it. The CDN redirects to jsDelivr, which is
84
- // followed: whoever answers, the bytes are held to the checksum.
85
69
  export async function getPodspec(name, version, checksum) {
86
70
  assertPod('getPodspec', name, version)
87
71
  assertSha1('getPodspec', 'checksum', checksum)
package/src/download.js CHANGED
@@ -5,10 +5,8 @@ import { ourCachePaths, readBytes, readRegularFile, writeBytes } from './cache.j
5
5
  import { request } from './http.js'
6
6
  import { gitTreeOfTarball } from './tree.js'
7
7
 
8
- // A hash as each registry writes it: npm's integrity, one sha512 in base64
9
- // after `sha512-`; crates.io's and Soldeer's checksum, a sha256 in hex;
10
- // Podfile.lock's checksum of a podspec, a sha1 in hex; a git tree id for a
11
- // tarball of that tree.
8
+ // A hash as each registry writes it: npm's integrity, `sha512-` and base64; crates.io's and Soldeer's checksum,
9
+ // a sha256 in hex; Podfile.lock's of a podspec, a sha1 in hex; a git tree id for a tarball of that tree.
12
10
  const DIGESTS = {
13
11
  sha512: (bytes) => `sha512-${createHash('sha512').update(bytes).digest('base64')}`,
14
12
  sha256: (bytes) => createHash('sha256').update(bytes).digest('hex'),
@@ -16,14 +14,8 @@ const DIGESTS = {
16
14
  tree: gitTreeOfTarball,
17
15
  }
18
16
 
19
- // Bytes whose `algorithm` hash is `expected`, which the registry or the
20
- // caller gives, never a disk; without it nothing is read. From `local`,
21
- // other tools' caches, and with `ours` our default cache and stasis's,
22
- // whether set or not (read, never written; a mismatch is passed over),
23
- // else the cache set, or a `cache` store in its place (readBytes; a
24
- // mismatch throws), else what `locate` answers, checked and then kept as
25
- // writeBytes keeps it, as `entry`, `what` unless given. A tree's `list`
26
- // and `symlinksAbove` are gitTreeOfTarball's.
17
+ // `expected` comes from the registry or the caller, never a disk; `local` is other tools' caches. A tree's options
18
+ // are gitTreeOfTarball's.
27
19
  export async function verifiedDownload({ method, dir, what, entry = what, ext, algorithm, expected, local = [], ours = false, cache, locate, options = {}, list, symlinksAbove }) {
28
20
  assert.ok(Object.hasOwn(DIGESTS, algorithm) && typeof expected === 'string' && expected !== '', `${method}: nothing to check ${what} against`)
29
21
  const digest = (bytes) => DIGESTS[algorithm](bytes, { expected, list, symlinksAbove })
package/src/electron.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { join, posix } from 'node:path'
3
3
 
4
- import { assertArgs, assertSha256, assertion, matches, optional } from './args.js'
5
- import { absolute, assertCache, cacheDirFor } from './cache.js'
4
+ import { assertOneOf, assertSha256, assertion, matches } from './args.js'
5
+ import { absolute, assertCacheOptions, cacheDirFor } from './cache.js'
6
6
  import { verifiedDownload } from './download.js'
7
7
  import { GITHUB_WEB, buildUrl } from './http.js'
8
8
 
@@ -13,9 +13,8 @@ const PLATFORMS = new Set(['darwin', 'linux', 'mas', 'win32'])
13
13
  const ARCHES = new Set(['arm64', 'armv7l', 'ia32', 'x64'])
14
14
  // No build metadata: the version is a URL segment and a file name.
15
15
  const assertElectronVersion = assertion('an Electron version', matches(/^(?=.{1,128}$)\d+\.\d+\.\d+(?:-[\dA-Za-z][\dA-Za-z.-]*)?$/u))
16
- const assertOneOf = (set, must) => assertion(must, (value) => set.has(value))
17
- const assertPlatform = assertOneOf(PLATFORMS, `one of ${[...PLATFORMS].join(', ')}`)
18
- const assertArch = assertOneOf(ARCHES, `one of ${[...ARCHES].join(', ')}`)
16
+ const assertPlatform = assertOneOf(PLATFORMS)
17
+ const assertArch = assertOneOf(ARCHES)
19
18
 
20
19
  // Where @electron/get keeps `url`: <root>/<sha256 of its directory's URL>/<file>,
21
20
  // the root install.js's electron_config_cache, else the platform's cache for electron.
@@ -26,15 +25,14 @@ function electronGetPaths(url) {
26
25
  return [absolute(process.env.electron_config_cache), cacheDirFor('electron')].filter(Boolean).map((root) => join(root, dir, posix.basename(url)))
27
26
  }
28
27
 
29
- // As @electron/get downloads it for install.js. The redirect to GitHub's asset
30
- // host is followed: the bytes are held to `checksum` wherever they come from.
28
+ // As @electron/get downloads it for install.js.
31
29
  export async function getElectronZip(version, platform, arch, checksum, options = {}) {
32
30
  const method = 'getElectronZip'
33
31
  assertElectronVersion(method, 'version', version)
34
32
  assertPlatform(method, 'platform', platform)
35
33
  assertArch(method, 'arch', arch)
36
34
  assertSha256(method, 'checksum', checksum)
37
- assertArgs(method, options, { cache: optional(assertCache) })
35
+ assertCacheOptions(method, options)
38
36
  const name = `electron-v${version}-${platform}-${arch}`
39
37
  const repo = version.includes('nightly') ? 'nightlies' : 'electron'
40
38
  const url = buildUrl(GITHUB_WEB, ['electron', repo, 'releases', 'download', `v${version}`, `${name}.zip`])
@@ -1,7 +1,3 @@
1
- // A commit's tree, held to the commit's id: the commit object itself, as
2
- // git fetches it from github.com over its protocol v2, and hashed, where
3
- // the API's answer for a commit is GitHub's word for what is in it.
4
-
5
1
  import assert from 'node:assert/strict'
6
2
  import { Buffer } from 'node:buffer'
7
3
  import { createHash } from 'node:crypto'
@@ -67,9 +63,7 @@ function packOf(bytes, method) {
67
63
  assert.fail(`${method}: GitHub answered with no packfile`)
68
64
  }
69
65
 
70
- // The bytes of the commit `sha` in the pack, an object of the commit type
71
- // whose `commit <size>\0` and bytes hash to it. The pack is held to its
72
- // trailer, the sha1 of the rest; an object is read a zlib stream at a time.
66
+ // The pack is held to its trailer, the sha1 of the rest; an object is read a zlib stream at a time.
73
67
  function commitIn(pack, sha, method) {
74
68
  assert.ok(pack.length >= 32 && pack.toString('latin1', 0, 4) === 'PACK' && [2, 3].includes(pack.readUInt32BE(4)), `${method}: GitHub's packfile is no packfile`)
75
69
  const end = pack.length - 20
@@ -107,12 +101,6 @@ function commitIn(pack, sha, method) {
107
101
  // A sha1 alone: GitHub keeps no repository in sha256.
108
102
  const assertCommit = assertion('a full commit sha1', isSha1)
109
103
 
110
- // The id of the tree of the full commit `sha`, from the commit's own
111
- // object: fetched from github.com's git-upload-pack, as git fetches it, and
112
- // held to `sha`, so the tree is the commit's whatever GitHub's API says.
113
- // The API's token, where the client has one, is sent as git sends one, by
114
- // Basic. A redirect is not followed: one for a repository renamed or
115
- // transferred throws, as getRepo is the call that follows it.
116
104
  export async function getCommitTree(headers, options) {
117
105
  assertArgs('getCommitTree', options, { repo: assertRepo, sha: assertCommit })
118
106
  const { repo, sha } = options
@@ -26,10 +26,8 @@ async function* pages(method, headers, pageUrl, maxPages = MAX_PAGES) {
26
26
  }
27
27
  }
28
28
 
29
- // A list GitHub pages by a cursor instead: the `after` of each page's
30
- // Link header `next` link, the one thing read off the link, so the next
31
- // page is asked of the list `pageUrl` names, wherever the link points. A
32
- // next link proves a page more.
29
+ // A list GitHub pages by a cursor instead: only the `after` of each page's Link `next` is read, so the next page
30
+ // is asked of the list `pageUrl` names, wherever the link points. A next link proves a page more.
33
31
  async function* cursorPages(method, headers, pageUrl, maxPages = MAX_PAGES) {
34
32
  const paging = { per_page: PER_PAGE }
35
33
  for (let page = 1; ; page++) {
@@ -58,10 +56,6 @@ async function listUserRepos(headers, options) {
58
56
  const REPO_BY_ID = /^https:\/\/api\.github\.com\/repositories\/([1-9]\d{0,14})$/u
59
57
  const REDIRECTS = new Set([301, 302, 307, 308])
60
58
 
61
- // With `followRedirect`, GitHub's redirect for a repository renamed or
62
- // transferred is followed, once, on its API alone, and the answer held to
63
- // the id it names rather than to the name asked; any other redirect, or a
64
- // second, is refused as without it.
65
59
  async function getRepo(headers, options) {
66
60
  assertArgs('getRepo', options, { repo: assertRepo, followRedirect: optional(assertBoolean) })
67
61
  const { repo, followRedirect } = options
@@ -104,27 +98,19 @@ async function getRepoTag(headers, options) {
104
98
  return { tag, oid: object.sha }
105
99
  }
106
100
 
107
- // GitHub lists each tag with the commit it names, an annotated one's too.
108
- async function listRepoTags(headers, options) {
109
- assertArgs('listRepoTags', options, { repo: assertRepo, maxPages: optional(assertNumber) })
101
+ // GitHub lists each tag with the commit it names, an annotated one's too,
102
+ // and each branch with the commit at its head.
103
+ const listRefs = (method, kind, list, isName) => async (headers, options) => {
104
+ assertArgs(method, options, { repo: assertRepo, maxPages: optional(assertNumber) })
110
105
  const { repo, maxPages } = options
111
- const tags = await paginate('listRepoTags', headers, (paging) => repoApi(repo, ['tags'], paging), maxPages)
112
- return tags.map((entry) => {
113
- assert.ok(isTagName(entry?.name) && isSha(entry.commit?.sha), `listRepoTags: GitHub listed ${show(entry?.name)} in ${repo}, which is no tag name with a commit`)
114
- return { tag: entry.name, oid: entry.commit.sha }
115
- })
116
- }
117
-
118
- // GitHub lists each branch with the commit at its head.
119
- async function listRepoBranches(headers, options) {
120
- assertArgs('listRepoBranches', options, { repo: assertRepo, maxPages: optional(assertNumber) })
121
- const { repo, maxPages } = options
122
- const branches = await paginate('listRepoBranches', headers, (paging) => repoApi(repo, ['branches'], paging), maxPages)
123
- return branches.map((entry) => {
124
- assert.ok(isRefName(entry?.name) && isSha(entry.commit?.sha), `listRepoBranches: GitHub listed ${show(entry?.name)} in ${repo}, which is no branch name with a commit`)
125
- return { branch: entry.name, oid: entry.commit.sha }
106
+ const refs = await paginate(method, headers, (paging) => repoApi(repo, [list], paging), maxPages)
107
+ return refs.map((entry) => {
108
+ assert.ok(isName(entry?.name) && isSha(entry.commit?.sha), `${method}: GitHub listed ${show(entry?.name)} in ${repo}, which is no ${kind} name with a commit`)
109
+ return { [kind]: entry.name, oid: entry.commit.sha }
126
110
  })
127
111
  }
112
+ const listRepoTags = listRefs('listRepoTags', 'tag', 'tags', isTagName)
113
+ const listRepoBranches = listRefs('listRepoBranches', 'branch', 'branches', isRefName)
128
114
 
129
115
  const assertRevision = assertion('a full commit sha, or a branch or tag name', (value) => isSha(value) || isRefName(value))
130
116
  // What GitHub's compare says of the counts it gives with it.
@@ -136,14 +122,6 @@ const COMPARED = {
136
122
  }
137
123
  const isCount = (value) => Number.isSafeInteger(value) && value >= 0
138
124
 
139
- // How `head` stands to `base` in the repo, as GitHub's compare tells it:
140
- // `ahead` where `base` is in `head`'s history, `behind` the other way round,
141
- // `identical`, or `diverged`; with the commits each has that the other
142
- // hasn't, and their merge base. Refused unless the status agrees with those
143
- // counts, the merge base is `base` where `head` is ahead of it or the same,
144
- // and the base GitHub compared is `base` where that is a commit. GitHub
145
- // answers for a commit of any fork of the repo too: whether one is the
146
- // repo's own is whether a ref of the repo has it in its history.
147
125
  async function compareCommits(headers, options) {
148
126
  assertArgs('compareCommits', options, { repo: assertRepo, base: assertRevision, head: assertRevision })
149
127
  const { repo, base, head } = options
@@ -158,11 +136,8 @@ async function compareCommits(headers, options) {
158
136
  return { status, aheadBy, behindBy, mergeBase }
159
137
  }
160
138
 
161
- // GitHub's object for the path first: a directory, symlink or submodule is
162
- // refused rather than read as a file's text. Up to 1 MB the object holds
163
- // the content; past it, `encoding: none`, and the blob it names is read,
164
- // which a push to the ref since cannot change. Either way the bytes must
165
- // hash to that blob.
139
+ // Past 1 MB GitHub's object holds no content (`encoding: none`) and the blob it names is read, which a push to
140
+ // the ref since cannot change.
166
141
  async function getRepoFile(headers, options) {
167
142
  assertArgs('getRepoFile', options, { repo: assertRepo, path: assertPath, ref: optional(assertRef) })
168
143
  const { repo, path, ref } = options
@@ -178,13 +153,8 @@ async function getRepoFile(headers, options) {
178
153
  return decode(bytes, url)
179
154
  }
180
155
 
181
- // Follows the redirect to codeload.github.com. A tree id names its content,
182
- // so the bytes are held to it, downloaded or cached, and cached by it alone,
183
- // for good. What a tarball cannot show, a submodule's commit, a subtree
184
- // with nothing in it or the LF blob of a file marked `eol=crlf`, comes
185
- // from GitHub's listings of the trees, which the id checks as well: a
186
- // directory at a time, as a recursive listing of a large tree is cut short.
187
- // Its symlinks climb no more than `symlinksAbove` levels above its root.
156
+ // Follows the redirect to codeload.github.com. Trees are listed a directory at a time, as a recursive listing of
157
+ // a large tree is cut short.
188
158
  async function treeTarball(method, headers, repo, tree, symlinksAbove) {
189
159
  const listings = new Map()
190
160
  const list = (sha) => {
@@ -201,9 +171,7 @@ async function commitTree(method, headers, repo, sha) {
201
171
  return commit.tree.sha
202
172
  }
203
173
 
204
- // A full sha only, so the bytes are that commit's, not wherever a ref points
205
- // now. Its tree's tarball, not its own, in which `git archive` rewrites the
206
- // files marked `export-subst`.
174
+ // A full sha only, so the bytes are that commit's, not wherever a ref points now.
207
175
  async function getRepoTarball(headers, options) {
208
176
  assertArgs('getRepoTarball', options, { repo: assertRepo, sha: assertSha, symlinksAbove: optional(assertLevels) })
209
177
  const { repo, sha, symlinksAbove } = options
@@ -243,12 +211,8 @@ async function listRepoDir(headers, options) {
243
211
  return await listTree('listRepoDir', headers, options.repo, tree)
244
212
  }
245
213
 
246
- // A tree and every tree under it in one listing, their entries by paths
247
- // from it, or null where GitHub cut it short, as it does past 100,000
248
- // entries or 7 MB. Each tree in it, the top one too, has to hash from the
249
- // entries listed in it, so none is left out, changed or added: an entry is
250
- // filed under the path before its last `/`, a tree's own with a `/` after
251
- // it, so `/x` or `a//x` is in no tree.
214
+ // An entry is filed under the path before its last `/`, a tree's own with a `/` after it, so `/x` or `a//x` is in
215
+ // no tree.
252
216
  async function listTreeDeep(method, headers, repo, tree) {
253
217
  const listing = await call(headers, repoApi(repo, ['git', 'trees', tree], { recursive: 1 }))
254
218
  if (listing?.truncated === true) return null
@@ -264,11 +228,6 @@ async function listTreeDeep(method, headers, repo, tree) {
264
228
  return entries
265
229
  }
266
230
 
267
- // Each file in `tree`, which is at `base` in the repo, by its path, its
268
- // name and its blob's id: from the tree's listing with every tree under
269
- // it, or, where GitHub cuts that short, from its own and then each
270
- // subtree's in turn, as GitHub advises for a large tree. A node_modules,
271
- // of packages installed, is not the repo's own.
272
231
  async function* filesIn(method, headers, repo, tree, base) {
273
232
  const deep = await listTreeDeep(method, headers, repo, tree)
274
233
  for (const { path, mode, type, sha } of deep ?? await listTree(method, headers, repo, tree)) {
@@ -281,11 +240,6 @@ async function* filesIn(method, headers, repo, tree, base) {
281
240
 
282
241
  const assertPaths = assertion('an array of paths inside a repository', (value) => Array.isArray(value) && value.every(isRepoPath))
283
242
 
284
- // Every entry of a commit's tree, by its path from the root, as
285
- // listTreeDeep lists it; where GitHub cuts that short, the tree's own
286
- // listing, then each tree in it the same way, only those `paths` are in
287
- // if given, `maxTrees` trees listed at most. Whether some were left
288
- // unlisted is `cut`.
289
243
  async function listRepoTree(headers, options) {
290
244
  assertArgs('listRepoTree', options, { repo: assertRepo, sha: assertSha, paths: optional(assertPaths), maxTrees: optional(assertNumber) })
291
245
  const { repo, sha, paths, maxTrees = MAX_TREES } = options
@@ -363,9 +317,6 @@ async function getCollaboratorPermission(headers, options) {
363
317
  return body
364
318
  }
365
319
 
366
- // The repository's copy is the maintainer's latest text, there from the
367
- // start; the global database has it only once GitHub has reviewed it, and
368
- // is the fallback for a repository that is gone, not for one that failed.
369
320
  async function getAdvisory(headers, options) {
370
321
  assertArgs('getAdvisory', options, { ghsa: assertGhsa, repo: optional(assertRepo) })
371
322
  const { ghsa, repo } = options
@@ -87,7 +87,6 @@ async function createBranch(headers, options) {
87
87
  return await call(headers, repoApi(repo, ['git', 'refs']), { method: 'POST', body: { ref: `refs/heads/${branch}`, sha } })
88
88
  }
89
89
 
90
- // A signed commit; the branch must already exist.
91
90
  async function createCommit(headers, options) {
92
91
  assertArgs('createCommit', options, { repo: assertRepo, branch: assertRef, message: null, additions: null, deletions: null, expectedHeadOid: optional(assertSha) })
93
92
  const { repo, branch } = options
package/src/http.js CHANGED
@@ -31,7 +31,6 @@ const ORIGINS = new Set([NPM_REGISTRY, GITHUB_API, OSV_API, OSV_EXPORTS, CRATES_
31
31
  const isSegment = matches(/^(?!\.\.?$)(?:[\w.~@-]|%[\dA-F]{2})+$/u)
32
32
  const isQueryKey = matches(/^[a-z_]+(?:\[\])?$/u)
33
33
  const isQueryValue = (value) => (typeof value === 'string' && value !== '') || (Number.isSafeInteger(value) && value >= 0)
34
- // Only a `key[]` repeats, and it always does.
35
34
  const isQuery = ([key, value]) => isQueryKey(key) && (key.endsWith('[]') ? Array.isArray(value) && value.length > 0 && value.every(isQueryValue) : isQueryValue(value))
36
35
  // A line break in a value would start a header of its own.
37
36
  const isHeader = ([name, value]) => /^[A-Za-z][\w-]*$/u.test(name) && matches(/^[ -~]*$/u)(value)
@@ -42,7 +41,6 @@ const LIMITS = {
42
41
  }
43
42
  const decoder = new TextDecoder('utf-8', { fatal: true })
44
43
 
45
- // `headers` are the response's, where there was one to read them from.
46
44
  export class HttpError extends Error {
47
45
  constructor(status, message, headers) {
48
46
  super(message)
@@ -92,7 +90,6 @@ export async function send(url, { method = 'GET', headers = {}, body, redirect =
92
90
  assert.ok(['manual', 'follow'].includes(redirect), `Unexpected redirect mode: ${redirect}`)
93
91
  assert.ok(Object.hasOwn(LIMITS, as), `Unexpected response type: ${as}`)
94
92
  assert.ok(Object.entries(headers).every(isHeader), 'Unexpected header')
95
- // Bytes as they are, under the type `headers` give; anything else as JSON.
96
93
  const json = body === undefined ? {} : body instanceof Uint8Array ? { body } : { headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body) }
97
94
  return await fetch(url, { method, headers, redirect, signal: AbortSignal.timeout(LIMITS[as].ms), ...json })
98
95
  }
@@ -126,8 +123,7 @@ function parse(bytes, url, as) {
126
123
  }
127
124
  }
128
125
 
129
- // Read as the caller says, not by content type, which proxies drop or
130
- // rewrite; answered with the response's headers.
126
+ // Read as the caller says, not by content type, which proxies drop or rewrite.
131
127
  export async function requestWithHeaders(url, options) {
132
128
  const res = await send(url, options)
133
129
  if (!res.ok) {
@@ -140,8 +136,7 @@ export async function requestWithHeaders(url, options) {
140
136
 
141
137
  export const request = async (url, options) => (await requestWithHeaders(url, options)).body
142
138
 
143
- // Whether `url` answers a HEAD with a 2xx. No body is read; a redirect is
144
- // not followed, and counts as no.
139
+ // A redirect is not followed, and counts as no.
145
140
  export async function answersHead(url) {
146
141
  const res = await send(url, { method: 'HEAD', as: 'json' })
147
142
  await res.body?.cancel()
package/src/lockfiles.js CHANGED
@@ -1,8 +1,6 @@
1
- // Each tool that writes a lockfile, by the format of it: the names it
2
- // writes one under, and those of the project files it locks, each a name
3
- // as git has it, `cargo.lock` not Cargo's, or a pattern. A lockfile's
4
- // pattern names in a `locks` group the file beside it that it locks, where
5
- // no name of that file's own tells it is one.
1
+ // Each tool that writes a lockfile, by its format: the names it writes one under and those of the project files
2
+ // it locks, each a pattern or a name as git has it (`cargo.lock` is not Cargo's). A lockfile's pattern names in a
3
+ // `locks` group the file beside it that it locks, where no name of that file's own tells it is one.
6
4
  export const FORMATS = {
7
5
  // pnpm-lock.<branch>.yaml with git-branch-lockfile; shrinkwrap.yaml before
8
6
  // pnpm 3. package.yaml and package.json5 in place of package.json, and
@@ -93,12 +91,8 @@ const NAMES = new Set(KNOWN.filter((known) => typeof known === 'string'))
93
91
  const PATTERN = new RegExp(KNOWN.filter((known) => typeof known !== 'string').map(({ source }) => `(?:${source})`).join('|'), 'u')
94
92
  const isKnown = (name) => NAMES.has(name) || PATTERN.test(name)
95
93
 
96
- // Whether `name` is one of `names`, each a name or a pattern.
97
94
  const isOf = (names, name) => names.some((known) => (typeof known === 'string' ? known === name : known.test(name)))
98
95
 
99
- // The lockfile a file of this name is, `{ format, locks }`, `locks` the name
100
- // of the file beside it that it locks where its pattern names one; or
101
- // undefined.
102
96
  export function lockfileOf(name) {
103
97
  for (const [format, { lockfiles }] of isKnown(name) ? TOOLS : []) {
104
98
  for (const known of lockfiles) {
@@ -108,6 +102,4 @@ export function lockfileOf(name) {
108
102
  }
109
103
  }
110
104
 
111
- // The formats of the lockfiles that lock a project of a file of this name,
112
- // in FORMATS' order, none where it is no project file.
113
105
  export const projectFormats = (name) => (isKnown(name) ? TOOLS.filter(([, { projects }]) => isOf(projects, name)).map(([format]) => format) : [])
@@ -4,12 +4,9 @@ import { join } from 'node:path'
4
4
 
5
5
  import { readRegularFile } from '../cache.js'
6
6
 
7
- // npm's cache, cacache as npm 5 and later keep it: a response by the URL
8
- // it answered, under the key `make-fetch-happen:request-cache:<url>`. The
9
- // index has a file for each key's sha256, of lines `<sha1>\t<entry>`, each
10
- // entry's sha1 of its own JSON: the last whole one for the key counts, and
11
- // one with no integrity is one deleted. The content is filed by its
12
- // sha512, and checked against it.
7
+ // npm's cache, cacache as npm 5 and later keep it: a response under `make-fetch-happen:request-cache:<url>`, in an
8
+ // index file by the key's sha256 of `<sha1 of entry>\t<entry>` lines, the last whole one counting and one with no
9
+ // integrity a deletion; the content filed by its sha512, and checked against it.
13
10
  const KEY = 'make-fetch-happen:request-cache:'
14
11
  const digest = (algorithm, data, encoding) => createHash(algorithm).update(data).digest(encoding)
15
12
  const shard = (hex) => [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4)]
@@ -33,8 +30,6 @@ async function lastEntry(root, key) {
33
30
  return entry
34
31
  }
35
32
 
36
- // The body npm keeps for `url`, beside what it kept of the response, or
37
- // null: none kept, one deleted, or content gone or not its sha512.
38
33
  export async function readNpmCached(root, url) {
39
34
  const entry = await lastEntry(root, `${KEY}${url}`)
40
35
  const integrity = typeof entry?.integrity === 'string' ? entry.integrity : ''
@@ -3,16 +3,22 @@ import assert from 'node:assert/strict'
3
3
  import { show } from '../args.js'
4
4
  import { NPM_REGISTRY, buildUrl, request } from '../http.js'
5
5
 
6
- // The first of these that is set and not empty.
7
- const npmToken = () => process.env.PREVENTIVE_MEASURES_NPM_TOKEN || process.env.STASIS_NPM_TOKEN || process.env.NPM_TOKEN
6
+ // @acme-corp/x is read with ACME_CORP_NPM_TOKEN where it is set. STASIS_NPM_TOKEN
7
+ // is stasis's token for every scope, never @stasis's own.
8
+ function scopeToken(name) {
9
+ const key = `${name.slice(1, name.indexOf('/')).toUpperCase().replaceAll(/[.-]/gu, '_')}_NPM_TOKEN`
10
+ return key === 'STASIS_NPM_TOKEN' ? undefined : process.env[key]
11
+ }
12
+
13
+ const npmToken = (name) => scopeToken(name) || process.env.PREVENTIVE_MEASURES_NPM_TOKEN || process.env.STASIS_NPM_TOKEN || process.env.NPM_TOKEN
8
14
 
9
15
  // Private packages are always scoped.
10
16
  export function withNpmToken(name, url, options = {}) {
11
17
  const method = options.method ?? 'GET'
12
18
  const own = url === `${NPM_REGISTRY}/${name}` || url.startsWith(`${NPM_REGISTRY}/${name}/`)
13
19
  assert.ok(method === 'GET' && `${new URL(url)}` === url && own, `Unexpected request for ${name}: ${method} ${url}`)
14
- const token = npmToken()
15
- return token && name.startsWith('@') ? { ...options, method, headers: { ...options.headers, Authorization: `Bearer ${token}` } } : options
20
+ const token = name.startsWith('@') && npmToken(name)
21
+ return token ? { ...options, method, headers: { ...options.headers, Authorization: `Bearer ${token}` } } : options
16
22
  }
17
23
 
18
24
  // A version's document, or with no `spec` the whole package's, every