@exodus/stasis 1.0.0-beta.15 → 1.0.0-beta.17

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 (67) hide show
  1. package/README.md +1 -1
  2. package/bin/stasis.js +26 -11
  3. package/package.json +10 -9
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +113 -233
  6. package/src/babel.js +39 -122
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +5 -9
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +50 -166
  11. package/src/cmd/bundle-options.js +110 -167
  12. package/src/cmd/bundle.js +861 -1344
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +46 -27
  15. package/src/cmd/output.js +17 -12
  16. package/src/cmd/sbom.js +3 -8
  17. package/src/cmd/tokens.js +10 -23
  18. package/src/define.js +34 -97
  19. package/src/diff.js +72 -128
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +10 -25
  22. package/src/installed.js +265 -0
  23. package/src/json-stream.js +4 -9
  24. package/src/loader-mock.js +3 -8
  25. package/src/loader.js +1 -5
  26. package/src/loaders/bash.js +41 -93
  27. package/src/loaders/cargo.js +298 -805
  28. package/src/loaders/foundry.js +109 -285
  29. package/src/loaders/paths.js +13 -13
  30. package/src/loaders/php.js +210 -489
  31. package/src/loaders/rust.js +507 -1430
  32. package/src/loaders/solidity-ownership.js +48 -128
  33. package/src/loaders/solidity.js +39 -122
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +9 -33
  37. package/src/metro-resolver.js +20 -47
  38. package/src/metro-transformer.js +0 -5
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +2 -5
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +90 -220
  44. package/src/resolve-node.js +27 -45
  45. package/src/resolve-typescript.js +109 -313
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +52 -128
  49. package/src/scan.js +136 -283
  50. package/src/sixel.js +18 -41
  51. package/src/table.js +14 -35
  52. package/src/validate-notes.d.ts +3 -2
  53. package/src/validate-notes.js +25 -19
  54. package/src/validate.d.ts +38 -11
  55. package/src/validate.js +478 -512
  56. package/src/vfs-bundle/entries.js +40 -57
  57. package/src/vfs-bundle/github.js +88 -121
  58. package/src/vfs-bundle/glob.js +4 -45
  59. package/src/vfs-bundle/lazy.js +27 -56
  60. package/src/vfs-bundle/prisma.js +167 -110
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +295 -318
  63. package/src/vfs-bundle/yarnclean.js +10 -31
  64. package/src/vfs-bundle.js +23 -64
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +75 -231
  67. package/src/installed-commits.js +0 -184
@@ -1,119 +1,57 @@
1
- // Cargo manifests for the Rust loader: Cargo.toml, Cargo.lock and cargo's configuration read by
2
- // @preventive/lockfile, per-bundle package lookup, dependency resolution among in-tree crates (the
3
- // package's own lib, workspace `path` deps, `cargo vendor`ed registry crates) and feature
4
- // resolution done the way `cargo build` does it, so `#[cfg(feature = "…")]` can be decided per
5
- // crate: @preventive/lockfile's, cargo's own resolver, where the build's lockfile and target are
6
- // known; a replay of the manifests otherwise.
1
+ // Cargo manifests for the Rust loader: dependency resolution among in-tree crates (path deps, `cargo
2
+ // vendor`ed ones) and feature resolution as `cargo build` does it: cargo's own resolver where it can run, else a replay.
7
3
 
8
4
  import { spawnSync } from 'node:child_process'
9
5
  import { createHash } from 'node:crypto'
10
- import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
6
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
11
7
  import { homedir } from 'node:os'
12
8
  import { dirname, isAbsolute, join, parse, posix, relative, resolve, sep } from 'node:path'
13
9
 
14
10
  import { readText } from '@exodus/stasis-core/bundle-util'
15
11
  import { diskHost } from '@exodus/stasis-core/host'
16
12
  import { canonicalizePath } from '@exodus/stasis-core/state-util'
17
- import { posixPathEscapes, relativeEscapes, toPosix } from '@exodus/stasis-core/util'
13
+ import { archiveIntegrity, fromEntries, isPlainObject, memoized, nestedMap, posixPathEscapes, relativeEscapes, toPosix, upsert } from '@exodus/stasis-core/util'
18
14
 
19
15
  import { LockfileError, linkCargo, parseCargoConfig, parseCargoLock, parseCargoManifest as readCargoManifest, readCargoVendor, resolveCargoFeatures } from '@preventive/lockfile/cargo.js'
20
16
  import { matches, parseVersion, parseVersionReq } from '@preventive/lockfile/rust-semver.js'
21
17
 
22
18
  import { isFile } from '../resolve-typescript.js'
19
+ import { ancestors } from './paths.js'
23
20
  import { TomlError, isTomlTable, nameErrors, readToml, splitTopLevel } from './toml.js'
24
21
 
25
- // `cargo vendor` copies registry crates in-tree under this dir.
26
22
  export const VENDOR_DIR = 'vendor'
27
23
 
28
24
  // A crate name as source spells it (`use proc_macro2`): Cargo allows `-`, rustc doesn't.
29
25
  export const normName = (name) => name.replaceAll('-', '_')
30
26
 
31
- // The file's bytes, or null when it can't be read.
32
- function readFileOrNull(file) {
33
- try {
34
- return readFileSync(file)
35
- } catch {
36
- return null
37
- }
38
- }
39
-
40
- // `map`'s value for `key` (a Map or WeakMap), computed on the first ask.
41
- export function cached(map, key, compute) {
42
- let value = map.get(key)
43
- if (value === undefined) {
44
- value = compute()
45
- map.set(key, value)
46
- }
47
- return value
48
- }
49
-
50
- // `dir` and each directory above it, the root last.
51
- function* ancestors(dir) {
52
- for (;;) {
53
- yield dir
54
- const parent = dirname(dir)
55
- if (parent === dir) return
56
- dir = parent
57
- }
58
- }
59
-
60
- // A TOML value that is a table, else null.
61
27
  const table = (v) => (isTomlTable(v) ? v : null)
62
28
 
63
- // --- Paths ---------------------------------------------------------------------------
64
-
65
- // Project-relative `sub` under `dir`, normalized; null when it escapes the bundle root.
66
29
  export function normalizeRel(dir, sub) {
67
30
  if (isAbsolute(sub) || posix.isAbsolute(sub)) return null
68
- const rel = posix.normalize(posix.join(dir === '.' ? '' : dir, sub))
69
- if (posixPathEscapes(rel)) return null
70
- return rel
31
+ const rel = posix.join(dir, sub)
32
+ return posixPathEscapes(rel) ? null : rel
71
33
  }
72
34
 
73
- // --- Cargo.toml -----------------------------------------------------------------------
74
-
75
35
  // A `[features]` entry asking a feature of a dependency: `key/feat` or `key?/feat`.
76
36
  const DEP_FEATURE_RE = /^([^/?]+)(\?)?\/(.+)$/u
77
37
 
78
- // `--features a,b pkg/c` (cargo's syntax: repeatable, comma- or space-separated) → the list of names.
79
38
  export function parseFeatureList(values) {
80
- return [...new Set(values.flatMap((s) => s.split(/[\s,]+/u)).map((s) => s.trim()).filter(Boolean))]
39
+ return [...new Set(values.flatMap((s) => s.split(/[\s,]+/u)).filter(Boolean))]
81
40
  }
82
41
 
83
- // Whether a source file belongs to a test or bench target of the package at `pkgDir` (`tests/*.rs`,
84
- // `benches/*.rs` and what they declare): rustc compiles those with `cfg(test)`.
42
+ const targetDirOf = (pkgDir, fileRel) => (pkgDir !== '.' && pkgDir !== '' && fileRel.startsWith(`${pkgDir}/`) ? fileRel.slice(pkgDir.length + 1) : fileRel).split('/')[0]
43
+
85
44
  export function isTestTargetPath(pkgDir, fileRel) {
86
- const first = targetDirOf(pkgDir, fileRel)
87
- return first === 'tests' || first === 'benches'
88
- }
89
- // Whether a file belongs to a target cargo builds with the dev-dependencies: a test, bench or
90
- // example (`examples/*.rs`), which unlike the other two isn't compiled with `cfg(test)`.
91
- function linksDevDepsPath(pkgDir, fileRel) {
92
- return isTestTargetPath(pkgDir, fileRel) || targetDirOf(pkgDir, fileRel) === 'examples'
93
- }
94
- // The first directory of a file's path inside its package.
95
- function targetDirOf(pkgDir, fileRel) {
96
- const inside = pkgDir === '.' || pkgDir === '' ? fileRel : (fileRel.startsWith(`${pkgDir}/`) ? fileRel.slice(pkgDir.length + 1) : fileRel)
97
- return inside.split('/')[0]
45
+ return ['tests', 'benches'].includes(targetDirOf(pkgDir, fileRel))
98
46
  }
99
47
 
100
- // `read()`, with a TomlError or LockfileError it throws naming `file`: what @preventive/lockfile
101
- // refuses stops the build, saying which file.
102
48
  const readNamed = (file, read) => nameErrors(file, read, [TomlError, LockfileError])
103
49
 
104
- // A Cargo.toml as the loader reads it: @preventive/lockfile's reading (`cargo`) -- the package, its
105
- // features (with the one each optional dependency no `dep:` names turns on) and every dependency
106
- // table, what a member inherits from its workspace applied, refused where cargo would refuse it or
107
- // the reader can't tell how cargo reads it -- plus what that reading leaves out: the lib target
108
- // (`[lib] name`, `path`) and the build script (`[package] build`). `workspace` is the workspace
109
- // root's, read before, for a member that inherits from it. Dependency keys are the `use` spelling
110
- // (`-` → `_`); each table is a request of its own, `<kind>` or `<kind>@<platform>` (`normal`,
111
- // `build`, `dev@cfg(windows)`): `[dependencies] rand = "0.7"` beside `[build-dependencies] rand =
112
- // "0.8"` are two crates, and sha2's dev-dependency on digest asks digest for nothing a build of
113
- // sha2's dependents sees; each entry has its `kind` and `target` (null for none) apart too. Throws
114
- // a TomlError or LockfileError naming `file`.
50
+ const requestKey = (d) => (d.target === undefined ? d.kind : `${d.kind}@${d.target}`)
51
+
52
+ // `cargo` as @preventive/lockfile reads it, plus the lib target and build script. `deps` are keyed by
53
+ // `use` spelling, each table (`normal`, `dev@cfg(windows)`) a request of its own.
115
54
  export const parseCargoManifest = (text, file = null, workspace = null) => manifestOf(text, readToml(text, file), file, workspace)
116
- // parseCargoManifest of `text` read as `doc` already.
117
55
  function manifestOf(text, doc, file, workspace) {
118
56
  const root = workspace?.cargo.workspace === undefined ? undefined : workspace.cargo
119
57
  const cargo = readNamed(file, () => readCargoManifest(text, isTomlTable(doc.workspace) ? undefined : root))
@@ -123,15 +61,13 @@ function manifestOf(text, doc, file, workspace) {
123
61
  const deps = new Map()
124
62
  for (const d of pkg?.dependencies ?? []) {
125
63
  const key = normName(d.name)
126
- if (!deps.has(key)) deps.set(key, { key, name: d.name, kinds: new Map() })
127
- deps.get(key).kinds.set(d.target === undefined ? d.kind : `${d.kind}@${d.target}`, {
64
+ upsert(deps, key, () => ({ key, name: d.name, kinds: new Map() })).kinds.set(requestKey(d), {
128
65
  kind: d.kind,
129
66
  target: d.target ?? null,
130
67
  version: d.version ?? null,
131
68
  path: d.source.type === 'path' ? d.source.path : null,
132
69
  source: d.source.type,
133
- // where from: a git dependency's repository URL, another registry's name or index than
134
- // crates.io's
70
+ // A git dependency's repository URL, another registry's name or index than crates.io's.
135
71
  origin: d.source.type === 'git' ? d.source.url : (d.source.type === 'registry' ? d.source.registry ?? d.source.index ?? null : null),
136
72
  package: d.package,
137
73
  renamed: d.package !== d.name,
@@ -151,74 +87,44 @@ function manifestOf(text, doc, file, workspace) {
151
87
  }
152
88
  }
153
89
 
154
- // Whether `version` satisfies the Cargo requirement `req`, by the semver crate's rules
155
- // (@preventive/lockfile's rust-semver.js): a prerelease only where the requirement names one of
156
- // its major, minor and patch.
157
90
  const satisfies = (version, req) => {
158
91
  const v = parseVersion(version)
159
92
  const comparators = parseVersionReq(req)
160
93
  return v !== undefined && comparators !== undefined && matches(comparators, v)
161
94
  }
162
95
 
163
- // --- cargo metadata -------------------------------------------------------------------
164
-
165
- // The Cargo.lock governing `baseDir`: beside the workspace root's Cargo.toml -- the nearest manifest
166
- // at or above `baseDir` with a `[workspace]` table, as cargo finds it -- else beside `baseDir`'s
167
- // own. A lock further up belongs to some other project: passing `--locked` for it would make
168
- // cargo refuse to create the one it needs. Read of `host`, the disk's unless given.
96
+ // Beside the nearest manifest at or above `baseDir` with a `[workspace]`, else beside its own. A lock
97
+ // further up is another project's: `--locked` for it would make cargo refuse to create the one it needs.
169
98
  export function findCargoLock(baseDir, host = diskHost) {
170
- let root = baseDir
171
- for (const dir of ancestors(baseDir)) {
99
+ const root = ancestors(baseDir).find((dir) => {
172
100
  const file = join(dir, 'Cargo.toml')
173
101
  const text = readText(host, file)
174
- if (text !== null && 'workspace' in readToml(text, file)) {
175
- root = dir
176
- break
177
- }
178
- }
102
+ return text !== null && 'workspace' in readToml(text, file)
103
+ }) ?? baseDir
179
104
  const candidate = join(root, 'Cargo.lock')
180
105
  return isFile(candidate, host) ? candidate : null
181
106
  }
182
107
 
183
- // --- cfg predicates ---------------------------------------------------------------------
184
-
185
- // A cfg predicate with its whitespace collapsed outside string literals: `my = "a b"` and
186
- // `my = "a b"` are two values.
108
+ // Whitespace inside string literals is kept: `my = "a b"` and `my = "a b"` are two values.
187
109
  export const normalizeCfg = (pred) => pred.replaceAll(/"(?:[^"\\]|\\.)*"|\s+/gu, (m) => (m.startsWith('"') ? m : ' ')).trim()
188
110
 
189
- // A cfg name as written, a raw identifier's `r#` dropped -- but `r#true` and `r#false`, names apart
190
- // from the literals `true` and `false`.
111
+ // `r#true` and `r#false` keep their `r#`: names apart from the literals `true` and `false`.
191
112
  export const cfgName = (written) => (/^r#(?:true|false)$/u.test(written) ? written : written.replace(/^r#/u, ''))
192
113
 
193
- // A leaf: `unix`, `target_os = "linux"`, a raw identifier's `r#` dropped.
194
114
  const CFG_LEAF_RE = /^(?:r#)?([A-Za-z_]\w*)\s*(?:=\s*"([^"]*)")?$/u
195
115
 
196
- // The cfg keys rustc sets from the target alone (`rustc --print cfg --target <triple>`), decided by
197
- // membership in that set when the target is known. Not among them: `debug_assertions`, `panic`,
198
- // `overflow_checks` and the like, which the build profile sets; `target_feature`, which the build
199
- // may add to or take from (`-C target-feature=-crt-static`, `-C target-cpu=native`); and
200
- // `target_thread_local`, which a stable rustc never prints.
116
+ // The cfg keys rustc sets from the target alone. Not among them: what the build profile sets, a
117
+ // `target_feature` the build may change (`-C target-cpu=native`), and `target_thread_local` (never on stable).
201
118
  export const TARGET_CFG_KEYS = new Set(['unix', 'windows', 'target_abi', 'target_arch', 'target_endian', 'target_env', 'target_family', 'target_has_atomic', 'target_os', 'target_pointer_width', 'target_vendor'])
202
119
 
203
- // Three-valued evaluation of a cfg predicate: `false` when it can never hold in the build (so the
204
- // item it gates is dead code for the bundle), `true` when it always does, `null` when the loader
205
- // can't tell. `all`/`any`/`not` compose. `test` holds only in a test/bench target (`env.test`);
206
- // `doctest` and `doc` never do when a program is built; `feature = "x"` is decided against
207
- // `env.features`, the crate's features on for certain (see createCargoContext) -- unknown for one
208
- // of `env.maybeFeatures`, on only in some builds, and without either set; a target leaf (`unix`,
209
- // `target_os = …`) against `env.target`, the platform's cfg set as rustc prints it
210
- // (rustcTargetCfgs), and unknown without one; every other leaf stays unknown. `env.units`, a list
211
- // of such envs, is code compiled several ways (a crate built for the target and, as a
212
- // build-dependency, for the host): false only when false in each, true only when true in each.
213
- // A predicate an unknown leaf occurs in more than once is decided when it comes out the same
214
- // whatever the unknown leaves are (up to six of them): `all(any(test, kani), not(kani))` -- zerocopy's
215
- // `#[cfg(any(test, kani))] mod tests { #[cfg(not(kani))] mod compatibility { … } }` -- never holds.
120
+ // False when the predicate never holds in the build, true when it always does, null when unknown. An
121
+ // unknown leaf met more than once is tried both ways (up to six of them): `all(any(test, kani), not(kani))` never holds.
216
122
  const MAX_FREE_CFG_LEAVES = 6
217
123
  export function evalCfg(pred, env = {}) {
218
124
  if (env.units) return unanimous(env.units.map((u) => evalCfg(pred, u)))
219
125
  const free = { counts: null } // unknown leaf → how often it occurs, once one is met
220
126
  const r = evalCfgWith(pred, env, null, free)
221
- if (r !== null || free.counts === null || free.counts.size > MAX_FREE_CFG_LEAVES || [...free.counts.values()].every((n) => n === 1)) return r
127
+ if (r !== null || free.counts === null || free.counts.size > MAX_FREE_CFG_LEAVES || free.counts.values().every((n) => n === 1)) return r
222
128
  const leaves = [...free.counts.keys()]
223
129
  let out
224
130
  for (let bits = 0; bits < 1 << leaves.length; bits++) {
@@ -228,13 +134,11 @@ export function evalCfg(pred, env = {}) {
228
134
  }
229
135
  return out
230
136
  }
231
- // evalCfg's three-valued pass: an unknown leaf takes its value from `assume` (leaf → value) when
232
- // that has it, else is counted in `free.counts`.
233
137
  function evalCfgWith(pred, env, assume, free = null) {
234
138
  const p = pred.trim()
235
139
  const m = /^(all|any|not)\s*\(([\s\S]*)\)$/u.exec(p)
236
140
  if (!m) {
237
- if (p === 'true' || p === 'false') return p === 'true' // the literals (rustc 1.88); `r#true` is a name
141
+ if (p === 'true' || p === 'false') return p === 'true' // the literals (rustc 1.88)
238
142
  const kv = CFG_LEAF_RE.exec(p)
239
143
  const known = kv === null ? null : evalCfgKey(kv[1], kv[2] ?? null, env)
240
144
  if (known !== null) return known
@@ -249,76 +153,56 @@ function evalCfgWith(pred, env, assume, free = null) {
249
153
  if (m[1] === 'all') return args.includes(false) ? false : (args.every((a) => a === true) ? true : null)
250
154
  return args.includes(true) ? true : (args.every((a) => a === false) ? false : null)
251
155
  }
252
- // The verdict on one leaf other than a literal, by its key and value (`target_os = "linux"`; null
253
- // for a bare `unix`), as evalCfg gives it -- `env.units` too.
254
156
  export function evalCfgKey(key, value, env) {
255
157
  if (env.units) return unanimous(env.units.map((u) => evalCfgKey(key, value, u)))
256
158
  if (value === null && key === 'test') return env.test === true
257
159
  if (value === null && (key === 'doctest' || key === 'doc')) return false
258
- if (key === 'feature' && value !== null) return env.features ? (env.features.has(value) ? true : (env.maybeFeatures?.has(value) ? null : false)) : null
160
+ if (key === 'feature' && value !== null) {
161
+ if (!env.features) return null
162
+ if (env.features.has(value)) return true
163
+ return env.maybeFeatures?.has(value) ? null : false
164
+ }
259
165
  if (env.target && TARGET_CFG_KEYS.has(key)) return env.target.has(value === null ? key : `${key}="${value}"`)
260
166
  return null
261
167
  }
262
- // Code compiled several ways: false only when false in each, true only when true in each.
263
168
  const unanimous = (each) => (each.every((r) => r === false) ? false : (each.every((r) => r === true) ? true : null))
264
169
 
265
- // `rustc --print cfg` output → the set of cfg leaves as printed, one per line (`unix`,
266
- // `target_os="linux"`).
267
170
  export function parseRustcCfg(text) {
268
171
  return new Set(text.split('\n').map((l) => l.trim()).filter(Boolean))
269
172
  }
270
173
 
271
- // How long a toolchain query may take before it counts as hung.
272
- const TOOL_TIMEOUT_MS = 60_000
273
174
  // Never let rustup install a toolchain on the loader's behalf, whatever a `rust-toolchain` file says.
274
175
  const TOOL_ENV = { ...process.env, RUSTUP_AUTO_INSTALL: '0' }
275
- // Where rustc is run from: the user's home directory, else the filesystem root. A rustup proxy
276
- // picks its toolchain from the `rust-toolchain(.toml)` files of the working directory and its
277
- // parents, and such a file may name a `path` to any binary -- so never the project being bundled
278
- // (untrusted input: its toolchain file must not choose what runs), and never a temp dir (anyone
279
- // can plant a file in a world-writable one). The home directory is the user's -- unless it is the
280
- // bundle root (`baseDir`) or lies inside it (a project bundled from a home directory, a CI job
281
- // whose HOME is its checkout): then the root, whose toolchain file, if any, is the machine's.
176
+ // A rustup proxy obeys the `rust-toolchain(.toml)` of its cwd and parents, which may name any binary:
177
+ // never run in the (untrusted) project nor a world-writable temp dir, but in the home directory --
178
+ // unless it is or lies inside the bundle root (by real path), then in the filesystem root.
282
179
  function toolCwd(baseDir) {
283
180
  const home = homedir()
284
181
  const root = parse(process.cwd()).root
285
182
  if (!home) return root
286
183
  if (baseDir === null) return home
287
- // Real paths: a home directory or bundle root reached through a link is where it really is.
288
184
  const base = canonicalizePath(baseDir)
289
185
  const homeAbs = canonicalizePath(home)
290
186
  return homeAbs === base || homeAbs.startsWith(base.endsWith(sep) ? base : base + sep) ? root : home
291
187
  }
292
188
 
293
- // Run rustc: `$RUSTC` when set, as cargo honours it (a target only another toolchain knows, such
294
- // as Solana's `sbf-solana-solana` in its platform-tools), else `rustc` from PATH -- a rustup proxy
295
- // resolving to the user's default toolchain (or `RUSTUP_TOOLCHAIN`), from toolCwd. With
296
- // RUSTUP_AUTO_INSTALL=0 an uninstalled toolchain is an error, not a download.
189
+ // `$RUSTC` when set, as cargo honours it (a target only another toolchain knows, as Solana's).
297
190
  function rustc(args, what, baseDir) {
298
191
  const bin = process.env.RUSTC || 'rustc'
299
- const r = spawnSync(bin, args, { cwd: toolCwd(baseDir), encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: TOOL_TIMEOUT_MS, env: TOOL_ENV })
192
+ const r = spawnSync(bin, args, { cwd: toolCwd(baseDir), encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 60_000, env: TOOL_ENV })
300
193
  if (r.error) throw new Error(`${bin} could not run (${r.error.message}); ${what} needs rustc on PATH (or $RUSTC)`, { cause: r.error })
301
194
  if (r.status !== 0) throw new Error(`${bin} ${args.join(' ')} failed (exit ${r.status}):\n${(r.stderr ?? '').trim()}`)
302
195
  return r.stdout
303
196
  }
304
197
 
305
- // The cfg set of a target: `{ triple, cfgs }` from `rustc --print cfg --target <triple>`, which
306
- // needs only rustc's built-in knowledge of the target, not its standard library. `host` is the
307
- // running rustc's host triple (`rustc -vV`). `baseDir` is the bundle root, which rustc is never
308
- // run from (toolCwd).
309
198
  export function rustcTargetCfgs(target, baseDir = null) {
310
199
  const triple = target === 'host' ? /^host: (\S+)$/mu.exec(rustc(['-vV'], '--cargo-target=host', baseDir))?.[1] ?? null : target
311
200
  if (triple === null) throw new Error('rustc -vV printed no host triple')
312
201
  return { triple, cfgs: parseRustcCfg(rustc(['--print', 'cfg', '--target', triple], '--cargo-target', baseDir)) }
313
202
  }
314
203
 
315
- // Run `cargo metadata` in `dir` (the directory the build runs in, inside the bundle root) and
316
- // return its JSON. Opt-in (`--cargo`) because it runs cargo, which reads the project's
317
- // `.cargo/config.toml` and may touch the registry and Cargo.lock (doc/file-formats.md has the full
318
- // caveat); never run on a bundle root unasked. With a lockfile present, `--locked` keeps the
319
- // resolution the one the build uses. The feature flags pass through; `platform`, a target triple,
320
- // restricts the graph to that target's dependencies.
321
- function runCargoMetadata(dir, { features = [], noDefaultFeatures = false, allFeatures = false, platform = null } = {}) {
204
+ // Opt-in (`--cargo`): cargo reads the project's `.cargo/config.toml` and may touch the registry.
205
+ function runCargoMetadata(dir, { features, noDefaultFeatures, allFeatures, platform }) {
322
206
  const args = ['metadata', '--format-version', '1']
323
207
  // The workspace's lock may sit above the bundle root: never let metadata rewrite it.
324
208
  if (findCargoLock(dir) !== null) args.push('--locked')
@@ -332,21 +216,9 @@ function runCargoMetadata(dir, { features = [], noDefaultFeatures = false, allFe
332
216
  return JSON.parse(r.stdout)
333
217
  }
334
218
 
335
- // `cargo metadata` JSON → `{ enabled: Map<dir, Set<feature>>, deps: Map<dir, Map<useName, dir>>,
336
- // lacking: [{ dir, key, name, kinds }] }` over the packages the bundle can carry: those whose
337
- // manifest lies inside the bundle root, plus registry packages cargo read from `~/.cargo/registry`
338
- // (no `.cargo/config.toml` redirecting crates.io to `vendor/`) that `locate(name, version)` finds
339
- // vendored in-tree -- `cargo vendor` copies exactly the lockfile's versions, so name + version
340
- // identify the dir. Anything else (an unvendored registry crate, a path dep outside the root)
341
- // can't be bundled: it is in `lacking`, once per package depending on it (`dir`), by its package
342
- // name (`name`; `key` with `-` → `_`), with the kinds of the tables naming it (`normal`, `dev`,
343
- // `build`). `deps` maps each package's dependencies by the name code refers to them with (renames
344
- // applied, `-` → `_`).
219
+ // A dependency on a package neither inside the bundle root nor vendored (`locate`) is `lacking`.
345
220
  export function resolutionFromMetadata(metadata, baseDir, { locate = null } = {}) {
346
- let realBase = baseDir
347
- try {
348
- realBase = realpathSync(baseDir)
349
- } catch { /* keep the lexical path */ }
221
+ const realBase = canonicalizePath(baseDir)
350
222
  const relDir = (manifestPath) => {
351
223
  if (typeof manifestPath !== 'string') return null
352
224
  const dir = dirname(manifestPath)
@@ -373,62 +245,45 @@ export function resolutionFromMetadata(metadata, baseDir, { locate = null } = {}
373
245
  const byName = new Map()
374
246
  for (const d of node.deps ?? []) {
375
247
  const target = dirOf.get(d.pkg)
376
- if (target !== undefined && typeof d.name === 'string') byName.set(normName(d.name), target)
377
- else if (target === undefined) {
378
- const name = nameOf.get(d.pkg) ?? d.name
379
- lacking.push({ dir, key: normName(name), name, kinds: new Set((Array.isArray(d.dep_kinds) ? d.dep_kinds : [{ kind: null }]).map((k) => k?.kind ?? 'normal')) })
248
+ if (target !== undefined) {
249
+ if (typeof d.name === 'string') byName.set(normName(d.name), target)
250
+ continue
380
251
  }
252
+ const name = nameOf.get(d.pkg) ?? d.name
253
+ lacking.push({ dir, key: normName(name), name, kinds: new Set((Array.isArray(d.dep_kinds) ? d.dep_kinds : [{ kind: null }]).map((k) => k?.kind ?? 'normal')) })
381
254
  }
382
255
  deps.set(dir, byName)
383
256
  }
384
257
  return { enabled, deps, lacking }
385
258
  }
386
259
 
387
- // The cargo config file in absolute directory `abs`: `.cargo/config` when it exists -- cargo
388
- // prefers the extensionless file over `.cargo/config.toml` when both are there -- else
389
- // `.cargo/config.toml`; null when there is neither.
260
+ // `.cargo/config`, which cargo prefers, else `.cargo/config.toml`.
390
261
  const cargoConfigAt = (abs) => ['.cargo/config', '.cargo/config.toml'].map((f) => join(abs, f)).find((file) => isFile(file)) ?? null
391
262
 
392
- // The cargo configs a build run in `from` (a project-relative dir) reads, as cargo finds them: the
393
- // config of that directory and of every one above it to the filesystem's root, the nearest first
394
- // -- those above the bundle root too, read but never bundled; `$CARGO_HOME`'s, the machine's, is
395
- // not -- as `{ dir, abs, file, text, doc }`: `dir` the directory holding its `.cargo`,
396
- // project-relative (null above the bundle root), `abs` the same absolute, `file` the config's
397
- // path from the bundle root. Throws a TomlError naming a config that isn't TOML.
263
+ // Nearest first, up to the filesystem's root ($CARGO_HOME's aside); `dir` is null above the bundle root.
398
264
  function cargoConfigs(baseDir, from) {
399
265
  const baseAbs = resolve(baseDir)
400
266
  const out = []
401
267
  for (const abs of ancestors(join(baseAbs, from))) {
402
268
  const found = cargoConfigAt(abs)
403
269
  const text = found === null ? null : readText(diskHost, found)
404
- if (text !== null) {
405
- const file = toPosix(relative(baseAbs, found))
406
- out.push({ dir: projectRel(baseAbs, abs), abs, file, text, doc: readToml(text, file) })
407
- }
270
+ if (text === null) continue
271
+ const file = toPosix(relative(baseAbs, found))
272
+ out.push({ dir: projectRel(baseAbs, abs), abs, file, text, doc: readToml(text, file) })
408
273
  }
409
274
  return out
410
275
  }
411
- // A path a cargo config or a manifest in absolute directory `absDir` writes (`.`: that directory),
412
- // as cargo takes it -- relative to that directory, an absolute one as it is -- project-relative
413
- // from the bundle root `baseAbs`; null outside it. A config's paths are relative to the directory
414
- // holding its `.cargo` (cargoConfigs' `abs`).
415
276
  const projectRel = (baseAbs, absDir, path = '.') => normalizeRel('.', toPosix(relative(baseAbs, resolve(absDir, path))))
416
277
 
417
- // The directory `cargo vendor` filled, as cargo configs `configs` (cargoConfigs) say: their
418
- // `[source]` tables merged as cargo merges them, each source's each key from the nearest config
419
- // writing it -- the `directory` of the source `[source.crates-io] replace-with` names, through any
420
- // chain of replacements (`cargo vendor` suggests `vendored-sources`, but any name does), else of
421
- // the one source some `replace-with` names, relative to the directory holding the `.cargo` of the
422
- // config writing it; the default `vendor` (at the bundle root) when nothing replaces a source
423
- // with a directory. A configured directory outside the bundle root, or that doesn't exist, is
424
- // warned about (a stale `vendor/` beside it is not what cargo builds from) unless `quiet`.
278
+ // The `directory` of the source `[source.crates-io] replace-with` names (through any chain), else of
279
+ // the one source some `replace-with` names, else `vendor`. One outside the bundle root or missing is warned of.
425
280
  function vendorDirOf(baseDir, configs, { quiet = false } = {}) {
426
- // source name -> { replaceWith, directory: { path, config } }
281
+ // Each key from the nearest config.
427
282
  const sources = new Map()
428
283
  for (const config of configs) {
429
- for (const [name, fields] of Object.entries(isTomlTable(config.doc.source) ? config.doc.source : {})) {
284
+ for (const [name, fields] of Object.entries(table(config.doc.source) ?? {})) {
430
285
  if (!isTomlTable(fields)) continue
431
- const s = sources.get(name) ?? sources.set(name, { replaceWith: null, directory: null }).get(name)
286
+ const s = upsert(sources, name, () => ({ replaceWith: null, directory: null }))
432
287
  if (s.replaceWith === null && typeof fields['replace-with'] === 'string') s.replaceWith = fields['replace-with']
433
288
  if (s.directory === null && typeof fields.directory === 'string') s.directory = { path: fields.directory, config }
434
289
  }
@@ -438,11 +293,10 @@ function vendorDirOf(baseDir, configs, { quiet = false } = {}) {
438
293
  for (let s = sources.get(name); s && !seen.has(s); s = sources.get(s.replaceWith)) {
439
294
  seen.add(s)
440
295
  if (s.directory !== null) return s.directory
441
- if (s.replaceWith === null) return null
442
296
  }
443
297
  return null
444
298
  }
445
- const replaced = new Set([...sources.values()].map((s) => (s.replaceWith === null ? null : follow(s.replaceWith))).filter((d) => d !== null))
299
+ const replaced = new Set(sources.values().map((s) => (s.replaceWith === null ? null : follow(s.replaceWith))).filter((d) => d !== null))
446
300
  const found = follow('crates-io') ?? (replaced.size === 1 ? [...replaced][0] : null)
447
301
  if (found === null) return VENDOR_DIR
448
302
  const norm = projectRel(resolve(baseDir), found.config.abs, found.path)?.replace(/\/+$/u, '') || null
@@ -454,28 +308,17 @@ function vendorDirOf(baseDir, configs, { quiet = false } = {}) {
454
308
  return norm
455
309
  }
456
310
 
457
- // The `--cfg` names in rustflags: `--cfg name`, `--cfg=name`, `--cfg 'name="value"'`.
458
- function cfgFlags(flags) {
459
- const out = []
460
- for (let i = 0; i < flags.length; i++) {
461
- const flag = flags[i]
462
- const arg = flag === '--cfg' ? flags[++i] : (flag.startsWith('--cfg=') ? flag.slice('--cfg='.length) : null)
463
- const name = typeof arg === 'string' ? /^(?:r#)?[A-Za-z_]\w*/u.exec(arg)?.[0] : undefined
464
- if (name !== undefined) out.push(cfgName(name))
465
- }
466
- return out
467
- }
468
- // The cfgs the rustflags of a build may set: those of the `build.rustflags` and
469
- // `target.<…>.rustflags` of each of its cargo configs (`configs`, see cargoConfigs: which applies,
470
- // and how cargo joins them, is the build's business), and of the environment cargo reads them
471
- // from (CARGO_ENCODED_RUSTFLAGS, RUSTFLAGS, CARGO_BUILD_RUSTFLAGS).
472
311
  function rustflagsCfgsOf(configs) {
473
312
  const names = new Set()
474
313
  const add = (value) => {
475
314
  const flags = Array.isArray(value) ? value.filter((f) => typeof f === 'string') : (typeof value === 'string' ? value.split(/\s+/u).filter(Boolean) : [])
476
- for (const name of cfgFlags(flags)) names.add(name)
315
+ for (let i = 0; i < flags.length; i++) {
316
+ const flag = flags[i]
317
+ const arg = flag === '--cfg' ? flags[++i] : (flag.startsWith('--cfg=') ? flag.slice('--cfg='.length) : null)
318
+ const name = typeof arg === 'string' ? /^(?:r#)?[A-Za-z_]\w*/u.exec(arg)?.[0] : undefined
319
+ if (name !== undefined) names.add(cfgName(name))
320
+ }
477
321
  }
478
- // The `rustflags` of the `build` table and of every `target.<…>` one.
479
322
  for (const { doc } of configs) {
480
323
  add(table(doc.build)?.rustflags)
481
324
  for (const target of Object.values(table(doc.target) ?? {})) add(table(target)?.rustflags)
@@ -485,12 +328,8 @@ function rustflagsCfgsOf(configs) {
485
328
  for (const v of [env.RUSTFLAGS, env.CARGO_BUILD_RUSTFLAGS]) if (v) add(v)
486
329
  return names
487
330
  }
488
- // What code a build script runs -- its own, or a lib it calls -- prints as
489
- // `cargo:rustc-cfg=<name>` (or `cargo::`), among the texts of its files, by what they write
490
- // outside full-line comments: the names it may set, and whether it may set one the loader can't
491
- // read -- a name it formats, whole (`rustc-cfg={}`, as cfg_aliases' `cfg_aliases!` does) or in
492
- // part (`rustc-cfg=os_{}`), the directive written apart from the name (build-rs's `rustc_cfg`),
493
- // `autocfg`'s probes.
331
+ // The cfgs build-script code may print as `cargo:rustc-cfg=<name>`, outside full-line comments; `any`
332
+ // when it may print one the loader can't read (a formatted name, as cfg_aliases does, build-rs, autocfg).
494
333
  const RUSTC_CFG_RE = /cargo::?rustc-cfg=((?:r#)?[A-Za-z_]\w*)?(\{)?/gu
495
334
  const CFG_MENTION_RE = /rustc[-_]cfg|\bautocfg\b/u
496
335
  function cfgsPrinted(texts) {
@@ -508,24 +347,18 @@ function cfgsPrinted(texts) {
508
347
  return { names, any }
509
348
  }
510
349
 
511
- // Whether a JSON value is a plain object (not an array, not null).
512
- const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
513
-
514
- // A source URL as cargo compares them: no trailing `/` or `.git`, the scheme and host lowercased.
515
350
  const canonicalUrl = (url) => url.trim().replace(/\/+$/u, '').replace(/\.git$/u, '').replace(/^([a-z][\w+.-]*:\/\/)([^/]*)/iu, (m) => m.toLowerCase())
516
- // crates.io's index, as a `[patch.<url>]` may name it.
351
+ const cfgPredicate = (spec) => /^cfg\((.*)\)$/su.exec(spec)?.[1]
517
352
  const CRATES_IO_INDEXES = new Set(['https://github.com/rust-lang/crates.io-index', 'sparse+https://index.crates.io'].map(canonicalUrl))
518
353
 
519
- // A `members` pattern's segment as a regex (glob's syntax, as cargo takes it: `*`, `?`, `[…]`).
520
354
  const globSegment = (seg) => new RegExp(`^${seg.replaceAll(/[.+^${}()|\\]/gu, '\\$&').replaceAll('[!', '[^').replaceAll('*', '[^/]*').replaceAll('?', '[^/]')}$`, 'u')
521
355
 
522
- // The stand-in platforms cargo's resolver is run against (see resolveGraph): each carries a mark
523
- // of its own, and the cfgs and a mark of the name of the platform it stands in for, where known.
356
+ // The stand-in platforms cargo's resolver is run against (see resolveGraph): each carries a mark of
357
+ // its own, and the cfgs and a mark of the name of the platform it stands in for, where known.
524
358
  const MARK_TARGET = '__stasis_target'
525
359
  const MARK_HOST = '__stasis_host'
526
360
  const MARK_NAME = '__stasis_target_name'
527
361
  const standInPlatform = (mark, info) => ({ name: mark, cfg: [mark, ...(info === null ? [] : [...info.cfgs, `${MARK_NAME}="${info.triple}"`])] })
528
- // `graph` with the platform of every target-specific dependency `to(platform)`.
529
362
  function retarget(graph, to) {
530
363
  const packages = Object.create(null)
531
364
  for (const [key, pkg] of Object.entries(graph.packages)) {
@@ -534,52 +367,35 @@ function retarget(graph, to) {
534
367
  return { ...graph, packages }
535
368
  }
536
369
 
537
- // --- Context ----------------------------------------------------------------------------
538
-
539
- // No custom cfg a build sets (see cfgsSetFor).
540
370
  const NO_CFGS_SET = { names: new Set(), any: false }
541
371
 
542
- // A compile unit: the feature context a file's code sees (`target`: the build's; `host`: that of
543
- // what is built for the host -- build-dependencies, proc-macro crates and their dependencies --
544
- // which resolver 2 keeps apart) and the platform it is compiled for, as `<features>|<platform>`.
545
- // A package's code is compiled as `target|target`, its build script as `target|host`, a
546
- // build-dependency's or proc-macro's code as `host|host`; one file may be compiled as several.
372
+ // A compile unit, `<features>|<platform>`: the feature context its code sees (`host` for what is built
373
+ // for the host, which resolver 2 keeps apart) and the platform it is compiled for.
547
374
  const unitKey = (featureCtx, platform) => `${featureCtx}|${platform}`
548
375
  export const TARGET_UNIT = unitKey('target', 'target')
549
376
  export const HOST_UNIT = unitKey('host', 'host')
550
377
  const unitFeatureCtx = (unit) => unit.slice(0, unit.indexOf('|'))
551
378
  const unitPlatform = (unit) => unit.slice(unit.indexOf('|') + 1)
552
379
 
553
- // Per-bundle Cargo state: manifest lookup (memoized per directory), crate-name resolution against
554
- // in-tree sources, and feature resolution for the packages owning `entries` (the crate roots being
555
- // bundled, like `cargo build -p …`). `features` / `noDefaultFeatures` / `allFeatures` mirror
556
- // cargo's flags for those root packages (`pkg/feat` targets one of them). `cargo: true` takes the
557
- // dependency graph and features from `cargo metadata` (see runCargoMetadata) instead. `target`
558
- // names the build's target -- a triple or `host`, asked of rustc (rustcTargetCfgs), or its `{
559
- // triple, cfgs }` outright -- so target-specific dependency tables and `#[cfg(unix)]`-style code
560
- // are decided; without one they are kept. The host's platform is known when the target is the
561
- // host, or given as `host` (`{ triple, cfgs }`). `baseDir` is the bundle root; every path in and
562
- // out is project-relative POSIX.
380
+ // Per-bundle Cargo state for the packages owning `entries`, built like `cargo build -p …` with
381
+ // cargo's feature flags (`cargo: true` asks `cargo metadata` instead). `target`: a triple or `host`
382
+ // for rustc to describe, or `{ triple, cfgs }`; without one, target-specific code is kept.
563
383
  export function createCargoContext(baseDir, { entries = [], features = [], noDefaultFeatures = false, allFeatures = false, cargo = false, target = null, host = null } = {}) {
564
384
  const targetInfo = target === null ? null : (typeof target === 'string' ? rustcTargetCfgs(target, baseDir) : target)
565
385
  const hostInfo = target === 'host' ? targetInfo : host
566
- const manifests = new Map()
567
- // dir -> the manifest as `{ file, text, buf, doc }` (its bytes, and its table tree), or null
568
- // (rootOf's look for [workspace])
569
- const tables = new Map()
570
- const tableOf = (dir) => cached(tables, dir, () => {
386
+ const baseAbs = resolve(baseDir)
387
+ const tableOf = memoized((dir) => {
571
388
  const file = posix.join(dir, 'Cargo.toml')
572
- const buf = readFileOrNull(join(baseDir, file))
573
- const text = buf === null ? null : buf.toString('utf8')
574
- return text === null ? null : { file, text, buf, doc: readToml(text, file) }
389
+ let buf
390
+ try {
391
+ buf = readFileSync(join(baseDir, file))
392
+ } catch {
393
+ return null
394
+ }
395
+ const text = buf.toString('utf8')
396
+ return { file, text, buf, doc: readToml(text, file) }
575
397
  })
576
- // The workspace root of the package whose manifest is at `dir` (its table tree `doc`), as cargo
577
- // finds it: its `[package] workspace` path, else the nearest manifest above it with a
578
- // [workspace] that doesn't exclude it -- one that does is passed over, as cargo passes it --
579
- // inside the bundle root (a project-relative dir), else above it (outerWorkspace). A [workspace]
580
- // that doesn't exclude the package is its workspace, `members` or not: cargo either takes it as
581
- // a member there (a member's path dependency is one) or refuses to build it. Null for a root, a
582
- // vendored crate (a published manifest inherits nothing) or a package outside any workspace.
398
+ // Null for a root, a vendored crate (a published one inherits nothing) or none.
583
399
  const rootOf = (dir, doc) => {
584
400
  if (isTomlTable(doc.workspace) || isVendoredDir(dir)) return null
585
401
  const named = table(doc.package)?.workspace
@@ -596,48 +412,33 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
596
412
  }
597
413
  return null
598
414
  }
599
- // Whether the [workspace] of the manifest `doc` at absolute `abs` excludes the package at
600
- // absolute `pkgAbs`, as cargo has it: under an `exclude` path and under no `members` one.
601
415
  const excludes = (doc, abs, pkgAbs) => {
602
416
  const under = (p) => typeof p === 'string' && (pkgAbs === join(abs, p) || pkgAbs.startsWith(`${join(abs, p)}${sep}`))
603
417
  const list = (v) => (Array.isArray(v) ? v : [])
604
418
  return list(doc.workspace.exclude).some(under) && !list(doc.workspace.members).some(under)
605
419
  }
606
- // The workspace root at absolute `abs`, above the bundle root: the manifest there with a
607
- // [workspace], read for what members inherit, the resolver it sets and its `[patch]` -- never
608
- // bundled, nor its lockfile read -- as `{ dir: null, outside: abs, file, doc, … }` (see
609
- // readManifest; `file` its path from the bundle root); undefined for no [workspace] there.
610
- const baseAbs = resolve(baseDir)
611
- const outer = new Map()
612
- const outerWorkspace = (abs) => {
613
- if (!outer.has(abs)) {
614
- const file = join(abs, 'Cargo.toml')
615
- const text = readText(diskHost, file)
616
- const label = toPosix(relative(baseAbs, file))
617
- const doc = text === null ? null : readToml(text, label)
618
- outer.set(abs, isTomlTable(doc?.workspace) ? { dir: null, outside: abs, file: label, doc, ...manifestOf(text, doc, label, null) } : undefined)
619
- }
620
- return outer.get(abs)
621
- }
622
- // A manifest as parseCargoManifest reads it, at `file` (`dir`'s Cargo.toml), with each path
623
- // dependency's directory, project-relative, on its entry (`dir`; null outside the bundle root):
624
- // an inherited one's path is the workspace root's.
625
- // `workspaceRoot` is the manifest of the workspace root it inherits from (rootOf), or null.
626
- // A vendored package's is as the vendor directory lists it, not yet checked (see readManifest).
627
- const manifestAt = (dir) => cached(manifests, dir, () => {
420
+ // Read for what members inherit, its resolver and `[patch]`, never bundled.
421
+ const outerWorkspace = memoized((abs) => {
422
+ const file = join(abs, 'Cargo.toml')
423
+ const text = readText(diskHost, file)
424
+ const label = toPosix(relative(baseAbs, file))
425
+ const doc = text === null ? null : readToml(text, label)
426
+ return isTomlTable(doc?.workspace) ? { dir: null, outside: abs, file: label, doc, ...manifestOf(text, doc, label, null) } : undefined
427
+ })
428
+ // A vendored package's is `unchecked` until readManifest checks it.
429
+ const manifestAt = memoized((dir) => {
628
430
  const raw = tableOf(dir)
629
- const root = raw === null ? null : rootOf(dir, raw.doc)
630
- const ws = root === null ? null : (typeof root === 'string' ? readManifest(root) : root)
631
- const m = raw === null ? null : { dir, file: raw.file, ...manifestOf(raw.text, raw.doc, raw.file, ws), workspaceRoot: ws, unchecked: isVendoredDir(dir) }
632
- for (const d of m?.deps.values() ?? []) {
431
+ if (raw === null) return null
432
+ const root = rootOf(dir, raw.doc)
433
+ const ws = typeof root === 'string' ? readManifest(root) : root
434
+ const m = { dir, file: raw.file, ...manifestOf(raw.text, raw.doc, raw.file, ws), workspaceRoot: ws, unchecked: isVendoredDir(dir) }
435
+ for (const d of m.deps.values()) {
633
436
  for (const r of d.kinds.values()) r.dir = r.path === null ? null : manifestPath(r.inherited && ws !== null ? ws : m, r.path)
634
437
  }
635
438
  return m
636
439
  })
637
- // The manifest at `dir` as the build takes it in (manifestAt): a vendored package's checked
638
- // against its `.cargo-checksum.json` (checkVendored), the bytes read, before what it says --
639
- // features, dependencies -- decides anything. Only a listing of the vendor directory reads a copy
640
- // unchecked: cargo checks the files of a copy it builds, not of every copy there.
440
+ // A vendored package's manifest is checked against its `.cargo-checksum.json` before what it says
441
+ // decides anything. Only a listing of the vendor directory reads one unchecked: cargo checks only a copy it builds.
641
442
  const readManifest = (dir) => {
642
443
  const m = manifestAt(dir)
643
444
  if (m?.unchecked) {
@@ -646,81 +447,38 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
646
447
  }
647
448
  return m
648
449
  }
649
- // The directory a path manifest `m` writes names, project-relative (null outside the bundle
650
- // root): relative to its directory, inside the bundle root or above it (`outside`).
651
450
  const manifestPath = (m, path) => (m.outside === undefined ? normalizeRel(m.dir, path) : projectRel(baseAbs, m.outside, path))
652
- // Manifests at or above `dir`, nearest first, up to the bundle root.
653
- const manifestsAbove = function* (dir) {
654
- for (;;) {
451
+ const packageFor = memoized((fileRel) => {
452
+ for (let dir = posix.dirname(fileRel); ; dir = posix.dirname(dir)) {
655
453
  const m = readManifest(dir)
656
- if (m) yield m
657
- if (dir === '.' || dir === '') return
658
- dir = posix.dirname(dir)
454
+ if (m?.package) return m
455
+ if (dir === '.' || dir === '') return null
659
456
  }
660
- }
661
- // The package owning a file: the nearest manifest above it with a [package]; memoized per
662
- // directory (every lookup below starts here, several times per file).
663
- const packageByDir = new Map()
664
- const packageFor = (fileRel) => {
665
- const dir = posix.dirname(fileRel)
666
- return cached(packageByDir, dir, () => {
667
- for (const m of manifestsAbove(dir)) if (m.package) return m
668
- return null
669
- })
670
- }
671
- // The workspace root manifest of package `m` (see rootOf): its own when it is a root, an outer
672
- // one above the bundle root (`outside`) too; `m` itself outside any workspace.
457
+ }, (fileRel) => posix.dirname(fileRel))
673
458
  const rootManifestOf = (m) => (m.isWorkspace ? m : (m.workspaceRoot ?? m))
674
- // The workspace root of the package at `dir` inside the bundle root, or null (outside any, or
675
- // one above the bundle root).
676
- const workspaceFor = (dir) => {
677
- const m = readManifest(dir)
678
- const root = m === null ? null : rootManifestOf(m)
679
- return root?.isWorkspace === true && root.outside === undefined ? root : null
680
- }
681
- // The manifest's lib target root when it is on disk (`[lib] path`, default `src/lib.rs`);
682
- // memoized on the manifest, since it is asked for once per crate reference.
683
- // A vendored package's `[lib] path` may not leave its directory (a published crate's never
684
- // does; one that tries is reaching for the project's files).
685
- const libPath = (m) => {
686
- if (m.libRoot === undefined) {
687
- const rel = normalizeRel(m.dir, m.lib.path ?? 'src/lib.rs')
688
- const inside = rel !== null && (!isVendoredDir(m.dir) || rel.startsWith(`${m.dir}/`))
689
- if (rel !== null && !inside) console.warn(`[loader.cargo] Refusing lib path outside its package: ${m.lib.path} in ${m.dir}`)
690
- m.libRoot = inside && isFile(join(baseDir, rel)) ? rel : null
691
- }
692
- return m.libRoot
693
- }
459
+ // A vendored package's targets may not leave its directory: a published crate's never do.
460
+ const ownTarget = (m, rel) => rel !== null && (!isVendoredDir(m.dir) || rel.startsWith(`${m.dir}/`))
461
+ const libPath = memoized((m) => {
462
+ const rel = normalizeRel(m.dir, m.lib.path ?? 'src/lib.rs')
463
+ const inside = ownTarget(m, rel)
464
+ if (rel !== null && !inside) console.warn(`[loader.cargo] Refusing lib path outside its package: ${m.lib.path} in ${m.dir}`)
465
+ return inside && isFile(join(baseDir, rel)) ? rel : null
466
+ })
694
467
  const libName = (m) => normName(m.lib.name ?? m.package?.name ?? '')
695
- // The package's build script when it is on disk (see buildScriptOf); memoized on the manifest.
696
- const buildScript = (m) => {
697
- if (m.buildScript === undefined) {
698
- const rel = m.package.build === false ? null : normalizeRel(m.dir, m.package.build ?? 'build.rs')
699
- const inside = rel !== null && (!isVendoredDir(m.dir) || rel.startsWith(`${m.dir}/`))
700
- if (rel !== null && !inside && isFile(join(baseDir, rel))) console.warn(`[loader.cargo] Refusing build script outside its package: ${m.package.build} in ${m.dir}`)
701
- m.buildScript = inside && isFile(join(baseDir, rel)) ? rel : null
702
- }
703
- return m.buildScript
704
- }
705
- // Whether `fileRel` belongs to a test or bench target of its package (compiled with `cfg(test)`).
468
+ const buildScript = memoized((m) => {
469
+ const rel = m.package.build === false ? null : normalizeRel(m.dir, m.package.build ?? 'build.rs')
470
+ const inside = ownTarget(m, rel)
471
+ if (rel !== null && !inside && isFile(join(baseDir, rel))) console.warn(`[loader.cargo] Refusing build script outside its package: ${m.package.build} in ${m.dir}`)
472
+ return inside && isFile(join(baseDir, rel)) ? rel : null
473
+ })
706
474
  const isTestTarget = (fileRel) => isTestTargetPath(packageFor(fileRel)?.dir ?? '.', fileRel)
707
- // Whether `fileRel` belongs to a target built with the dev-dependencies (tests, benches,
708
- // examples).
709
- const linksDevDeps = (fileRel) => linksDevDepsPath(packageFor(fileRel)?.dir ?? '.', fileRel)
710
- // The packages an entry is a test, bench or example target of: their dev-dependencies are
711
- // linked (that build is `cargo test`'s). Memoized.
712
- let devRoots = null
713
- const devRootDirs = () => (devRoots ??= new Set(entries.filter((e) => linksDevDeps(e)).map((e) => packageFor(e)?.dir)))
475
+ // An example, unlike a test or bench, isn't compiled with `cfg(test)`, but links the dev-dependencies too.
476
+ const linksDevDeps = (fileRel) => ['tests', 'benches', 'examples'].includes(targetDirOf(packageFor(fileRel)?.dir ?? '.', fileRel))
477
+ const devRootDirs = memoized(() => new Set(entries.filter(linksDevDeps).map((e) => packageFor(e)?.dir)))
714
478
  const version = (m) => m.package.version
715
479
 
716
- // --- dependency resolution
717
-
718
- // The directory cargo is taken to run in for the build (`runDir`): the one of the package the
719
- // first entry belongs to -- `cargo build` there, which finds its workspace root above -- unless
720
- // that entry is a vendored crate's (in the vendor directory the bundle root's configs name),
721
- // whose own config cargo never reads; else the bundle root. What the cargo config sets for the
722
- // build -- the vendor directory, `[patch]`, rustflags -- is what the configs cargo reads when
723
- // run there say (`configs`, see cargoConfigs), and those are the configs a bundle carries.
480
+ // Cargo is taken to run in the first entry's package, unless the entry is a vendored crate's (whose
481
+ // config cargo never reads), else the bundle root. Its configs set the vendor dir, `[patch]` and rustflags.
724
482
  const rootConfigs = cargoConfigs(baseDir, '.')
725
483
  const rootVendorDir = vendorDirOf(baseDir, rootConfigs, { quiet: true })
726
484
  const ownEntry = entries.find((e) => !e.startsWith(`${rootVendorDir}/`))
@@ -733,65 +491,43 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
733
491
  }
734
492
  const runDir = ownEntry === undefined ? '.' : packageDirAbove(posix.dirname(ownEntry))
735
493
  const configs = runDir === '.' ? rootConfigs : cargoConfigs(baseDir, runDir)
736
- // The vendor directory of the build the entries are in, as those configs say.
737
494
  const vendorDir = vendorDirOf(baseDir, configs)
738
- // Whether a package directory is a vendored crate's (a registry crate `cargo vendor` copied in).
739
495
  const isVendoredDir = (dir) => dir !== vendorDir && dir.startsWith(`${vendorDir}/`)
740
- // The vendored crates, `<vendorDir>/<dir>/`, as `[{ version, dir, git }]`, indexed `byName`
741
- // (normalized package name; the dir may hyphenate a snake_case name, and an older duplicate
742
- // version lives in `<name>-<version>/`) and `byLib` (lib name, for the crates whose `[lib] name`
743
- // differs: `md-5` → `md5`). `git`: whether the copy is of a git repository -- its
744
- // `.cargo-checksum.json` has no package checksum, which a registry's always does -- or null
745
- // without that file.
746
- let vendorIndex = null
747
- const vendored = () => {
748
- if (vendorIndex === null) {
749
- vendorIndex = { byName: new Map(), byLib: new Map() }
750
- let dirs = []
751
- try {
752
- dirs = readdirSync(join(baseDir, vendorDir))
753
- } catch { /* no vendor dir */ }
754
- for (const d of dirs) {
755
- if (d.startsWith('.')) continue // a directory source reads none of these
756
- const m = manifestAt(`${vendorDir}/${d}`)
757
- if (!m?.package) continue
758
- const sums = checksumOf(m.dir)
759
- const entry = { version: version(m), dir: m.dir, git: sums?.git ?? null }
760
- for (const [index, key] of [[vendorIndex.byName, normName(m.package.name)], [vendorIndex.byLib, libName(m)]]) {
761
- if (!index.has(key)) index.set(key, [])
762
- index.get(key).push(entry)
763
- }
764
- }
496
+ // `git`: whether the copy is a git checkout's (no package checksum), null without `.cargo-checksum.json`.
497
+ const vendored = memoized(() => {
498
+ const index = { byName: new Map(), byLib: new Map() }
499
+ let dirs = []
500
+ try {
501
+ dirs = readdirSync(join(baseDir, vendorDir))
502
+ } catch { /* no vendor dir */ }
503
+ for (const d of dirs) {
504
+ if (d.startsWith('.')) continue // a directory source reads none of these
505
+ const m = manifestAt(`${vendorDir}/${d}`)
506
+ if (!m?.package) continue
507
+ const entry = { version: version(m), dir: m.dir, git: checksumOf(m.dir)?.git ?? null }
508
+ upsert(index.byName, normName(m.package.name), () => []).push(entry)
509
+ upsert(index.byLib, libName(m), () => []).push(entry)
765
510
  }
766
- return vendorIndex
767
- }
768
- // A vendored package's `.cargo-checksum.json`, parsed, or null when it has none.
769
- const checksums = new Map()
770
- const checksumOf = (dir) => cached(checksums, dir, () => {
511
+ return index
512
+ })
513
+ // `package` the crate's sha256 in hex (none for a git checkout's copy: `git`), `files` each file's.
514
+ const checksumOf = memoized((dir) => {
771
515
  const file = posix.join(dir, '.cargo-checksum.json')
772
516
  const text = readText(diskHost, join(baseDir, file))
773
- let value = null
774
- if (text !== null) {
775
- try {
776
- value = JSON.parse(text)
777
- } catch (err) {
778
- throw new Error(`${file}: not JSON: ${err.message}`, { cause: err })
779
- }
517
+ if (text === null) return null
518
+ let value
519
+ try {
520
+ value = JSON.parse(text)
521
+ } catch (err) {
522
+ throw new Error(`${file}: not JSON: ${err.message}`, { cause: err })
780
523
  }
781
- // A registry's copy has a package checksum; a git checkout's has none. `files`: each file's
782
- // sha256, as `cargo vendor` listed them, path relative to the package.
783
- return value === null ? null : { text, git: (value?.package ?? null) === null, files: isPlainObject(value?.files) ? value.files : {} }
524
+ return value === null ? null : { text, git: (value?.package ?? null) === null, package: typeof value?.package === 'string' ? value.package : null, files: isPlainObject(value?.files) ? value.files : {} }
784
525
  })
785
- // Where `cargo vendor` copied the vendored package at `dir` from, as its `.cargo-checksum.json`
786
- // tells: `registry` or `git` (a git checkout); null without that file, when it could be either.
787
526
  const copySource = (dir) => {
788
527
  const git = checksumOf(dir)?.git
789
528
  return git === undefined ? null : (git ? 'git' : 'registry')
790
529
  }
791
- // Throws when `fileRel`, a file of the vendored package at `dir`, isn't byte for byte (`buf`) the
792
- // file its `.cargo-checksum.json` lists -- edited after `cargo vendor`: cargo refuses to build
793
- // the package, and so the bundle does. A file the list doesn't name, or a package without one,
794
- // passes. Once per file (`verified`): what passed isn't hashed again.
530
+ // cargo refuses to build a file changed since `cargo vendor`; an unlisted file, or a package without the list, passes.
795
531
  const verified = new Set()
796
532
  const checkVendored = (dir, fileRel, buf) => {
797
533
  if (verified.has(fileRel)) return
@@ -802,138 +538,87 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
802
538
  }
803
539
  verified.add(fileRel)
804
540
  }
805
- // The package the build is of: the first entry's package that isn't vendored -- the one cargo is
806
- // run in (runDir), taken now that the vendor directory is known; null when no entry has one.
807
- // Memoized.
808
- let buildPkg
809
- const buildPackage = () => {
810
- if (buildPkg === undefined) buildPkg = entries.map(packageFor).find((m) => m && !isVendoredDir(m.dir)) ?? null
811
- return buildPkg
541
+ // A package checksum other than the one Cargo.lock locks is a copy of another crate, which cargo refuses to build.
542
+ const lockChecked = new Set()
543
+ const checkLocked = (m) => {
544
+ if (lockChecked.has(m.dir)) return
545
+ lockChecked.add(m.dir)
546
+ const hex = checksumOf(m.dir)?.package
547
+ const lk = hex ? lockfile() : null
548
+ const locked = lk === null ? [] : lockKeysOf(lk, m).map((key) => lk.lock.packages[key].checksum).filter(Boolean)
549
+ if (locked.length > 0 && !locked.includes(hex)) {
550
+ throw new Error(`${m.dir}/.cargo-checksum.json: the package checksum of ${m.package.name} ${version(m)}, ${hex}, isn't the one ${lk.file} locks (${locked.join(', ')}): vendor it again`)
551
+ }
812
552
  }
813
- // The workspace root of the build: its package's (rootManifestOf), inside the bundle root or
814
- // above it (`outside`: read, never bundled), the package itself outside any workspace; the bundle
815
- // root's manifest when no entry has a package. Its Cargo.lock is the build's, and its resolver
816
- // and `[patch]` apply to every package of the build.
553
+ const buildPackage = memoized(() => entries.map(packageFor).find((m) => m && !isVendoredDir(m.dir)) ?? null)
554
+ // Its Cargo.lock, resolver and `[patch]` are the build's.
817
555
  const buildWorkspaceRoot = () => {
818
556
  const pkg = buildPackage()
819
557
  return pkg === null ? readManifest('.') : rootManifestOf(pkg)
820
558
  }
821
- // The build's Cargo.lock, project-relative: beside its workspace root, as cargo finds it -- a
822
- // vendored crate's own published lock plays no part; null when that root lies above the bundle
823
- // root (its lockfile is cargo's, never read, and one beside the package isn't the build's).
559
+ // Null when the workspace root lies above the bundle root: its lockfile is cargo's, never read.
824
560
  const buildLockPath = () => {
825
561
  const root = buildWorkspaceRoot()
826
562
  return root?.outside === undefined ? posix.join(root?.dir ?? '.', 'Cargo.lock') : null
827
563
  }
828
- // The build's Cargo.lock (buildLockPath), read by @preventive/lockfile (`version = 3` or `4`; an
829
- // older one, or a lock that isn't what cargo writes or could be read two ways, stops the build),
830
- // as `{ file, text, lock, byId }` (`byId`: `name version` → the keys of that version's
831
- // packages); null when there is none in the bundle root.
832
- let lock
833
- const lockfile = () => {
834
- if (lock === undefined) {
835
- const file = buildLockPath()
836
- const text = file === null ? null : readText(diskHost, join(baseDir, file))
837
- lock = null
838
- if (text !== null) {
839
- const parsed = readNamed(file, () => parseCargoLock(text))
840
- const byId = new Map()
841
- for (const [key, p] of Object.entries(parsed.packages)) {
842
- const id = `${normName(p.name)} ${p.version}`
843
- if (!byId.has(id)) byId.set(id, [])
844
- byId.get(id).push(key)
845
- }
846
- lock = { file, lock: parsed, byId }
847
- }
848
- }
849
- return lock
850
- }
851
- // `--cargo`: the graph and features as cargo resolved them, with registry packages it read from
852
- // the registry cache matched to their `vendor/` copy by name + version.
564
+ const lockfile = memoized(() => {
565
+ const file = buildLockPath()
566
+ const text = file === null ? null : readText(diskHost, join(baseDir, file))
567
+ if (text === null) return null
568
+ const lock = readNamed(file, () => parseCargoLock(text))
569
+ const byId = new Map()
570
+ for (const [key, p] of Object.entries(lock.packages)) upsert(byId, `${normName(p.name)} ${p.version}`, () => []).push(key)
571
+ return { file, lock, byId }
572
+ })
853
573
  const metadata = cargo
854
574
  ? resolutionFromMetadata(runCargoMetadata(join(baseDir, runDir), { features, noDefaultFeatures, allFeatures, platform: targetInfo?.triple ?? null }), baseDir, {
855
575
  locate: (name, ver) => (typeof name === 'string' ? vendored().byName.get(normName(name))?.find((c) => c.version === ver)?.dir ?? null : null),
856
576
  })
857
577
  : null
858
- // Where the build takes its `[patch]` tables from, in the order they apply: the cargo configs'
859
- // (`configs`, nearest first), as @preventive/lockfile reads them, then the workspace root
860
- // manifest's (buildWorkspaceRoot), as `{ patch, at, from }`: `at(path)` the directory a patch's
861
- // path names, project-relative (null outside the bundle root) -- relative to the directory
862
- // holding a config's `.cargo`, or to the manifest's -- `from` the file. Throws a TomlError or
863
- // LockfileError naming a config.
864
- let patchMemo = null
865
- const patchSources = () => {
866
- if (patchMemo === null) {
867
- const root = buildWorkspaceRoot()
868
- patchMemo = [
869
- ...configs.map((c) => ({ patch: readNamed(c.file, () => parseCargoConfig([c.text])).patch, at: (path) => projectRel(baseAbs, c.abs, path), from: c.file })),
870
- ...(root ? [{ patch: root.cargo.patch, at: (path) => manifestPath(root, path), from: root.file }] : []),
871
- ]
872
- }
873
- return patchMemo
874
- }
875
- // The `[patch]` of crate `crate` for what request `r` comes from, as `{ spec, dir, from }`, the
876
- // first patchSources has -- `spec` as @preventive/lockfile reads it, `dir` the patch's directory
877
- // for a path (null outside the bundle root), `from` the file saying so. Undefined when nothing
878
- // patches it.
578
+ // In the order they apply: the cargo configs' (nearest first), then the workspace root manifest's.
579
+ const patchSources = memoized(() => {
580
+ const root = buildWorkspaceRoot()
581
+ return [
582
+ ...configs.map((c) => ({ patch: readNamed(c.file, () => parseCargoConfig([c.text])).patch, at: (path) => projectRel(baseAbs, c.abs, path), from: c.file })),
583
+ ...(root ? [{ patch: root.cargo.patch, at: (path) => manifestPath(root, path), from: root.file }] : []),
584
+ ]
585
+ })
879
586
  const patchFor = (crate, r) => {
880
587
  for (const { patch, at, from } of patchSources()) {
881
588
  for (const [source, specs] of Object.entries(patch)) {
882
589
  if (!patchesSource(source, r)) continue
883
590
  for (const [name, spec] of Object.entries(specs)) {
884
- if (normName(name) !== crate) continue
885
- return { spec, dir: spec.source.type === 'path' ? at(spec.source.path) : null, from }
591
+ if (normName(name) === crate) return { spec, dir: spec.source.type === 'path' ? at(spec.source.path) : null, from }
886
592
  }
887
593
  }
888
594
  }
889
- return undefined
890
595
  }
891
- // Whether a `[patch.<source>]` table patches what request `r` comes from: crates.io's
892
- // (`crates-io`, or its index URL) for a crates.io dependency, the registry's name or index for
893
- // another, the repository for a git dependency -- URLs compared as cargo canonicalizes them (no
894
- // trailing `/` or `.git`, the scheme's and host's case aside).
895
596
  const patchesSource = (source, r) => {
896
597
  if (r.source === 'git') return r.origin !== null && canonicalUrl(source) === canonicalUrl(r.origin)
897
598
  if (r.source !== 'registry') return false
898
599
  if (r.origin === null) return source === 'crates-io' || CRATES_IO_INDEXES.has(canonicalUrl(source))
899
600
  return source === r.origin || canonicalUrl(source) === canonicalUrl(r.origin)
900
601
  }
901
- // Where a lockfile's package comes from: `path`, `git` or `registry` (sparse or not).
902
602
  const sourceKind = (source) => (source === undefined ? 'path' : (source.startsWith('git+') ? 'git' : 'registry'))
903
- // The keys of the build's lockfile that are package `m`: its path package, or for a vendored copy
904
- // the locked package of its name and version from where the copy came from (a git checkout or a
905
- // registry, see vendored).
603
+ // For a vendored copy, the locked package of its name and version from where the copy came from.
906
604
  const lockKeysOf = (lk, m) => {
907
605
  const keys = lk.byId.get(`${normName(m.package.name)} ${version(m)}`) ?? []
908
606
  if (!isVendoredDir(m.dir)) return keys.filter((k) => lk.lock.packages[k].source === undefined)
909
607
  const kind = copySource(m.dir)
910
608
  return keys.filter((k) => lk.lock.packages[k].source !== undefined && (kind === null || sourceKind(lk.lock.packages[k].source) === kind))
911
609
  }
912
- // Dependency → package, memoized per (package, request): the fixed-point loop asks many times.
913
- const depTargets = new Map()
914
- // The in-tree package a dependency of `m` resolves to through one of its tables (`request`): a
915
- // `path` dep, else a `[patch]` path override (patchFor) whose version satisfies the requirement,
916
- // else the vendored crate of that name from where the dependency says (a git dependency, or one a
917
- // git `[patch]` replaces, takes a copy of a git checkout; any other a registry's) -- the version
918
- // Cargo.lock records for `m` from that source when it satisfies the requirement, else the one
919
- // vendored version that does. A package can depend on two versions of one crate (`borsh = "1"`
920
- // beside `borsh0-9 = { package = "borsh", version = "0.9" }`, or one per table): the lock then
921
- // lists both under it, and the requirement tells which is which. Null when it isn't in-tree -- a
922
- // path (or patch) outside the bundle root, or no vendored copy -- and, warned, when the vendored
923
- // copies don't settle it: the locked version isn't among them, none satisfies the requirement,
924
- // or several do and no lock chooses. Cargo would build none of those from what the bundle holds,
925
- // so none is guessed.
926
- // What it warns of is said once, when it is first asked for unless `quiet`, else when
927
- // warnDep asks: the replay lays out every declaration, and warns only of those the build links.
610
+ // A path, a `[patch]` path whose version fits, else the vendored copy Cargo.lock pins for `m` or the one
611
+ // that fits. Null when it isn't in-tree, and warned when the copies don't settle it: none is guessed.
612
+ const depTargets = new Map() // the fixed-point loop asks many times
928
613
  const resolveDep = (m, dep, request, { quiet = false } = {}) => {
929
- const byRequest = cached(depTargets, m.dir, () => new Map())
930
- const found = cached(byRequest, request, () => {
614
+ const found = upsert(nestedMap(depTargets, m.dir), request, () => {
931
615
  const warnings = []
932
616
  return { t: resolveDepUncached(m, dep, request, (w) => warnings.push(w)), warnings }
933
617
  })
934
618
  if (!quiet) warnDep(m, request)
935
619
  return found.t
936
620
  }
621
+ // Said once: the replay warns only of the declarations the build links.
937
622
  const warnDep = (m, request) => {
938
623
  for (const w of depTargets.get(m.dir)?.get(request)?.warnings.splice(0) ?? []) console.warn(w)
939
624
  }
@@ -942,7 +627,6 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
942
627
  const t = dir === null ? null : readManifest(dir)
943
628
  return t?.package ? t : null
944
629
  }
945
- // cargo metadata knows exactly which package each dependency edge points at.
946
630
  const known = metadata?.deps.get(m.dir)?.get(dep.key)
947
631
  if (known !== undefined) return asPackage(known)
948
632
  const who = `${m.package.name} ${version(m)}`
@@ -971,20 +655,20 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
971
655
  } else if (patch?.spec.source.type === 'git') {
972
656
  kind = 'git'
973
657
  }
974
- // A copy of where the dependency comes from (a copy without `.cargo-checksum.json` could be either).
658
+ // A copy without `.cargo-checksum.json` could be either.
975
659
  const candidates = (vendored().byName.get(crate) ?? []).filter((c) => c.git === null || c.git === (kind === 'git'))
976
660
  if (candidates.length === 0) return null
977
661
  const vendoredList = candidates.map((c) => c.version).toSorted((a, b) => b.localeCompare(a, 'en', { numeric: true })).join(', ')
978
662
  const lk = lockfile()
979
663
  if (lk) {
664
+ // A package may depend on two versions of one crate: the requirement tells which pin is this one.
980
665
  const pins = lockKeysOf(lk, m)
981
666
  .flatMap((k) => lk.lock.packages[k].dependencies)
982
667
  .map((k) => lk.lock.packages[k])
983
668
  .filter((p) => normName(p.name) === crate && sourceKind(p.source) === kind)
984
669
  .map((p) => p.version)
985
670
  const want = pins.find(fits) ?? null
986
- // A lock whose pin the requirement no longer allows is out of date: cargo would resolve
987
- // again, so the requirement decides.
671
+ // A pin the requirement no longer allows: cargo would resolve again, so the requirement decides.
988
672
  if (want === null && pins.length > 0) warn(`[loader.cargo] ${lk.file} pins ${who} to ${crate} ${pins.join(', ')}, which ${req} doesn't allow: the lock is out of date`)
989
673
  if (want !== null) {
990
674
  const hit = candidates.find((c) => c.version === want)
@@ -1000,61 +684,32 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1000
684
  return null
1001
685
  }
1002
686
 
1003
- // --- feature resolution
1004
-
1005
- // Cargo's feature resolver: v2 (edition 2021, or `resolver = "2"`) leaves dev-dependencies out of
1006
- // a normal build's unification, resolves what is built for the host apart from what is built for
1007
- // the target, and ignores the tables of platforms not being built; v1 unifies them all. v3
1008
- // (edition 2024, or `resolver = "3"`) resolves features as v2 does, and picks versions by
1009
- // `rust-version` too, which the lockfile and the vendored copies have decided here. It is the
1010
- // workspace's setting: the build's workspace root's (buildWorkspaceRoot) `resolver`, else its
1011
- // edition's, as linkCargo gives it -- never that of a vendored crate an entry is in, where cargo
1012
- // isn't run.
1013
- let resolverMemo = null
1014
- const resolverVersion = () => {
1015
- if (resolverMemo === null) {
1016
- const root = buildWorkspaceRoot()
1017
- const edition = Number(root?.package?.edition ?? 0)
1018
- resolverMemo = root?.resolver ?? (edition >= 2024 ? 3 : (edition >= 2021 ? 2 : 1))
1019
- }
1020
- return resolverMemo
1021
- }
1022
- // The feature context a unit's code sees (resolver 2 keeps the host's apart; resolver 1 has one).
1023
- const featureCtx = (c) => (resolverVersion() === 1 ? 'target' : c)
1024
- const isProcMacroPkg = (m) => m?.lib.procMacro === true
1025
- // The platform a context compiles for, as far as the loader knows it: the target's triple and
1026
- // cfgs when `target` was given; the host's only when the target is the host (`host`), since the
1027
- // machine that builds need not be the one that bundles.
687
+ const resolverVersion = memoized(() => {
688
+ const root = buildWorkspaceRoot()
689
+ const edition = Number(root?.package?.edition ?? 0)
690
+ return root?.resolver ?? (edition >= 2024 ? 3 : (edition >= 2021 ? 2 : 1))
691
+ })
692
+ // The host's only when the target is the host: the machine that builds need not be the one that bundles.
1028
693
  const platformInfo = (platform) => (platform === 'target' ? targetInfo : hostInfo)
1029
- // Whether a table for platform `spec` (a `cfg(…)` or a triple; null or undefined for none) is
1030
- // one for `platform`: `yes`, `no`, or `maybe` when its cfgs aren't known or don't decide it.
694
+ // `maybe` when the platform's cfgs aren't known or don't decide it.
1031
695
  const tableOn = (spec, platform) => {
1032
696
  if (spec === null || spec === undefined) return 'yes'
1033
697
  const info = platformInfo(platform)
1034
698
  if (info === null) return 'maybe'
1035
- const cfg = /^cfg\((.*)\)$/u.exec(spec)
1036
- const holds = cfg ? evalCfg(cfg[1], { target: info.cfgs }) : spec === info.triple
699
+ const cfg = cfgPredicate(spec)
700
+ const holds = cfg === undefined ? spec === info.triple : evalCfg(cfg, { target: info.cfgs })
1037
701
  return holds === true ? 'yes' : (holds === false ? 'no' : 'maybe')
1038
702
  }
1039
- // A package in a context, as the resolutions key it: resolver 1's one context is `target`'s.
1040
- const nodeKey = (c, dir) => `${featureCtx(c)}\0${dir}`
703
+ const nodeKey = (c, dir) => `${resolverVersion() === 1 ? 'target' : c}\0${dir}`
1041
704
 
1042
- // Both feature resolutions of `graph` (linkCargo's, or the replay's) by cargo's resolver, for the
1043
- // build of `packages`, members of it, per (context, dir) as nodeKey keys them -- `dirOf(key)` the
1044
- // dir of a package key, undefined for none -- resolver 1's one set under `target`, the normal one
1045
- // where there is one: `sure` with the features on for certain, `all` with those that may be, and
1046
- // `result`, the resolver's own answer for `all`. Cargo's resolver takes the platforms it builds
1047
- // for as known, and the loader may not know them: it runs against stand-ins (standInPlatform), a
1048
- // target-specific table the loader can't decide on one -- a platform it doesn't know, a cfg it
1049
- // can't decide there (`cfg(loom)`, which rustflags may set) -- off for `sure` and on for `all`,
1050
- // the rest for cargo to decide as written. What cargo's resolver refuses -- a feature asked of a
1051
- // package that hasn't it -- stops the build, naming `file`.
705
+ // Both feature resolutions by cargo's resolver, by nodeKey, run against stand-in platforms: a table
706
+ // the loader can't decide is off for `sure` and on for `all`; `result` is the resolver's own for `all`.
1052
707
  const resolveGraph = (graph, packages, file, dirOf) => {
1053
708
  const build = { packages, features, allFeatures, noDefaultFeatures, dev: entries.some((e) => linksDevDeps(e)), host: standInPlatform(MARK_HOST, hostInfo), targets: [standInPlatform(MARK_TARGET, targetInfo)] }
1054
709
  let undecided = false
1055
710
  const decided = (on) => retarget(graph, (spec) => {
1056
711
  const at = (platform) => {
1057
- if (tableOn(spec, platform) !== 'maybe') return /^cfg\((.*)\)$/su.exec(spec)?.[1] ?? `${MARK_NAME} = "${spec}"`
712
+ if (tableOn(spec, platform) !== 'maybe') return cfgPredicate(spec) ?? `${MARK_NAME} = "${spec}"`
1058
713
  undecided = true
1059
714
  return String(on)
1060
715
  }
@@ -1076,21 +731,8 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1076
731
  return { sure: byNode(sure), all: byNode(all), result: all }
1077
732
  }
1078
733
 
1079
- // --- the replay: cargo's feature resolver, by @preventive/lockfile, over the manifests
1080
-
1081
- // The graph cargo's feature resolver takes, as linkCargo gives one, laid out from the manifests
1082
- // where the lockfile's can't be: each package in-tree the entries' packages (`roots`) reach, by
1083
- // its dir, each of its declarations resolved as resolveDep resolves it -- a path, a `[patch]`, the
1084
- // vendored copy the lockfile or the requirement picks -- but a dependency's own dev-dependencies,
1085
- // which no build of the entries has. A declaration nothing in-tree answers resolves to a stand-in
1086
- // of its own, which depends on nothing and has every feature its dependent may ask of it: the
1087
- // declaration's, `default`, and what a `name/feature` or `name?/feature` of the package's
1088
- // features, or of `--cargo-features` for a root, names. So does, unresolved (`unbuilt`), a
1089
- // dev-dependency of a root that no entry is a test, bench or example of, under resolver 2: cargo's
1090
- // resolver takes the dev targets of every member as built or none, and the entries build only
1091
- // theirs. The members are the roots, and there is no root package: `--cargo-features` goes to each
1092
- // that has it. `edges`: each declaration's resolved key, with its package and request (`m`, `d`,
1093
- // `request`), and whether it is a stand-in.
734
+ // A declaration nothing in-tree answers, or under resolver 2 a root's dev-dependency no entry builds
735
+ // (`unbuilt`), gets a stand-in with any feature it is asked.
1094
736
  const replayGraph = (roots) => {
1095
737
  const packages = Object.create(null)
1096
738
  const edges = []
@@ -1103,7 +745,7 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1103
745
  const dependencies = pkg.dependencies.map((d, index) => {
1104
746
  if (d.kind === 'dev' && !rootDirs.has(m.dir)) return { ...d, resolved: undefined, active: false }
1105
747
  const dep = m.deps.get(normName(d.name))
1106
- const request = dep.kinds.get(d.target === undefined ? d.kind : `${d.kind}@${d.target}`)
748
+ const request = dep.kinds.get(requestKey(d))
1107
749
  const unbuilt = d.kind === 'dev' && unbuiltDev(m)
1108
750
  const t = unbuilt ? null : resolveDep(m, dep, request, { quiet: true })
1109
751
  if (t !== null) queue.push(t)
@@ -1119,17 +761,13 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1119
761
  const named = DEP_FEATURE_RE.exec(value)
1120
762
  if (named?.[1] === d.name) asked.add(named[3])
1121
763
  }
1122
- const manifest = { name: d.package, features: Object.fromEntries([...asked].map((f) => [f, []])), dependencies: [], procMacro: false, procMacroTarget: false }
1123
- Object.setPrototypeOf(manifest.features, null)
764
+ const manifest = { name: d.package, features: fromEntries([...asked].map((f) => [f, []])), dependencies: [], procMacro: false, procMacroTarget: false }
1124
765
  packages[key] = { name: d.package, version: '0.0.0', source: undefined, checksum: undefined, manifest, dependencies: [] }
1125
766
  }
1126
767
  return { graph: { resolver: resolverVersion(), root: undefined, members: [...rootDirs], packages }, edges }
1127
768
  }
1128
769
 
1129
- // The replay's resolution, as resolveGraph gives it, and the dependencies the build links that
1130
- // nothing in-tree answers -- a stand-in it reaches -- as `dir key` → `{ dir, key, name, kinds }`,
1131
- // the kinds of their tables (see lackingDependencies). What resolveDep warned of, it says now of
1132
- // the declarations whose package the build reaches.
770
+ // What resolveDep warned of, it says now of the declarations whose package the build reaches.
1133
771
  const replay = () => {
1134
772
  const roots = [...new Set(entries.map(packageFor).filter(Boolean))]
1135
773
  if (roots.length === 0) return { resolved: { sure: new Map(), all: new Map() }, lacking: new Map() }
@@ -1141,18 +779,11 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1141
779
  if (unbuilt || !(key in resolved.result)) continue
1142
780
  warnDep(m, request)
1143
781
  if (!standIn) continue
1144
- const id = `${m.dir}\0${normName(d.name)}`
1145
- if (!lacking.has(id)) lacking.set(id, { dir: m.dir, key: normName(d.name), name: d.name, kinds: new Set() })
1146
- lacking.get(id).kinds.add(d.kind)
782
+ upsert(lacking, `${m.dir}\0${normName(d.name)}`, () => ({ dir: m.dir, key: normName(d.name), name: d.name, kinds: new Set() })).kinds.add(d.kind)
1147
783
  }
1148
784
  return { resolved, lacking }
1149
785
  }
1150
786
 
1151
- // --- the exact resolution: cargo's resolver, by @preventive/lockfile
1152
-
1153
- // The directories a workspace `members` pattern names, project-relative (glob's syntax, as cargo
1154
- // takes it: `*`, `?` and `[…]` within a segment, `**` for any depth); null when it leaves the
1155
- // bundle root.
1156
787
  const subdirs = (dir) => {
1157
788
  try {
1158
789
  return readdirSync(join(baseDir, dir), { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => (dir === '.' ? e.name : `${dir}/${e.name}`))
@@ -1182,9 +813,6 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1182
813
  }
1183
814
  return dirs
1184
815
  }
1185
- // The workspace's members, project-relative, as cargo finds them: the root package, the
1186
- // packages its `members` patterns name, and the path dependencies of members inside the root's
1187
- // directory, less what `exclude` names; null when a pattern leaves the bundle root.
1188
816
  const membersOf = (root) => {
1189
817
  const ws = root.cargo.workspace
1190
818
  if (ws === undefined) return [root.dir]
@@ -1199,40 +827,19 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1199
827
  }
1200
828
  // Set iteration is live: a path dependency added is walked in turn.
1201
829
  for (const dir of out) {
1202
- for (const d of readManifest(dir).deps.values()) {
1203
- for (const r of d.kinds.values()) {
1204
- const sub = r.dir
1205
- if (sub !== null && inRoot(sub) && !isExcluded(sub) && readManifest(sub)?.package) out.add(sub)
1206
- }
830
+ for (const { dir: sub } of readManifest(dir).deps.values().flatMap((d) => d.kinds.values())) {
831
+ if (sub !== null && inRoot(sub) && !isExcluded(sub) && readManifest(sub)?.package) out.add(sub)
1207
832
  }
1208
833
  }
1209
834
  return [...out]
1210
835
  }
1211
- // The build as cargo resolves it, where the loader holds all that takes -- the build's lockfile
1212
- // and target, a manifest for every package the lockfile has (each path package inside the
1213
- // bundle root, every other one vendored, `.cargo-checksum.json` and all) and entries whose
1214
- // packages are workspace members: @preventive/lockfile lays the lockfile's graph over the
1215
- // manifests (linkCargo) and turns on the features `cargo build -p <the entries' packages>` does
1216
- // (resolveCargoFeatures), cargo's rules throughout -- each table's own source, a [patch] from the
1217
- // root manifest or the cargo config, proc-macros and build-dependencies built for the host, the
1218
- // command line's features handed out as cargo hands them out. What either refuses -- a lockfile
1219
- // out of date with the manifests, a vendored copy whose checksum isn't the lockfile's, a feature
1220
- // asked of a package that hasn't it -- stops the build. A table the loader can't decide on a
1221
- // platform -- the host's, where the target isn't `host` -- is resolved both ways (resolveGraph).
1222
- // `{ graph, dirOf, keyOf, resolved }` -- package key ↔ dir, and the features per (context, dir)
1223
- // as resolveGraph gives them -- or null when something it takes is missing, for the replay to
1224
- // decide: no lockfile, no target, a package not vendored, a path outside the bundle root.
1225
- let exactMemo
1226
- let exactWhy = null // why there is none, for the replay to say
1227
- const exact = () => {
1228
- if (exactMemo === undefined) exactMemo = exactUncached()
1229
- return exactMemo
1230
- }
836
+ // The build as cargo resolves it, where the loader holds all it takes; else null, `exactWhy` saying what's missing.
837
+ let exactWhy = null
1231
838
  const notExact = (why) => {
1232
839
  exactWhy = why
1233
840
  return null
1234
841
  }
1235
- const exactUncached = () => {
842
+ const exact = memoized(() => {
1236
843
  if (metadata) return null
1237
844
  if (targetInfo === null) return notExact('no --cargo-target')
1238
845
  const lockPath = buildLockPath()
@@ -1243,18 +850,15 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1243
850
  if (root === null) return notExact('no package owns the entries')
1244
851
  const memberDirs = membersOf(root)
1245
852
  if (memberDirs === null) return notExact(`a members pattern of ${root.file} leaves the bundle root`)
1246
- // The path packages: the members, the path dependencies of each, the path [patch]es.
1247
- const keyOf = new Map() // dir -> package key
1248
- const dirOf = new Map() // package key -> dir
853
+ const keyOf = new Map()
854
+ const dirOf = new Map()
1249
855
  const queue = [...memberDirs]
1250
856
  for (const { patch, at, from } of patchSources()) {
1251
- for (const specs of Object.values(patch)) {
1252
- for (const spec of Object.values(specs)) {
1253
- if (spec.source.type !== 'path') continue
1254
- const dir = at(spec.source.path)
1255
- if (dir === null) return notExact(`${from} patches with a path outside the bundle root`)
1256
- queue.push(dir)
1257
- }
857
+ for (const spec of Object.values(patch).flatMap((specs) => Object.values(specs))) {
858
+ if (spec.source.type !== 'path') continue
859
+ const dir = at(spec.source.path)
860
+ if (dir === null) return notExact(`${from} patches with a path outside the bundle root`)
861
+ queue.push(dir)
1258
862
  }
1259
863
  }
1260
864
  for (const dir of queue) {
@@ -1264,16 +868,13 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1264
868
  const key = `${m.package.name} ${m.package.version}`
1265
869
  keyOf.set(dir, key)
1266
870
  dirOf.set(key, dir)
1267
- for (const d of m.deps.values()) {
1268
- for (const r of d.kinds.values()) {
1269
- if (r.path === null) continue
1270
- if (r.dir === null) return notExact(`${m.package.name}'s path dependency ${r.path} lies outside the bundle root`)
1271
- queue.push(r.dir)
1272
- }
871
+ for (const r of m.deps.values().flatMap((d) => d.kinds.values())) {
872
+ if (r.path === null) continue
873
+ if (r.dir === null) return notExact(`${m.package.name}'s path dependency ${r.path} lies outside the bundle root`)
874
+ queue.push(r.dir)
1273
875
  }
1274
876
  }
1275
- // The vendor directory as a directory source reads it, and every package of the lockfile there
1276
- // (a copy the lockfile doesn't list needs no checksums: cargo never reads it).
877
+ // A copy the lockfile doesn't list needs no checksums: cargo never reads it.
1277
878
  const vendor = Object.create(null)
1278
879
  const held = new Map() // `name version` -> whether its copy has its checksums
1279
880
  for (const sub of subdirs(vendorDir)) {
@@ -1286,9 +887,10 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1286
887
  if (sums !== null) vendor[name] = { manifest: tableOf(sub).text, checksum: sums.text }
1287
888
  }
1288
889
  for (const [key, p] of Object.entries(lk.lock.packages)) {
1289
- if (p.source === undefined && !dirOf.has(key)) return notExact(`${lk.file} locks the path package ${p.name} ${p.version}, which isn't in-tree`)
1290
- if (p.source !== undefined && !held.has(`${p.name} ${p.version}`)) return notExact(`${p.name} ${p.version} is locked but not vendored`)
1291
- if (p.source !== undefined && !held.get(`${p.name} ${p.version}`)) return notExact(`the vendored copy of ${p.name} ${p.version} has no .cargo-checksum.json`)
890
+ const id = `${p.name} ${p.version}`
891
+ if (p.source === undefined && !dirOf.has(key)) return notExact(`${lk.file} locks the path package ${id}, which isn't in-tree`)
892
+ if (p.source !== undefined && !held.has(id)) return notExact(`${id} is locked but not vendored`)
893
+ if (p.source !== undefined && !held.get(id)) return notExact(`the vendored copy of ${id} has no .cargo-checksum.json`)
1292
894
  }
1293
895
  const copies = readNamed(lk.file, () => readCargoVendor(lk.lock, vendor))
1294
896
  const manifestsByKey = Object.create(null)
@@ -1306,20 +908,13 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1306
908
  const config = readNamed(configs[0]?.file ?? null, () => parseCargoConfig(configs.map((c) => c.text)))
1307
909
  const graph = readNamed(lk.file, () => linkCargo(lk.lock, manifestsByKey, { workspace: root.cargo, members: memberKeys, config }))
1308
910
  return { graph, dirOf, keyOf, resolved: resolveGraph(graph, entryKeys, root.file, (key) => dirOf.get(key)) }
1309
- }
911
+ })
1310
912
 
1311
- // Both resolutions, per (context, package dir): `sure` without the undecided tables, `all` with
1312
- // them -- the exact resolution's where there is one, the replay's otherwise. `--cargo`: cargo
1313
- // metadata gives one feature set per package, the union over everything cargo would build for
1314
- // the workspace (dev and build dependencies, every platform), so a feature in it is on only maybe
1315
- // in either context -- code a `cfg(not(feature = "x"))` keeps in some build is never dropped --
1316
- // and one outside it is off. `lacking` (the replay's): the dependencies no package in-tree
1317
- // answers, `dir key` → `{ dir, key, name, kinds }` -- the kinds of its active tables -- as
1318
- // `cargo metadata`'s (see lackingDependencies).
1319
913
  let resolved = null
1320
914
  let lacking = null
1321
915
  const ensureResolved = () => {
1322
916
  if (resolved !== null) return resolved
917
+ // cargo metadata's is a per-package union over every build: each feature in it is only maybe on.
1323
918
  if (metadata) {
1324
919
  const byNode = new Map([...metadata.enabled].flatMap(([dir, set]) => [[nodeKey('target', dir), set], [nodeKey('host', dir), set]]))
1325
920
  resolved = { sure: new Map(), all: byNode }
@@ -1329,23 +924,18 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1329
924
  }
1330
925
  return resolved
1331
926
  }
1332
- // Per node, the features on only maybe: in `all`, not in `sure` (one object per node).
1333
- const maybeByNode = new Map()
1334
- const maybeOf = (node) => cached(maybeByNode, node, () => {
927
+ const maybeOf = memoized((node) => {
1335
928
  const { sure, all } = ensureResolved()
1336
929
  const on = sure.get(node)
1337
930
  const maybe = new Set([...(all.get(node) ?? [])].filter((f) => !on?.has(f)))
1338
931
  return maybe.size === 0 ? null : maybe
1339
932
  })
1340
- // A package in the `all` resolution but not the `sure` one is built only maybe: nothing of its
1341
- // is on for certain.
933
+ // A package in the `all` resolution but not the `sure` one is built only maybe: nothing of its is on for certain.
1342
934
  const NO_FEATURES = new Set()
1343
935
 
1344
- // --- cfgs a build may set
1345
936
  let rustflagCfgs = null
1346
937
  const cfgsSetMemo = new Map()
1347
- // A crate root's text -- a build script's, a lib's -- and that of the modules it declares (`mod
1348
- // probe;`, beside it), a few levels down: where its `cargo:rustc-cfg=` lines are.
938
+ // A crate root's text and that of the modules it declares, a few levels down.
1349
939
  const crateTexts = (root) => {
1350
940
  const texts = []
1351
941
  const queue = [[root, 0]]
@@ -1367,13 +957,9 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1367
957
  return texts
1368
958
  }
1369
959
 
1370
- // What the build script of package `m` may print through the crates it calls (cfgsPrinted of
1371
- // their libs: cfg_aliases' `cfg_aliases!` prints the names its input gives) -- its
1372
- // build-dependencies for the host, and what they depend on in turn. One the bundle root lacks
1373
- // may print any for all the loader knows, which needs no lib read. Asked once per package
1374
- // (cfgsSetFor).
960
+ // What a build script may print through the crates it calls, as cfg_aliases' `cfg_aliases!` does.
1375
961
  const helpersPrinted = (m) => {
1376
- const crates = new Map() // dir -> manifest
962
+ const crates = new Map()
1377
963
  if (linksLacking(m, 'build', crates)) return { names: new Set(), any: true }
1378
964
  const names = new Set()
1379
965
  for (const t of crates.values()) {
@@ -1383,9 +969,6 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1383
969
  }
1384
970
  return { names, any: false }
1385
971
  }
1386
- // Whether package `p` links, through its `kind` dependencies for the host and what they depend
1387
- // on in turn, a crate the bundle root lacks; those it links in-tree go into `crates` (dir →
1388
- // manifest).
1389
972
  const linksLacking = (p, kind, crates) => [...p.deps.values()].some((d) => [...d.kinds.values()].some((r) => {
1390
973
  if (r.kind !== kind || tableOn(r.target, 'host') === 'no') return false
1391
974
  const t = resolveDep(p, d, r)
@@ -1394,44 +977,19 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1394
977
  crates.set(t.dir, t)
1395
978
  return linksLacking(t, 'normal', crates)
1396
979
  }))
1397
- // What package `t`'s lib may print for a build script calling it (cfgsPrinted); memoized per
1398
- // package.
1399
- const libPrints = new Map()
1400
- const libPrinted = (t) => cached(libPrints, t.dir, () => {
980
+ const libPrinted = memoized((t) => {
1401
981
  const lib = libPath(t)
1402
982
  return lib === null ? NO_CFGS_SET : cfgsPrinted(crateTexts(lib))
1403
- })
983
+ }, (t) => t.dir)
1404
984
 
1405
- // The in-tree crate roots a name resolves to from package `m` (null: no owning package), leaving
1406
- // out `m`'s own lib (which depends on the asking file), as `[{ file, key }]`: the package its
1407
- // dependency of that name resolves to (path dep, `[patch]`, or the vendored version Cargo.lock
1408
- // says); a dependency whose lib is named that (`md-5` is used as `md5`); or -- for a file no
1409
- // manifest claims -- the one vendored crate of that lib or package name. A package's own name for
1410
- // a crate is its manifest's word: a declared dependency that doesn't resolve in-tree (a path
1411
- // outside the bundle root, a version no vendored copy has) never falls back to some vendored copy
1412
- // of that name, and a name it doesn't declare is no crate of its. Which of the dependency's
1413
- // tables count is the asking code's (`roles`, one per crate root the file is compiled in): a build
1414
- // script's are the `[build-dependencies]`, a test, bench or example target's the
1415
- // `[dependencies]` and `[dev-dependencies]`, other code's the `[dependencies]` (any table when
1416
- // none of those has it) -- each only where its platform may be one the code is compiled for
1417
- // (`platforms`, the file's units'; a build script's the host): a table the target's cfgs rule out
1418
- // is no dependency of a build for it, under either resolver. Tables that may each apply -- one
1419
- // per platform when no target decides them, or one per role -- give one candidate each, `key`
1420
- // naming which (`*` for the untargeted table, else its platform; `build-script ` before a build
1421
- // script's beside another role's). Memoized per (package, name, roles, platforms): every file of
1422
- // a package asks for the same few crates.
1423
- const crateTargets = new Map()
1424
- const depCrate = (m, norm, roles, platforms) => {
1425
- const memo = `${m?.dir ?? ''}\0${norm}\0${roles.join()}\0${platforms.join()}`
1426
- return cached(crateTargets, memo, () => depCrateUncached(m, norm, roles, platforms))
1427
- }
985
+ // The in-tree crate roots a name resolves to from package `m`, through each table the code's `roles`
986
+ // link on its `platforms` (`key` naming which); for no package, the one vendored crate.
987
+ const crateTargets = new Map() // every file of a package asks for the same few crates
988
+ const depCrate = (m, norm, roles, platforms) => upsert(crateTargets, `${m?.dir ?? ''}\0${norm}\0${roles.join()}\0${platforms.join()}`, () => depCrateUncached(m, norm, roles, platforms))
1428
989
  const ROLE_KINDS = { build: ['build'], test: ['normal', 'dev'], normal: ['normal'] }
1429
- // The role of the code of crate root `root` in package `m` (see depCrate).
1430
990
  const roleOf = (m, root) => (root === buildScript(m) ? 'build' : (linksDevDeps(root) ? 'test' : 'normal'))
1431
- // Of a dependency's tables (`{ kind, target, … }`, the manifest's or the linked graph's, in
1432
- // order), the packages the asking code links: for each role, the first table of each platform
1433
- // that may apply and that `find` finds a package for, as `{ t, key }` (see depCrate). `any`: a
1434
- // role with no table of its kinds takes any table instead (a declared name).
991
+ // For each role, the first table of each platform that may apply that `find` finds a package for.
992
+ // `any`: a role lacking any takes all.
1435
993
  const linkedTables = (all, roles, platforms, find, any) => {
1436
994
  const out = []
1437
995
  const seen = new Set()
@@ -1440,7 +998,7 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1440
998
  const plats = role === 'build' ? ['host'] : platforms
1441
999
  for (const r of own.length === 0 && any ? all : own) {
1442
1000
  const on = r.target ?? null
1443
- const key = `${role === 'build' && roles.length > 1 ? 'build-script ' : ''}${on === null ? '*' : (/^cfg\((.*)\)$/su.exec(on)?.[1] ?? on)}`
1001
+ const key = `${role === 'build' && roles.length > 1 ? 'build-script ' : ''}${on === null ? '*' : (cfgPredicate(on) ?? on)}`
1444
1002
  if (seen.has(key) || !plats.some((p) => tableOn(on, r.kind === 'build' ? 'host' : p) !== 'no')) continue
1445
1003
  const t = find(r)
1446
1004
  if (t === null) continue
@@ -1450,7 +1008,6 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1450
1008
  }
1451
1009
  return out
1452
1010
  }
1453
- // The candidates as crate roots, one per file.
1454
1011
  const asRoots = (found) => {
1455
1012
  const out = []
1456
1013
  for (const { t, key } of found) {
@@ -1459,8 +1016,6 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1459
1016
  }
1460
1017
  return out
1461
1018
  }
1462
- // depCrate from the exact resolution: the package's dependency of that key, else the unrenamed
1463
- // one whose lib is named that, as the lockfile resolves it.
1464
1019
  const exactCrate = (x, key, norm, roles, platforms) => {
1465
1020
  const deps = x.graph.packages[key].dependencies
1466
1021
  const packageOf = (d) => (d.resolved === undefined ? null : readManifest(x.dirOf.get(d.resolved)))
@@ -1468,6 +1023,8 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1468
1023
  if (declared.length > 0) return asRoots(linkedTables(declared, roles, platforms, packageOf, true))
1469
1024
  return asRoots(linkedTables(deps.filter((d) => d.name === d.package && d.resolved !== undefined && libName(packageOf(d)) === norm), roles, platforms, packageOf, false))
1470
1025
  }
1026
+ // A declared name is the manifest's word: one that doesn't resolve in-tree never falls back to some
1027
+ // vendored copy of that name.
1471
1028
  const depCrateUncached = (m, norm, roles, platforms) => {
1472
1029
  const x = m ? exact() : null
1473
1030
  const key = x?.keyOf.get(m.dir)
@@ -1475,9 +1032,8 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1475
1032
  if (m) {
1476
1033
  const d = m.deps.get(norm)
1477
1034
  if (d) return asRoots(linkedTables([...d.kinds.values()], roles, platforms, (r) => resolveDep(m, d, r), true))
1478
- // A dependency whose lib is named `norm`: only one that may be is resolved (a path
1479
- // dependency's manifest says, a vendored crate's must have that lib name), so a name that is
1480
- // no crate (`u8::MAX`) resolves -- and warns about -- nothing.
1035
+ // Only a dependency that may have lib name `norm` is resolved, so a name that is no crate
1036
+ // (`u8::MAX`) resolves -- and warns about -- nothing.
1481
1037
  const mayBe = (r) => {
1482
1038
  if (!r.path) return vendored().byLib.has(norm)
1483
1039
  const t = r.dir === null ? null : readManifest(r.dir)
@@ -1515,141 +1071,97 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1515
1071
  return depCrate(m, norm, roles, platforms)
1516
1072
  }
1517
1073
 
1518
- // The files describing package `m`'s build, on disk (see buildFilesFor).
1519
- const buildFiles = (m) => {
1074
+ const buildFiles = memoized((m) => {
1520
1075
  const out = [{ path: posix.join(m.dir, 'Cargo.toml'), kind: 'manifest' }]
1521
1076
  if (isVendoredDir(m.dir)) {
1522
1077
  const checksum = posix.join(m.dir, '.cargo-checksum.json')
1523
1078
  if (isFile(join(baseDir, checksum))) out.push({ path: checksum, kind: 'checksum' })
1524
1079
  return out
1525
1080
  }
1526
- const ws = workspaceFor(m.dir)
1527
- if (ws && ws.dir !== m.dir) out.push({ path: posix.join(ws.dir, 'Cargo.toml'), kind: 'manifest' })
1081
+ const ws = rootManifestOf(m)
1082
+ if (ws.isWorkspace && ws.outside === undefined && ws.dir !== m.dir) out.push({ path: posix.join(ws.dir, 'Cargo.toml'), kind: 'manifest' })
1528
1083
  // The build's lockfile and cargo configs, not the package's own: cargo reads only those.
1529
1084
  const lockPath = buildLockPath()
1530
1085
  if (lockPath !== null && isFile(join(baseDir, lockPath))) out.push({ path: lockPath, kind: 'lock' })
1531
1086
  for (const c of configs) if (c.dir !== null) out.push({ path: c.file, kind: 'config' })
1532
1087
  return out
1088
+ })
1089
+ const vendoredPackage = (fileRel) => {
1090
+ const m = packageFor(fileRel)
1091
+ return m !== null && isVendoredDir(m.dir) ? m : null
1533
1092
  }
1534
1093
 
1535
1094
  return {
1536
- // Where `cargo vendor` put the registry crates (project-relative): `vendor`, or what
1537
- // .cargo/config.toml names. A package under it is a vendored dependency.
1538
1095
  vendorDir,
1539
- // Identity of the package owning `fileRel` -- `{ dir, name, version }` from the nearest
1540
- // Cargo.toml with a [package] -- or null when no manifest claims it.
1541
1096
  packageInfo(fileRel) {
1542
1097
  const m = packageFor(fileRel)
1543
1098
  return m ? { dir: m.dir, name: m.package.name, version: version(m) } : null
1544
1099
  },
1545
- // Whether `fileRel` is the lib target root of the package owning it (a crate root by role,
1546
- // whatever its name).
1547
1100
  isLibRoot(fileRel) {
1548
1101
  const m = packageFor(fileRel)
1549
1102
  return m !== null && libPath(m) === fileRel
1550
1103
  },
1551
- // The in-tree crate roots a crate name as used in source (`use name::…`, `extern crate name`)
1552
- // names from `fromFile`, as `[{ file, key }]`: the owning package's own lib (from another of
1553
- // its files), else what depCrate finds -- for the code of each crate root the file is compiled
1554
- // in (`roots`; the file's own role without them), on the platforms of its compile units
1555
- // (`units`; the target's without them). Several when tables that may each apply name different
1556
- // packages (see depCrate); none for anything else (a registry dep that isn't vendored, std, a
1557
- // name that isn't a crate).
1104
+ // `roots`: the crate roots `fromFile` is compiled in; `units`: the units they are compiled as.
1558
1105
  crateCandidates,
1559
- // The first of crateCandidates, or null.
1560
1106
  resolveCrate: (name, fromFile, opts) => crateCandidates(name, fromFile, opts)[0]?.file ?? null,
1561
- // Where the features come from: `{ mode, why }` -- `cargo` (cargo's resolver over the
1562
- // lockfile), `metadata` (`cargo metadata`), or `replay` (the manifests replayed) with `why`
1563
- // cargo's resolver couldn't run.
1107
+ // `cargo` (cargo's resolver over the lockfile), `metadata`, or `replay` with `why` cargo's resolver couldn't run.
1564
1108
  resolution() {
1565
1109
  ensureResolved()
1566
1110
  return metadata ? { mode: 'metadata', why: null } : (exact() === null ? { mode: 'replay', why: exactWhy } : { mode: 'cargo', why: null })
1567
1111
  },
1568
1112
  isTestTarget,
1569
- // The dependencies the build links that nothing in-tree answers, for the packages at `dirs` (the
1570
- // bundled ones): declared, and active in the build as far as the resolution tells (its tables
1571
- // for the build's platforms, an optional one turned on; maybe ones too), but a registry crate
1572
- // not vendored, a path outside the bundle root -- as `{ key, name, from }` (the dependency's
1573
- // key and name in its dependent's manifest, and that package as `name version`). Code may name
1574
- // such a crate by another name than the manifest's (`md-5` is used as `md5`), or not at all, so
1575
- // the bundle can't tell from the code that it lacks one. Dev-dependencies count only for a
1576
- // package an entry is a test, bench or example target of; build-dependencies only for a
1577
- // package with a build script, and with `buildScripts` (build scripts bundled). Cargo's
1578
- // resolver needs every locked package in-tree, so it has none.
1113
+ // Dev-dependencies only for a dev entry's package, build-dependencies only with `buildScripts` and a build script.
1579
1114
  lackingDependencies(dirs, { buildScripts = false } = {}) {
1580
1115
  ensureResolved()
1581
1116
  const counts = (kind, dir) => (kind === 'dev' ? devRootDirs().has(dir) : (kind !== 'build' || (buildScripts && buildScript(readManifest(dir)) !== null)))
1582
- const out = []
1583
- const seen = new Set()
1117
+ const out = new Map()
1584
1118
  for (const { dir, key, name, kinds } of [...(lacking?.values() ?? []), ...(metadata?.lacking ?? [])]) {
1585
1119
  const m = dirs.has(dir) ? readManifest(dir) : null
1586
1120
  const from = m?.package ? `${m.package.name} ${version(m)}` : null
1587
- if (from === null || seen.has(`${from}\0${key}`) || ![...kinds].some((k) => counts(k, dir))) continue
1588
- seen.add(`${from}\0${key}`)
1589
- out.push({ key, name, from })
1121
+ if (from === null || out.has(`${from}\0${key}`) || ![...kinds].some((k) => counts(k, dir))) continue
1122
+ out.set(`${from}\0${key}`, { key, name, from })
1590
1123
  }
1591
- return out
1124
+ return [...out.values()]
1592
1125
  },
1593
- // Whether `fromFile`'s package declares a dependency of that name (in any table, by the key
1594
- // code uses): then the name is that crate -- rustc refuses a `use` path whose lead a glob
1595
- // import also provides, as ambiguous (E0659) -- in-tree or not.
1126
+ // A declared name is that crate, in-tree or not: rustc refuses a `use` path whose lead a glob import
1127
+ // also provides, as ambiguous (E0659).
1596
1128
  declaresCrate(name, fromFile) {
1597
1129
  return packageFor(fromFile)?.deps.has(normName(name)) === true
1598
1130
  },
1599
- // The build's target: its triple and cfg set (`unix`, `target_os="linux"`, … as rustc prints
1600
- // them), or null for both when none was given.
1601
1131
  targetTriple: targetInfo?.triple ?? null,
1602
1132
  targetCfgs: targetInfo?.cfgs ?? null,
1603
- // The files that describe the build of `fileRel`'s package, project-relative, as `{ path,
1604
- // kind }`, those on disk. A vendored package's: its Cargo.toml (`manifest`) and the
1605
- // `.cargo-checksum.json` cargo checks its files against (`checksum`) -- the lock and config a
1606
- // registry crate was published with play no part in a build that depends on it. Any other
1607
- // package's: its own Cargo.toml and, inside the bundle root, the workspace's above it
1608
- // (`manifest`); and the build's Cargo.lock (`lock`) and the cargo configs it reads (`config`,
1609
- // see `runDir`), those inside the bundle root -- not a path dependency's own, which no build
1610
- // of the entries reads. Empty for a file no manifest claims.
1611
1133
  buildFilesFor(fileRel) {
1612
1134
  const m = packageFor(fileRel)
1613
- if (!m) return []
1614
- m.buildFiles ??= buildFiles(m)
1615
- return m.buildFiles
1135
+ return m ? buildFiles(m) : []
1616
1136
  },
1617
- // Throws when `fileRel` is a vendored package's file whose bytes (`buf`) aren't the ones its
1618
- // `.cargo-checksum.json` lists -- edited after `cargo vendor`: cargo refuses to build it, and
1619
- // so the bundle does. A file the list doesn't name, or a package without one, passes; one
1620
- // checked already -- a vendored Cargo.toml, as its package was read -- isn't hashed again.
1621
1137
  checkVendoredFile(fileRel, buf) {
1622
- const m = packageFor(fileRel)
1623
- if (m !== null && isVendoredDir(m.dir)) checkVendored(m.dir, fileRel, buf)
1138
+ const m = vendoredPackage(fileRel)
1139
+ if (m === null) return
1140
+ checkVendored(m.dir, fileRel, buf)
1141
+ checkLocked(m)
1624
1142
  },
1625
- // Whether `fileRel` belongs to a vendored package (a crate `cargo vendor` copied in, a registry's
1626
- // or a git checkout's: see vendoredFrom).
1627
1143
  isVendored(fileRel) {
1628
- const m = packageFor(fileRel)
1629
- return m !== null && isVendoredDir(m.dir)
1144
+ return vendoredPackage(fileRel) !== null
1145
+ },
1146
+ // Undefined for a git checkout's copy, one without `.cargo-checksum.json`, or a package not vendored.
1147
+ vendoredIntegrity(fileRel) {
1148
+ const m = vendoredPackage(fileRel)
1149
+ if (m === null) return undefined
1150
+ checkLocked(m)
1151
+ return archiveIntegrity('cargo', checksumOf(m.dir)?.package)
1630
1152
  },
1631
- // Where `cargo vendor` copied the vendored package owning `fileRel` from, as its
1632
- // `.cargo-checksum.json` tells: `registry` (a package checksum) or `git` (a git checkout's: none);
1633
- // null when it has no such file, and so could be either, or isn't vendored.
1634
1153
  vendoredFrom(fileRel) {
1635
- const m = packageFor(fileRel)
1636
- return m !== null && isVendoredDir(m.dir) ? copySource(m.dir) : null
1154
+ const m = vendoredPackage(fileRel)
1155
+ return m === null ? null : copySource(m.dir)
1637
1156
  },
1638
- // The build script of `fileRel`'s package, project-relative, when there is one on disk:
1639
- // `[package] build = "…"`, else `build.rs` beside the manifest; `build = false` means none. A
1640
- // vendored package's may not name a file outside the package (a published crate never does).
1641
1157
  buildScriptOf(fileRel) {
1642
1158
  const m = packageFor(fileRel)
1643
1159
  return m ? buildScript(m) : null
1644
1160
  },
1645
- // The custom cfgs the build of `fileRel`'s package may set (a `--cfg` a default build lacks is
1646
- // otherwise presumed off): `{ names, any }` -- the names its build script prints as
1647
- // `cargo:rustc-cfg=…`, itself or through a crate it calls, and those the rustflags set, and
1648
- // whether the script may set one the loader can't read. One object per package (and one for
1649
- // every package that sets none).
1161
+ // A `--cfg` a default build lacks is otherwise presumed off.
1650
1162
  cfgsSetFor(fileRel) {
1651
1163
  const m = packageFor(fileRel)
1652
- return cached(cfgsSetMemo, m?.dir ?? '\0', () => {
1164
+ return upsert(cfgsSetMemo, m?.dir ?? '\0', () => {
1653
1165
  rustflagCfgs ??= rustflagsCfgsOf(configs)
1654
1166
  const script = m ? buildScript(m) : null
1655
1167
  const printed = script === null ? NO_CFGS_SET : cfgsPrinted(crateTexts(script))
@@ -1659,10 +1171,7 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1659
1171
  return names.size === 0 && !any ? NO_CFGS_SET : { names, any }
1660
1172
  })
1661
1173
  },
1662
- // The features on for certain for the package owning `fileRel`, compiled as `unit` (see
1663
- // unitOfCrate), in the build of the root packages; null when that is unknown: no owning
1664
- // manifest, no root package to resolve from, or a package the resolved build doesn't pull in
1665
- // (its gated code is then kept, not dropped).
1174
+ // Null when unknown, as for a package the build doesn't pull in: its gated code is then kept.
1666
1175
  featuresFor(fileRel, unit = TARGET_UNIT) {
1667
1176
  const m = packageFor(fileRel)
1668
1177
  if (!m) return null
@@ -1670,45 +1179,29 @@ export function createCargoContext(baseDir, { entries = [], features = [], noDef
1670
1179
  const { sure, all } = ensureResolved()
1671
1180
  return sure.get(node) ?? (all.has(node) ? NO_FEATURES : null)
1672
1181
  },
1673
- // The features on only in some of the builds the loader can't tell apart (a target-specific
1674
- // table it can't decide, or what only such a table requests), for the same package and unit;
1675
- // null when there are none.
1182
+ // On only in some of the builds the loader can't tell apart (a target-specific table it can't decide).
1676
1183
  maybeFeaturesFor(fileRel, unit = TARGET_UNIT) {
1677
1184
  const m = packageFor(fileRel)
1678
- if (!m) return null
1679
- return maybeOf(nodeKey(unitFeatureCtx(unit), m.dir))
1185
+ return m ? maybeOf(nodeKey(unitFeatureCtx(unit), m.dir)) : null
1680
1186
  },
1681
- // Every package of a context the build may pull in: dir -> { on, maybe }, the features on for
1682
- // certain and those on only maybe (a package only an undecided table pulls in has every
1683
- // feature of its maybe). For diagnostics and tests.
1187
+ // dir -> { on, maybe }: a package only an undecided table pulls in has every feature of its maybe.
1684
1188
  featureResolution(context = 'target') {
1685
- const out = new Map()
1686
1189
  const prefix = nodeKey(context, '')
1687
- for (const node of ensureResolved().all.keys()) {
1688
- if (node.startsWith(prefix)) out.set(node.slice(prefix.length), { on: ensureResolved().sure.get(node) ?? NO_FEATURES, maybe: maybeOf(node) ?? NO_FEATURES })
1689
- }
1690
- return out
1190
+ const { sure, all } = ensureResolved()
1191
+ const inContext = all.keys().filter((node) => node.startsWith(prefix))
1192
+ return new Map(inContext.map((node) => [node.slice(prefix.length), { on: sure.get(node) ?? NO_FEATURES, maybe: maybeOf(node) ?? NO_FEATURES }]))
1691
1193
  },
1692
- // Every resolved package of a context: dir -> Set<feature on for certain>. For diagnostics and tests.
1693
1194
  resolvedFeatures(context = 'target') {
1694
- const out = new Map()
1695
1195
  const prefix = nodeKey(context, '')
1696
- for (const [node, set] of ensureResolved().sure) if (node.startsWith(prefix)) out.set(node.slice(prefix.length), set)
1697
- return out
1196
+ const inContext = ensureResolved().sure.entries().filter(([node]) => node.startsWith(prefix))
1197
+ return new Map(inContext.map(([node, set]) => [node.slice(prefix.length), set]))
1698
1198
  },
1699
- // The compile unit of a crate root `libFile` named from code compiled as `fromUnit`: a proc-macro
1700
- // crate, and anything code compiled for the host names (a build script's build-dependencies,
1701
- // a proc-macro's dependencies), is built for the host in the host's feature context; else the
1702
- // namer's unit.
1703
1199
  unitOfCrate(libFile, fromUnit = TARGET_UNIT) {
1704
- return isProcMacroPkg(packageFor(libFile)) || unitPlatform(fromUnit) === 'host' ? HOST_UNIT : fromUnit
1200
+ return packageFor(libFile)?.lib.procMacro === true || unitPlatform(fromUnit) === 'host' ? HOST_UNIT : fromUnit
1705
1201
  },
1706
- // The unit of a build script of a package compiled as `pkgUnit`: for the host, with the
1707
- // package's features.
1708
1202
  buildScriptUnit(pkgUnit = TARGET_UNIT) {
1709
1203
  return unitKey(unitFeatureCtx(pkgUnit), 'host')
1710
1204
  },
1711
- // The cfgs and triple of the platform `unit` compiles for, as far as known (see platformInfo).
1712
1205
  platformOf(unit = TARGET_UNIT) {
1713
1206
  return platformInfo(unitPlatform(unit))
1714
1207
  },