@exodus/stasis 1.0.0-beta.9 → 1.0.0-rc.1

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 +6 -2
  2. package/bin/stasis.js +222 -334
  3. package/package.json +38 -14
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +256 -212
  6. package/src/babel.js +119 -82
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +24 -8
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +211 -117
  11. package/src/cmd/bundle-options.js +347 -0
  12. package/src/cmd/bundle.js +1664 -1001
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +48 -21
  15. package/src/cmd/output.js +25 -12
  16. package/src/cmd/sbom.js +6 -9
  17. package/src/cmd/tokens.js +60 -0
  18. package/src/define.js +218 -0
  19. package/src/diff.js +73 -129
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +27 -0
  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 +43 -120
  27. package/src/loaders/cargo.js +301 -808
  28. package/src/loaders/foundry.js +112 -290
  29. package/src/loaders/paths.js +15 -26
  30. package/src/loaders/php.js +211 -492
  31. package/src/loaders/rust.js +518 -1461
  32. package/src/loaders/solidity-ownership.js +51 -142
  33. package/src/loaders/solidity.js +42 -188
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +41 -0
  37. package/src/metro-resolver.js +58 -133
  38. package/src/metro-transformer.js +0 -6
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +8 -7
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +152 -249
  44. package/src/resolve-node.js +29 -45
  45. package/src/resolve-typescript.js +166 -298
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +70 -97
  49. package/src/scan.js +240 -282
  50. package/src/sixel.js +310 -0
  51. package/src/table.js +95 -0
  52. package/src/validate-notes.d.ts +19 -0
  53. package/src/validate-notes.js +72 -0
  54. package/src/validate.d.ts +159 -0
  55. package/src/validate.js +1315 -0
  56. package/src/vfs-bundle/entries.js +50 -46
  57. package/src/vfs-bundle/github.js +114 -94
  58. package/src/vfs-bundle/glob.js +379 -0
  59. package/src/vfs-bundle/lazy.js +99 -0
  60. package/src/vfs-bundle/prisma.js +235 -105
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +418 -277
  63. package/src/vfs-bundle/yarnclean.js +79 -0
  64. package/src/vfs-bundle.js +24 -55
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +79 -231
  67. package/src/installed-commits.js +0 -182
@@ -1,22 +1,11 @@
1
- // Foundry configuration for the Solidity loader: foundry.toml profiles (with `extends`) and the
2
- // remappings `forge build` hands solc -- the `FOUNDRY_REMAPPINGS`/`DAPP_REMAPPINGS` env var,
3
- // remappings.txt, the profile's `remappings`, those of every dependency that is itself a Foundry
4
- // project, and the ones forge auto-detects under the `libs` dirs (global, plus per-dependency
5
- // contexts for an alias two dependencies map differently). A port of foundry v1.8.3's
6
- // `RemappingsProvider` (crates/config/src/providers/remappings.rs) and foundry-compilers'
7
- // `Remapping::find_many_with_context` (artifacts/solc/src/remappings/find.rs), including the
8
- // `forge build` pass that drops aliases of the project's own src/test/script dirs.
9
- //
10
- // Paths are absolute POSIX strings internally, compared the way Rust compares `Path`s (by
11
- // component: a trailing `/` doesn't count), and returned relative to the project root. Not read:
12
- // the global ~/.foundry/foundry.toml, `FOUNDRY_CONFIG`, and the FOUNDRY_*/DAPP_* overrides of
13
- // other keys (`FOUNDRY_PROFILE` and the remapping env vars are). The project is read through a
14
- // `host` (@exodus/stasis-core/host), the disk's by default.
1
+ // foundry.toml profiles (with `extends`) and the remappings `forge build` hands solc: a port of foundry
2
+ // v1.8.3's `RemappingsProvider` and foundry-compilers' `Remapping::find_many_with_context`. Not read:
3
+ // ~/.foundry/foundry.toml, `FOUNDRY_CONFIG`, FOUNDRY_*/DAPP_* other than the profile and remappings.
15
4
 
16
5
  import { posix, resolve } from 'node:path'
17
6
 
18
7
  import { diskHost } from '@exodus/stasis-core/host'
19
- import { toPosix } from '@exodus/stasis-core/util'
8
+ import { nestedMap, toPosix } from '@exodus/stasis-core/util'
20
9
  import { isDir } from '../resolve-typescript.js'
21
10
  import { projectOwnership, projectRelative, readUtf8OrNull, realpathOrNull } from './solidity-ownership.js'
22
11
  import { isTomlTable, readToml } from './toml.js'
@@ -24,21 +13,14 @@ import { isTomlTable, readToml } from './toml.js'
24
13
  export const FOUNDRY_TOML = 'foundry.toml'
25
14
  export const REMAPPINGS_TXT = 'remappings.txt'
26
15
 
27
- // --- Path helpers (Rust `Path` semantics on POSIX strings) --------------------------------
28
-
16
+ // Paths are absolute POSIX, compared by component as Rust compares `Path`s.
29
17
  const isAbs = (p) => p.startsWith('/')
30
18
  const normalComps = (p) => p.split('/').filter((c) => c !== '' && c !== '.')
31
19
  const compCount = (p) => normalComps(p).length + (isAbs(p) ? 1 : 0)
32
20
  const fileName = (p) => normalComps(p).at(-1) ?? null
33
21
  const pathKey = (p) => (isAbs(p) ? '/' : '') + normalComps(p).join('/')
34
22
  const pathEq = (a, b) => pathKey(a) === pathKey(b)
35
- // `Path::ends_with` with a relative suffix: the last components match.
36
- const pathEndsWith = (p, suffix) => {
37
- const a = normalComps(p)
38
- const b = normalComps(suffix)
39
- return b.length <= a.length && b.every((c, i) => a[a.length - b.length + i] === c)
40
- }
41
- // `Path::strip_prefix`: the remaining components (no trailing `/`), or null.
23
+ // `Path::strip_prefix`: the remaining components, or null.
42
24
  function stripPrefix(p, base) {
43
25
  if (isAbs(p) !== isAbs(base)) return null
44
26
  const a = normalComps(p)
@@ -47,7 +29,6 @@ function stripPrefix(p, base) {
47
29
  return a.slice(b.length).join('/')
48
30
  }
49
31
  const pathStartsWith = (p, base) => stripPrefix(p, base) !== null
50
- // `PathBuf::join`: an absolute `p` replaces; otherwise appended with one separator.
51
32
  const rustJoin = (base, p) => (isAbs(p) ? p : base.endsWith('/') ? `${base}${p}` : `${base}/${p}`)
52
33
  const parentOf = (p) => {
53
34
  const c = normalComps(p)
@@ -55,7 +36,6 @@ const parentOf = (p) => {
55
36
  return (isAbs(p) ? '/' : '') + c.slice(0, -1).join('/')
56
37
  }
57
38
  const cmpStr = (a, b) => (a < b ? -1 : a > b ? 1 : 0)
58
- // `Ord for Path`: component by component.
59
39
  function cmpPath(a, b) {
60
40
  if (isAbs(a) !== isAbs(b)) return isAbs(a) ? -1 : 1
61
41
  const x = normalComps(a)
@@ -72,8 +52,7 @@ function canonicalize(p, host) {
72
52
  return real === null ? null : toPosix(real)
73
53
  }
74
54
 
75
- // How messages name a file of the project at `root` (absolute POSIX, read through `host`): from the
76
- // root, by its lexical or its canonical path, else as given.
55
+ // How messages name a file of the project at `root`: from the root, by its lexical or its canonical path.
77
56
  export function shownFrom(root, host = diskHost, canonicalRoot = canonicalize(root, host) ?? root) {
78
57
  return (abs) => stripPrefix(abs, root) || stripPrefix(abs, canonicalRoot) || abs
79
58
  }
@@ -86,9 +65,8 @@ const isSymlinkPath = (p, host) => {
86
65
  }
87
66
  }
88
67
 
89
- // A dir's entries with their (symlink-followed) kind, in the filesystem's own order where the host
90
- // has one (readdirUnsorted): forge walks `read_dir` unsorted, and where two packages share a lib
91
- // window the first one listed decides a remapping. An entry whose symlink doesn't resolve is dropped.
68
+ // In the filesystem's own order where the host has one: forge walks `read_dir` unsorted, and where two
69
+ // packages share a lib window the first one listed decides a remapping. A dangling symlink is dropped.
92
70
  function listDir(dir, host) {
93
71
  let entries
94
72
  try {
@@ -96,65 +74,46 @@ function listDir(dir, host) {
96
74
  } catch {
97
75
  return []
98
76
  }
99
- const out = []
100
- for (const e of entries) {
77
+ return entries.flatMap((e) => {
101
78
  const path = rustJoin(dir, e.name)
102
79
  const kind = e.isSymbolicLink() ? host.stat(path) : e
103
- if (kind === null) continue
104
- out.push({ path, name: e.name, isFile: kind.isFile(), isDir: kind.isDirectory(), isSymlink: e.isSymbolicLink() })
105
- }
106
- return out
80
+ return kind === null ? [] : [{ path, name: e.name, isFile: kind.isFile(), isDir: kind.isDirectory(), isSymlink: e.isSymbolicLink() }]
81
+ })
107
82
  }
108
83
 
109
- // The auto-detection's view of a dir: hidden entries skipped.
110
84
  const readDir = (dir, host) => listDir(dir, host).filter((e) => !e.name.startsWith('.'))
111
85
 
112
- // --- Remapping values ----------------------------------------------------------------------
113
-
114
- // Rust's `str::trim`: Unicode White_Space only, so a byte-order mark (U+FEFF, which JS's `trim`
115
- // takes) stays, as it does for forge.
86
+ // Rust's `str::trim`: a byte-order mark (U+FEFF, which JS's `trim` takes) stays, as it does for forge.
116
87
  const rustTrim = (s) => s.replaceAll(/^\p{White_Space}+|\p{White_Space}+$/gu, '')
117
88
 
118
- // `[context:]name=path`, as forge (`Remapping::from_str`) and solc split it: at the first `=`, then
119
- // the first `:` before it. An empty context is global; an empty name or path is invalid (null),
89
+ // `[context:]name=path`, split as forge and solc split it. An empty name or path is invalid (null),
120
90
  // but for solc (`emptyPath`) only an empty name is: `x/=` maps `x/A.sol` to `A.sol`.
121
91
  function parseRemapping(entry, { emptyPath = false } = {}) {
122
92
  const eq = entry.indexOf('=')
123
93
  if (eq === -1) return null
124
- let name = entry.slice(0, eq)
94
+ const colon = entry.slice(0, eq).indexOf(':')
95
+ const name = entry.slice(colon + 1, eq)
125
96
  const path = entry.slice(eq + 1)
126
- let context = null
127
- const colon = name.indexOf(':')
128
- if (colon !== -1) {
129
- context = name.slice(0, colon)
130
- name = name.slice(colon + 1)
131
- }
97
+ let context = colon === -1 ? null : entry.slice(0, colon)
132
98
  if (rustTrim(name) === '' || (!emptyPath && rustTrim(path) === '')) return null
133
99
  if (context !== null && rustTrim(context) === '') context = null
134
100
  return { context, name, path }
135
101
  }
136
102
 
137
- // What an invalid remapping should have been; errors name where one is, never its text, which may
138
- // be anything (a file named as a mapping by mistake, a secret included).
103
+ // Errors name where an invalid remapping is, never its text, which may be anything (a secret included).
139
104
  const REMAPPING_FORM = 'expected [context:]prefix=target'
140
105
 
141
- // A remappings.txt / env var body: one remapping per non-blank (trimmed) line. A line that isn't
142
- // one throws, naming `label` (the file or variable) and the line, as forge and solc refuse the
143
- // file. `emptyPath`: see parseRemapping.
106
+ // One remapping per non-blank line; a line that isn't one throws, as forge and solc refuse the file.
144
107
  export function parseRemappingLines(text, { label = 'remappings', emptyPath = false } = {}) {
145
- const out = []
146
- text.split('\n').forEach((raw, i) => {
108
+ return text.split('\n').flatMap((raw, i) => {
147
109
  const line = rustTrim(raw)
148
- if (line === '') return
110
+ if (line === '') return []
149
111
  const r = parseRemapping(line, { emptyPath })
150
112
  if (r === null) throw new Error(`${label}:${i + 1}: invalid remapping, ${REMAPPING_FORM}`)
151
- out.push(r)
113
+ return [r]
152
114
  })
153
- return out
154
115
  }
155
116
 
156
- // A foundry.toml's `remappings` value, parsed. One forge rejects -- not an array of strings, or an
157
- // entry that isn't `[context:]name=path` -- throws, naming `file` when given and the entry (from 1).
158
117
  function configRemappings(value, file) {
159
118
  const where = `${file === null ? '' : `${file}: `}\`remappings\``
160
119
  if (!Array.isArray(value)) throw new Error(`${where} is not an array of strings`)
@@ -166,50 +125,37 @@ function configRemappings(value, file) {
166
125
  })
167
126
  }
168
127
 
169
- // A config forge refuses for its settings (a missing or nested `extends`, colliding keys) or that a
170
- // dependency may not read (a link out of it): forge skips such a dependency's config, and so does
171
- // loadNestedConfig. Anything else wrong with a config -- text that isn't TOML, an invalid
172
- // remapping -- is another error, and fatal.
128
+ // A config forge refuses for its settings, or that a dependency may not read: a dependency's is
129
+ // skipped, as forge skips it. Anything else wrong with a config is fatal.
173
130
  class ConfigRefused extends Error {}
174
131
 
175
- // Forge's trailing `/` on a remapping's name and path, unless they end in `/` or `.sol`.
176
132
  const withSlash = (s) => (s.endsWith('/') || s.endsWith('.sol') ? s : `${s}/`)
133
+ const withTrailing = (s) => (s.endsWith('/') ? s : `${s}/`)
134
+ const trimSlashes = (s) => s.replace(/\/+$/u, '')
177
135
 
178
- // A remapping as forge hands it to solc, in the loader's `{ context, prefix, target }` shape:
179
- // `forge-std=lib/forge-std/src` is `forge-std/=lib/forge-std/src/`.
180
136
  export const toSolcRemapping = (r) => ({ context: r.context, prefix: withSlash(r.name), target: withSlash(r.path) })
181
137
 
182
- // The profile forge selects: FOUNDRY_PROFILE, else `default`. Profile names are case-insensitive
183
- // (figment's `Profile`), so they are compared lowercased.
138
+ // Profile names are case-insensitive (figment's `Profile`).
184
139
  export const foundryProfile = (env) => (env.FOUNDRY_PROFILE || 'default').toLowerCase()
185
140
 
186
141
  // `RelativeRemappingPathBuf::with_root`.
187
142
  function withRoot(parent, path) {
188
143
  const rest = stripPrefix(path, parent)
189
144
  if (rest !== null) return { parent, path: rest }
190
- if (isAbs(path)) return { parent: null, path }
191
- return { parent, path }
145
+ return { parent: isAbs(path) ? null : parent, path }
192
146
  }
193
147
 
194
- // `RelativeRemapping::new(remapping, root)`.
195
- function toRelative(r, root) {
196
- return {
197
- context: r.context === null ? null : withRoot(root, r.context).path,
198
- name: r.name,
199
- path: withRoot(root, r.path),
200
- }
201
- }
148
+ // `RelativeRemapping::new`.
149
+ const toRelative = (r, root) => ({ context: r.context === null ? null : withRoot(root, r.context).path, name: r.name, path: withRoot(root, r.path) })
202
150
 
203
- // `From<RelativeRemapping> for Remapping`: the path joined back onto its parent, and a trailing
204
- // `/` on name and path unless they end in `/` or `.sol`.
151
+ // `From<RelativeRemapping> for Remapping`.
205
152
  function fromRelative(rr) {
206
153
  const { parent, path } = rr.path
207
154
  const joined = isAbs(path) || parent === null ? path : rustJoin(parent, path)
208
155
  return { context: rr.context, name: withSlash(rr.name), path: withSlash(joined) }
209
156
  }
210
157
 
211
- // `relative_remapping_preserving_context_boundary`: relative to `root`, keeping a context's
212
- // trailing `/` (it bounds the directory the context names).
158
+ // `relative_remapping_preserving_context_boundary`: a context's trailing `/` bounds its directory.
213
159
  function relativePreservingBoundary(r, root) {
214
160
  const rr = toRelative(r, root)
215
161
  if (r.context?.endsWith('/') && rr.context !== null) rr.context = withTrailing(rr.context)
@@ -217,18 +163,14 @@ function relativePreservingBoundary(r, root) {
217
163
  }
218
164
 
219
165
  // `Display for RelativeRemapping`.
220
- function displayRelative(rr) {
221
- const s = `${rr.context === null ? '' : `${rr.context}:`}${rr.name}=${rr.path.path}`
222
- return withSlash(s)
223
- }
166
+ const displayRelative = (rr) => withSlash(`${rr.context === null ? '' : `${rr.context}:`}${rr.name}=${rr.path.path}`)
224
167
 
225
- // `RelativeRemapping` equality (paths by component).
226
168
  const relKey = (rr) => `${rr.context}\0${rr.name}\0${rr.path.parent === null ? '\u0001' : pathKey(rr.path.parent)}\0${pathKey(rr.path.path)}`
227
169
 
228
- // `Remappings`: a list that only takes an alias not already claimed (in the same context) by an
229
- // equal or shorter one, and never an alias of the project's own src/test/script dirs.
170
+ // `Remappings`: takes an alias only when no equal or shorter one claims it (in the same context), and
171
+ // never an alias of the project's own src/test/script dirs.
230
172
  class Remappings {
231
- constructor(remappings = [], projectPaths = []) {
173
+ constructor(remappings, projectPaths = []) {
232
174
  this.remappings = remappings
233
175
  this.projectPaths = projectPaths
234
176
  }
@@ -244,21 +186,11 @@ class Remappings {
244
186
  this.remappings.push(r)
245
187
  }
246
188
 
247
- // First of each (context, name).
248
189
  intoInner() {
249
- const seen = new Set()
250
- return this.remappings.filter((r) => {
251
- const key = `${r.context}\0${r.name}`
252
- if (seen.has(key)) return false
253
- seen.add(key)
254
- return true
255
- })
190
+ return [...Map.groupBy(this.remappings, (r) => `${r.context}\0${r.name}`).values()].map(([r]) => r)
256
191
  }
257
192
  }
258
193
 
259
- const withTrailing = (s) => (s.endsWith('/') ? s : `${s}/`)
260
- const trimSlashes = (s) => s.replace(/\/+$/u, '')
261
-
262
194
  // `remapping_name_is_prefix`: `prefix` names `name` or a parent namespace of it.
263
195
  function nameIsPrefix(prefix, name) {
264
196
  const p = trimSlashes(prefix)
@@ -266,8 +198,6 @@ function nameIsPrefix(prefix, name) {
266
198
  return p === n || (n.startsWith(p) && n.slice(p.length).startsWith('/'))
267
199
  }
268
200
 
269
- // --- Auto-detection (foundry-compilers find.rs) ---------------------------------------------
270
-
271
201
  const SRC_DIR = 'src'
272
202
  const JS_SRC_DIR = 'contracts'
273
203
  const isSourceDir = (p) => [SRC_DIR, JS_SRC_DIR].includes(fileName(p))
@@ -275,14 +205,8 @@ const isLibName = (name) => name === 'lib' || name === 'node_modules'
275
205
  const isLibDir = (p) => isLibName(fileName(p))
276
206
  const noRecurse = (name) => name === 'tests' || name === 'test' || name === 'demo'
277
207
 
278
- function dirDistance(root, current) {
279
- const rest = stripPrefix(current, root)
280
- return rest === null ? 0 : normalComps(rest).length
281
- }
282
-
283
- // The window a dir under the lib dir `root` belongs to: `root`'s child on the way to `current`.
284
- // (Upstream loops `while !is_lib_dir(next) || !next.ends_with("contracts")`, which always holds on
285
- // the first component.)
208
+ // `root`'s child on the way to `current`. (Upstream loops `while !is_lib_dir(next) ||
209
+ // !next.ends_with("contracts")`, which always holds on the first component.)
286
210
  function nextNestedWindow(root, current) {
287
211
  if (!isLibDir(root)) return root
288
212
  const first = normalComps(stripPrefix(current, root) ?? '')[0]
@@ -291,37 +215,28 @@ function nextNestedWindow(root, current) {
291
215
 
292
216
  function lastNestedSourceDir(root, dir) {
293
217
  if (isSourceDir(dir)) return dir
294
- let p = dir
295
- for (let parent = parentOf(p); parent !== null; parent = parentOf(p)) {
218
+ for (let parent = parentOf(dir); parent !== null; parent = parentOf(parent)) {
296
219
  if (pathEq(parent, root)) return root
297
220
  if (isSourceDir(parent)) return parent
298
- p = parent
299
221
  }
300
222
  return root
301
223
  }
302
224
 
303
- const endsWithJsSource = (c) => fileName(c.sourceDir) === JS_SRC_DIR || pathEndsWith(c.sourceDir, 'contracts/src')
225
+ const endsWithJsSource = (c) => fileName(c.sourceDir) === JS_SRC_DIR || normalComps(c.sourceDir).slice(-2).join('/') === 'contracts/src'
304
226
 
305
227
  function mergeOnSameLevel(candidates, currentDir, level, windowStart, insideNodeModules) {
306
- // A single `src` candidate wins outright.
307
228
  const srcs = candidates.filter((c) => fileName(c.sourceDir) === SRC_DIR)
308
- if (srcs.length === 1) {
309
- candidates.splice(0, candidates.length, srcs[0])
310
- return
311
- }
229
+ if (srcs.length === 1) return srcs
312
230
  // Else the current dir absorbs the candidates of its level (`current/{auth,tokens}/*.sol`).
313
- for (let i = candidates.length - 1; i >= 0; i--) {
314
- if (candidates[i].level === level) candidates.splice(i, 1)
315
- }
231
+ const rest = candidates.filter((c) => c.level !== level)
316
232
  const sourceDir = insideNodeModules ? windowStart : currentDir
317
233
  // `<dep>/src/lib/` mistaken for a package of its own.
318
- if (level > 0 && pathEq(sourceDir, windowStart) && (isSourceDir(sourceDir) || isLibDir(sourceDir))) return
319
- candidates.push({ windowStart, sourceDir, level })
234
+ if (level > 0 && pathEq(sourceDir, windowStart) && (isSourceDir(sourceDir) || isLibDir(sourceDir))) return rest
235
+ return [...rest, { windowStart, sourceDir, level }]
320
236
  }
321
237
 
322
- // Candidates below `currentDir`: a window opens at each `lib`/`node_modules` barrier, and a dir
323
- // holding `.sol` files is a source dir of the window it lies in. Symlinked dirs are followed,
324
- // except back into the current traversal path.
238
+ // A window opens at each `lib`/`node_modules` barrier, and a dir holding `.sol` files is a source dir
239
+ // of the window it lies in. Symlinked dirs are followed, except back into the current traversal path.
325
240
  function findRemappingCandidates(currentDir, open, level, insideNodeModules, visited, host) {
326
241
  let isCandidate = false
327
242
  let current
@@ -343,29 +258,24 @@ function findRemappingCandidates(currentDir, open, level, insideNodeModules, vis
343
258
  }
344
259
  }
345
260
 
346
- const candidates = []
347
- for (const [{ path, name }, seen] of search) {
348
- candidates.push(...(isLibName(name)
349
- ? findRemappingCandidates(path, path, level + 1, insideNodeModules, seen, host)
350
- : findRemappingCandidates(path, open, level, insideNodeModules, seen, host)))
351
- }
261
+ const candidates = search.flatMap(([{ path, name }, seen]) => (isLibName(name)
262
+ ? findRemappingCandidates(path, path, level + 1, insideNodeModules, seen, host)
263
+ : findRemappingCandidates(path, open, level, insideNodeModules, seen, host)))
352
264
 
353
265
  const windowStart = nextNestedWindow(open, currentDir)
354
266
  if (isCandidate || candidates.filter((c) => c.level === level && pathEq(c.windowStart, windowStart)).length > 1) {
355
- mergeOnSameLevel(candidates, currentDir, level, windowStart, insideNodeModules)
356
- } else {
357
- // A single nested candidate: `current/nested/contracts/c.sol` maps to `current`.
358
- const c = candidates.find((x) => x.level === level)
359
- if (c) {
360
- const distance = dirDistance(c.windowStart, c.sourceDir)
361
- if (distance > 1 && endsWithJsSource(c)) c.sourceDir = windowStart
362
- else if (!isSourceDir(c.sourceDir) && !pathEq(c.sourceDir, c.windowStart)) c.sourceDir = lastNestedSourceDir(open, c.sourceDir)
363
- }
267
+ return mergeOnSameLevel(candidates, currentDir, level, windowStart, insideNodeModules)
268
+ }
269
+ // A single nested candidate: `current/nested/contracts/c.sol` maps to `current`.
270
+ const c = candidates.find((x) => x.level === level)
271
+ if (c) {
272
+ const distance = normalComps(stripPrefix(c.sourceDir, c.windowStart) ?? '').length
273
+ if (distance > 1 && endsWithJsSource(c)) c.sourceDir = windowStart
274
+ else if (!isSourceDir(c.sourceDir) && !pathEq(c.sourceDir, c.windowStart)) c.sourceDir = lastNestedSourceDir(open, c.sourceDir)
364
275
  }
365
276
  return candidates
366
277
  }
367
278
 
368
- // Prefer the shorter path, then one ending in `src`.
369
279
  function insertPrioritized(map, key, path) {
370
280
  const existing = map.get(key)
371
281
  if (existing === undefined || compCount(existing) > compCount(path) || (fileName(path) === SRC_DIR && fileName(existing) !== SRC_DIR)) {
@@ -373,8 +283,7 @@ function insertPrioritized(map, key, path) {
373
283
  }
374
284
  }
375
285
 
376
- // The dependency owning a nested package window: the path before the last `lib`/`node_modules`
377
- // component below `root` (null at the top level).
286
+ // The path before the last `lib`/`node_modules` component below `root` (null at the top level).
378
287
  function dependencyOwner(root, windowStart) {
379
288
  const rest = stripPrefix(windowStart, root)
380
289
  if (rest === null) return null
@@ -389,11 +298,9 @@ const byContextDepth = (a, b) => {
389
298
  return compCount(y) - compCount(x) || cmpStr(x, y)
390
299
  }
391
300
 
392
- // A map's entries, sorted by key with `cmp`.
393
301
  const sortedEntries = (map, cmp) => [...map].toSorted(([a], [b]) => cmp(a, b))
394
302
 
395
- // `Remapping::find_many_with_context(dir)`: `{ global, contextual }` remappings for the packages
396
- // under a lib dir, `contextual` keyed by the dependency whose own lib dir holds the package.
303
+ // `contextual` is keyed by the dependency whose own lib dir holds the package.
397
304
  export function findRemappingsWithContext(dir, host = diskHost) {
398
305
  const insideNodeModules = fileName(dir) === 'node_modules'
399
306
  const candidates = readDir(dir, host)
@@ -408,10 +315,7 @@ export function findRemappingsWithContext(dir, host = diskHost) {
408
315
  if (name === null) continue
409
316
  const key = `${name}/`
410
317
  const owner = dependencyOwner(dir, c.windowStart)
411
- if (owner !== null) {
412
- if (!contextual.has(owner)) contextual.set(owner, new Map())
413
- insertPrioritized(contextual.get(owner), key, c.sourceDir)
414
- }
318
+ if (owner !== null) insertPrioritized(nestedMap(contextual, owner), key, c.sourceDir)
415
319
  insertPrioritized(global, key, c.sourceDir)
416
320
  }
417
321
  return {
@@ -422,8 +326,6 @@ export function findRemappingsWithContext(dir, host = diskHost) {
422
326
  }
423
327
  }
424
328
 
425
- // --- foundry.toml ---------------------------------------------------------------------------
426
-
427
329
  const snakeCase = (k) => k.replaceAll(/([a-z0-9])([A-Z])/gu, '$1_$2').replaceAll('-', '_').toLowerCase()
428
330
 
429
331
  // Top-level tables that are sections of their own, not (legacy) profiles (`Config::STANDALONE_SECTIONS`).
@@ -432,20 +334,14 @@ const STANDALONE_SECTIONS = new Set([
432
334
  'coverage', 'mutation', 'tracing', 'labels', 'dependencies', 'soldeer', 'vyper', 'bind_json',
433
335
  ])
434
336
 
435
- // foundry.toml -> `{ profiles, topLevel }`. `profiles` is Map<profile, Map<key, value>> (profile
436
- // names lowercased, keys snake_cased as forge does) from the `[profile.<name>]` tables and the
437
- // legacy top-level `[<name>]` ones forge still reads (not for `extends`), the former winning key
438
- // by key; a profile's sub-tables are its values like any other (`extends`, `fuzz`: forge compares
439
- // them all for a `no-collision` extends). `topLevel` holds the values set outside any table (forge
440
- // rejects those; a `--mapping` file may list its `remappings` there). Throws a TomlError naming
441
- // `file` on text that isn't TOML, as forge refuses the file.
337
+ // `[profile.<name>]` over the legacy `[<name>]`, key by key; `topLevel`: values outside any table.
442
338
  function parseFoundryToml(text, file = null) {
443
339
  const current = new Map()
444
340
  const legacy = new Map()
445
341
  const topLevel = new Map()
446
342
  const read = (map, name, table) => {
447
343
  const profile = name.toLowerCase()
448
- const dict = map.get(profile) ?? map.set(profile, new Map()).get(profile)
344
+ const dict = nestedMap(map, profile)
449
345
  for (const [key, value] of Object.entries(table)) {
450
346
  const k = snakeCase(key)
451
347
  if (k !== 'extends' || map === current) dict.set(k, value) // forge reads `extends` from `[profile.<name>]` only
@@ -462,13 +358,11 @@ function parseFoundryToml(text, file = null) {
462
358
  return { profiles, topLevel }
463
359
  }
464
360
 
465
- // Figment's merge of an `extends` base under the local file: local keys win, and with the
466
- // default `extend-arrays` strategy an array set on both sides is the base's followed by the local's.
361
+ // Figment's merge of an `extends` base: local keys win; `extend-arrays` appends a local array to the base's.
467
362
  function mergeExtended(base, local, strategy) {
468
363
  const out = new Map([...base].map(([p, dict]) => [p, new Map(dict)]))
469
364
  for (const [p, dict] of local) {
470
- if (!out.has(p)) out.set(p, new Map())
471
- const merged = out.get(p)
365
+ const merged = nestedMap(out, p)
472
366
  for (const [k, v] of dict) {
473
367
  const prev = merged.get(k)
474
368
  merged.set(k, strategy === 'extend-arrays' && Array.isArray(prev) && Array.isArray(v) ? [...prev, ...v] : v)
@@ -477,16 +371,11 @@ function mergeExtended(base, local, strategy) {
477
371
  return out
478
372
  }
479
373
 
480
- // forge's `Extends`: a path, or `{ path, strategy? }`.
481
374
  const EXTEND_STRATEGIES = new Set(['extend-arrays', 'replace-arrays', 'no-collision'])
482
375
  const isExtends = (v) => typeof v === 'string'
483
376
  || (isTomlTable(v) && typeof v.path === 'string' && (v.strategy === undefined || EXTEND_STRATEGIES.has(v.strategy)))
484
377
 
485
- // A foundry.toml's profiles, with the selected profile's `extends` base merged in (forge's
486
- // `TomlFileProvider`). `files` lists what was read; `topLevel` is the file's own (see
487
- // parseFoundryToml). Throws where forge refuses the config, and where `refused` (a dependency's
488
- // config: see findNestedFoundryRemappings) gives a reason not to read the file or its base: a
489
- // dependency's config may not read the project's files. Messages name files `show(file)`.
378
+ // Forge's `TomlFileProvider`. Throws where forge refuses the config, or `refused` refuses the file or its base.
490
379
  function readFoundryProfiles(file, profile, { refused = () => null, show, host }) {
491
380
  const name = show(file)
492
381
  const refusal = refused(file)
@@ -499,8 +388,7 @@ function readFoundryProfiles(file, profile, { refused = () => null, show, host }
499
388
  if (ext !== undefined) {
500
389
  if (!isExtends(ext)) throw new Error(`${name}: \`extends\` must be a path, or a table with a \`path\` and an optional \`strategy\` (${[...EXTEND_STRATEGIES].join(', ')})`)
501
390
  const { path: extPath, strategy = 'extend-arrays' } = typeof ext === 'string' ? { path: ext } : ext
502
- // Joined as forge joins it, not normalized: the read resolves a `..` after a symlink the way
503
- // forge's does (from where the link leads), not textually.
391
+ // Joined, not normalized: the read resolves a `..` after a symlink as forge's does, from where the link leads.
504
392
  const baseFile = rustJoin(posix.dirname(file), extPath)
505
393
  const baseRefusal = refused(baseFile)
506
394
  if (baseRefusal) throw new ConfigRefused(`${name}: refusing to extend ${extPath}: ${baseRefusal}`)
@@ -521,41 +409,29 @@ function readFoundryProfiles(file, profile, { refused = () => null, show, host }
521
409
  return { profiles, topLevel, files }
522
410
  }
523
411
 
524
- // `[profile.default]` overlaid with the selected profile (a missing selected profile falls back to
525
- // the default, as forge does for dependency configs).
526
- function selectProfile(profiles, profile) {
527
- const dict = new Map(profiles.get('default') ?? [])
528
- if (profile !== 'default') for (const [k, v] of profiles.get(profile) ?? []) dict.set(k, v)
529
- return dict
530
- }
412
+ // A missing selected profile falls back to the default, as forge does for dependency configs.
413
+ const selectProfile = (profiles, profile) => new Map([...(profiles.get('default') ?? []), ...(profiles.get(profile) ?? [])])
531
414
 
532
- // The `remappings` a foundry.toml's profiles set for `profile` (`[profile.default]` overlaid by
533
- // it), else the file's top-level `remappings` (a mapping file written for stasis), as written; an
534
- // invalid one throws (configRemappings, naming `file`).
415
+ // Else the file's top-level `remappings` (a mapping file written for stasis).
535
416
  function profileRemappings({ profiles, topLevel }, profile, file = null) {
536
417
  const value = selectProfile(profiles, profile).get('remappings') ?? topLevel.get('remappings')
537
418
  return value === undefined ? [] : configRemappings(value, file)
538
419
  }
539
420
 
540
- // A foundry.toml text's own remappings for `profile` (see profileRemappings).
541
421
  export function foundryTomlRemappings(text, profile = 'default') {
542
422
  return profileRemappings(parseFoundryToml(text), profile)
543
423
  }
544
424
 
545
- // The same for a foundry.toml file, with its `extends` base: what `--mapping=foundry.toml` takes.
546
- // `files` lists what was read; `profiled` whether the selected `profile` is one of the file's.
547
- // Messages name files `show(file)`.
425
+ // What `--mapping=foundry.toml` takes; `profiled`: whether the selected `profile` is one of the file's.
548
426
  export function readFoundryTomlRemappings(file, profile, { show, host = diskHost }) {
549
427
  const abs = toPosix(resolve(file))
550
428
  const read = readFoundryProfiles(abs, profile, { show, host })
551
429
  return { remappings: profileRemappings(read, profile, show(abs)), files: read.files, profiled: hasProfile(read.profiles, profile) }
552
430
  }
553
431
 
554
- // Whether the selected `profile` is one of `profiles` (not the default, which always applies).
555
432
  const hasProfile = (profiles, profile) => profile !== 'default' && profiles.has(profile)
556
433
 
557
- // hasProfile, for the root foundry.toml: one that isn't there is warned about (forge uses
558
- // `[profile.default]` for it).
434
+ // For the root foundry.toml: a profile that isn't there is warned about.
559
435
  function profileApplies(profiles, profile) {
560
436
  if (profile !== 'default' && !profiles.has(profile)) {
561
437
  console.warn(`[loader.solidity] FOUNDRY_PROFILE=${profile} is not a profile in foundry.toml; using [profile.default]`)
@@ -563,21 +439,15 @@ function profileApplies(profiles, profile) {
563
439
  return hasProfile(profiles, profile)
564
440
  }
565
441
 
566
- // `ProjectPathsConfig::find_source_dir`: `src` unless only `contracts` exists.
442
+ // `ProjectPathsConfig::find_source_dir`.
567
443
  const findSourceDir = (root, host) => (isDir(rustJoin(root, 'src'), host) || !isDir(rustJoin(root, JS_SRC_DIR), host) ? 'src' : JS_SRC_DIR)
568
444
 
569
445
  // `DappHardhatDirProvider`: `lib` and/or `node_modules`, whichever exist (`lib` when neither).
570
446
  function detectLibs(root, host) {
571
- const nm = isDir(rustJoin(root, 'node_modules'), host)
572
- const lib = isDir(rustJoin(root, 'lib'), host)
573
- if (!nm) return ['lib']
574
- return lib ? ['lib', 'node_modules'] : ['node_modules']
447
+ if (!isDir(rustJoin(root, 'node_modules'), host)) return ['lib']
448
+ return isDir(rustJoin(root, 'lib'), host) ? ['lib', 'node_modules'] : ['node_modules']
575
449
  }
576
450
 
577
- // The selected profile's settings for a Foundry project at `root` (absolute POSIX), defaults
578
- // filled in the way forge fills them. `remappings` are the profile's own, unnormalized; an invalid
579
- // one throws (configRemappings). `refused`, `show` (from the root by default), `host`: see
580
- // readFoundryProfiles.
581
451
  function loadFoundryConfig(root, profile, { refused, host, show = shownFrom(root, host) }) {
582
452
  const file = rustJoin(root, FOUNDRY_TOML)
583
453
  const name = show(file)
@@ -602,10 +472,7 @@ function loadFoundryConfig(root, profile, { refused, host, show = shownFrom(root
602
472
  }
603
473
  }
604
474
 
605
- // --- The remappings provider ----------------------------------------------------------------
606
-
607
- // `foundry_toml_dir_entries`: `dir` and its direct subdirs (symlinks resolved) that hold a
608
- // foundry.toml, as `{ canonical, path, isSymlink }`.
475
+ // `foundry_toml_dir_entries`: `dir` and its direct subdirs (symlinks resolved) that hold a foundry.toml.
609
476
  function foundryTomlDirEntries(dir, host) {
610
477
  const out = []
611
478
  const consider = (path, isSymlink) => {
@@ -626,30 +493,24 @@ function rebaseNested(r, canonical, lexical) {
626
493
  return rest === null ? v : rustJoin(lexical, rest)
627
494
  }
628
495
  const out = { ...r, path: rebase(r.path) }
629
- if (r.context !== null) {
630
- const boundary = r.context.endsWith('/')
631
- let context
632
- if (isAbs(r.context)) {
633
- context = rebase(r.context)
634
- } else {
635
- const parts = []
636
- for (const c of normalComps(rustJoin(lexical, r.context))) {
637
- if (c === '..') parts.pop()
638
- else parts.push(c)
639
- }
640
- context = `/${parts.join('/')}`
496
+ if (r.context === null) return out
497
+ let context
498
+ if (isAbs(r.context)) {
499
+ context = rebase(r.context)
500
+ } else {
501
+ const parts = []
502
+ for (const c of normalComps(rustJoin(lexical, r.context))) {
503
+ if (c === '..') parts.pop()
504
+ else parts.push(c)
641
505
  }
642
- out.context = boundary ? withTrailing(context) : context
506
+ context = `/${parts.join('/')}`
643
507
  }
508
+ out.context = r.context.endsWith('/') ? withTrailing(context) : context
644
509
  return out
645
510
  }
646
511
 
647
- // A dependency's config as forge's `load_nested_config` reads it: remappings rebased onto its
648
- // canonical root, its remappings.txt, its src and libs. Null when forge would reject the config,
649
- // or when `refused` refuses it or its `extends` base (warned: ConfigRefused); a remappings.txt it
650
- // refuses is skipped (warned). One that isn't TOML or holds an invalid remapping throws: forge
651
- // refuses a bad remappings.txt line too, and skips a foundry.toml it can't read, which here is an
652
- // error rather than a config quietly left out. `refused`, `show`: see readFoundryProfiles.
512
+ // Forge's `load_nested_config`, remappings rebased onto the canonical root; null (warned) where forge
513
+ // rejects it or `refused` refuses it. One that isn't TOML throws, where forge would quietly skip it.
653
514
  function loadNestedConfig(canonical, profile, { refused, show, host }) {
654
515
  let config
655
516
  try {
@@ -661,7 +522,7 @@ function loadNestedConfig(canonical, profile, { refused, show, host }) {
661
522
  }
662
523
  const txt = rustJoin(canonical, REMAPPINGS_TXT)
663
524
  const txtName = show(txt)
664
- const refusal = refused(txt) // (null when nothing is there)
525
+ const refusal = refused(txt)
665
526
  if (refusal) console.warn(`[loader.solidity] Skipping a dependency's ${txtName}: ${refusal}`)
666
527
  const text = refusal ? null : readUtf8OrNull(txt, txtName, host)
667
528
  return {
@@ -674,28 +535,20 @@ function loadNestedConfig(canonical, profile, { refused, show, host }) {
674
535
  }
675
536
  }
676
537
 
677
- // `find_nested_foundry_remappings`: `[lexicalLibPath, remapping, isPackageEntry]` for every
678
- // dependency (transitively, through each one's own libs) that is a Foundry project. A dependency's
679
- // config reads only its own files and other dependencies' (by real path: `ownership`, see
680
- // solidityOwnership), as forge would find them from its lexical path.
538
+ // `find_nested_foundry_remappings`: `[lexicalLibPath, remapping, isPackageEntry]`. A dependency's config
539
+ // reads only its own files and other dependencies' (by real path: `ownership`).
681
540
  function findNestedFoundryRemappings(root, libPaths, profile, files, ownership, host) {
682
541
  const canonicalRoot = canonicalize(root, host) ?? root
683
542
  const shown = shownFrom(root, host, canonicalRoot)
684
- // A dependency's file (a path from its canonical dir) under its lexical path: where the bundle
685
- // sees it, and how messages name it.
543
+ // A dependency's file under its lexical path: where the bundle sees it, and how messages name it.
686
544
  const lexical = (entry, file) => rustJoin(entry.path, stripPrefix(file, entry.canonical) ?? file)
687
- // Why the config of the dependency at `entry` may not read `file` (a path from its canonical
688
- // dir), or null: judged by the path from the root, the lexical one or else the canonical one (an
689
- // absolute lib, `/proc/self/cwd/...`). It may read its own files and other dependencies'; a
690
- // dependency outside the root reads nothing, and one a dependency's `libs` named must be a
691
- // dependency itself (not the project's own dir passed off as one). Nothing there (the OS agrees:
692
- // solidityOwnership) is left for the read to find missing.
545
+ // Why the dependency at `entry` may not read `file`, judged from the root by its lexical, else
546
+ // canonical path; one a dependency's `libs` named must be a dependency itself.
693
547
  const refused = (entry) => (file) => {
694
548
  const dir = stripPrefix(entry.path, root) ?? stripPrefix(entry.canonical, canonicalRoot)
695
549
  if (dir === null) return 'the dependency lies outside the project root'
696
550
  if (entry.viaDependency && !ownership.of(dir).dependency) return `${dir}, which a dependency's \`libs\` names, isn't a dependency`
697
- // `file` as joined under the dependency's dir (an `extends` path unnormalized, for the walk to
698
- // resolve as the read does); one not under it (an absolute path elsewhere) lies outside it.
551
+ // `file` is as joined (an `extends` path unnormalized, for the walk to resolve as the read does).
699
552
  if (!file.startsWith(`${entry.canonical}/`)) return 'it lies outside the dependency'
700
553
  const o = ownership.of(`${dir}/${file.slice(entry.canonical.length + 1)}`)
701
554
  if (o.reason) return o.reason
@@ -712,11 +565,7 @@ function findNestedFoundryRemappings(root, libPaths, profile, files, ownership,
712
565
  const configs = new Map()
713
566
  const out = []
714
567
  while (pending.size > 0) {
715
- let key
716
- let entry
717
- for (const [k, e] of pending) {
718
- if (entry === undefined || cmpEntry(e, entry) < 0) [key, entry] = [k, e]
719
- }
568
+ const [key, entry] = [...pending].reduce((min, e) => (cmpEntry(e[1], min[1]) < 0 ? e : min))
720
569
  pending.delete(key)
721
570
  if (entry.canonical === canonicalRoot) continue
722
571
  if (!configs.has(entry.canonical)) {
@@ -744,8 +593,7 @@ function findNestedFoundryRemappings(root, libPaths, profile, files, ownership,
744
593
  return out
745
594
  }
746
595
 
747
- // `configured_auto_remapping`: an auto-detected alias a dependency's config redirects (its
748
- // synthesized `<dep>/<src>/` entry) takes that target.
596
+ // `configured_auto_remapping`: an auto-detected alias a dependency's config redirects takes that target.
749
597
  function configuredAutoRemapping(r, packageEntries) {
750
598
  let best = null
751
599
  for (const [lib, configured] of packageEntries) {
@@ -762,8 +610,7 @@ function configuredAutoRemapping(r, packageEntries) {
762
610
  return best === null ? r : { ...r, path: best.configured.path }
763
611
  }
764
612
 
765
- // `contextual_overlays`: null when an applicable authoritative alias already covers the
766
- // refinement; else the authoritative aliases below it, re-scoped to the refinement's context.
613
+ // `contextual_overlays`: null when an applicable authoritative alias already covers the refinement.
767
614
  function contextualOverlays(authoritative, refinement) {
768
615
  const applicable = authoritative.filter((m) => m.context === null || (refinement.context !== null && pathStartsWith(refinement.context, m.context)))
769
616
  if (applicable.some((m) => nameIsPrefix(m.name, refinement.name))) return null
@@ -773,8 +620,7 @@ function contextualOverlays(authoritative, refinement) {
773
620
  .map((m) => ({ ...m, context: refinement.context }))
774
621
  }
775
622
 
776
- // `expand_scoped_contextual_remapping`: a contextual `@scope/=<..>/node_modules/@scope/` becomes
777
- // one remapping per package in the scope.
623
+ // `expand_scoped_contextual_remapping`: one remapping per package of a `node_modules/@scope/`.
778
624
  function expandScopedContextual(r, host) {
779
625
  const scope = trimSlashes(r.name)
780
626
  if (!scope.startsWith('@') || fileName(r.path) !== scope || fileName(parentOf(r.path) ?? '') !== 'node_modules') return [r]
@@ -794,7 +640,6 @@ function insertClosest(m, key, path) {
794
640
  }
795
641
  }
796
642
 
797
- // A refinement with the authoritative aliases it overlays, or nothing when one already covers it.
798
643
  const withOverlays = (authoritative, r) => {
799
644
  const overlays = contextualOverlays(authoritative, r)
800
645
  return overlays ? [...overlays, r] : []
@@ -807,25 +652,18 @@ function providerRemappings(root, { userRemappings, libs, autoDetect, profile, f
807
652
  if (!autoDetect) return all.intoInner()
808
653
 
809
654
  const nested = findNestedFoundryRemappings(root, libs, profile, files, ownership, host)
810
- const auto = { global: [], contextual: [] }
811
- for (const lib of libs) {
812
- const found = findRemappingsWithContext(rustJoin(root, lib), host)
813
- auto.global.push(...found.global)
814
- auto.contextual.push(...found.contextual)
815
- }
655
+ const auto = libs.map((lib) => findRemappingsWithContext(rustJoin(root, lib), host))
816
656
 
817
657
  const packageEntries = nested.filter(([, , pkg]) => pkg)
818
- const safeAlias = (r) => !['lib/', 'src/', 'contracts/'].includes(r.name)
819
- const global = auto.global.map((r) => configuredAutoRemapping(r, packageEntries)).filter(safeAlias)
820
- const contextual = auto.contextual.map((r) => configuredAutoRemapping(r, packageEntries)).filter(safeAlias)
658
+ const configured = (rs) => rs.map((r) => configuredAutoRemapping(r, packageEntries)).filter((r) => !['lib/', 'src/', 'contracts/'].includes(r.name))
659
+ const global = configured(auto.flatMap((found) => found.global))
660
+ const contextual = configured(auto.flatMap((found) => found.contextual))
821
661
  const detected = [...global, ...contextual]
822
662
 
823
- const targetsByAlias = new Map()
824
- for (const r of detected) {
825
- if (!targetsByAlias.has(r.name)) targetsByAlias.set(r.name, new Set())
826
- targetsByAlias.get(r.name).add(pathKey(r.path))
663
+ const ambiguous = new Set()
664
+ for (const [name, rs] of Map.groupBy(detected, (r) => r.name)) {
665
+ if (new Set(rs.map((r) => pathKey(r.path))).size > 1) ambiguous.add(name)
827
666
  }
828
- const ambiguous = new Set([...targetsByAlias].filter(([, t]) => t.size > 1).map(([name]) => name))
829
667
 
830
668
  const explicitContextual = nested.filter(([, r]) => r.context !== null).flatMap(([, r]) => withOverlays(authoritativeUser, r))
831
669
  const authoritative = [...authoritativeUser, ...explicitContextual]
@@ -854,12 +692,7 @@ function providerRemappings(root, { userRemappings, libs, autoDetect, profile, f
854
692
  return all.intoInner()
855
693
  }
856
694
 
857
- // The lib dirs `forge build` uses for the Foundry project at `baseDir`, `{ libs, profiled, files }`:
858
- // the selected profile's `libs` (`profiled` when that profile is the file's), else the detected
859
- // ones; also those, warned, when forge would reject the foundry.toml's settings (ConfigRefused; with
860
- // a pinned mapping file, nothing else is read from it). `files` lists the config files read (the
861
- // foundry.toml, its `extends` base). A foundry.toml that isn't TOML or holds an invalid remapping
862
- // throws.
695
+ // The detected lib dirs, warned, where forge would reject the foundry.toml's settings (a pinned mapping file reads nothing else).
863
696
  export function foundryLibs(baseDir, { env = process.env, host = diskHost } = {}) {
864
697
  const root = toPosix(resolve(baseDir))
865
698
  const profile = foundryProfile(env)
@@ -873,18 +706,11 @@ export function foundryLibs(baseDir, { env = process.env, host = diskHost } = {}
873
706
  }
874
707
  }
875
708
 
876
- // The source directory of the Foundry project at `baseDir`: its default profile's `src`, else
877
- // forge's (`src` unless only `contracts` exists).
878
709
  export function foundrySourceDir(baseDir, { host = diskHost } = {}) {
879
710
  return loadFoundryConfig(toPosix(resolve(baseDir)), 'default', { host }).src
880
711
  }
881
712
 
882
- // The Foundry project at `baseDir`: what `forge build` would use. `remappings` are
883
- // `{ context, prefix, target }` relative to the root, in forge's order; `libs` the lib dirs;
884
- // `files` the config files read (project-relative, `../` when outside the project); `envUsed` the
885
- // environment variables that shaped them; `ownership` its files' owners (see solidityOwnership),
886
- // which also confines what a dependency's config reads. `env` supplies FOUNDRY_PROFILE and
887
- // FOUNDRY_REMAPPINGS / DAPP_REMAPPINGS.
713
+ // `remappings` relative to the root, in forge's order; `envUsed`: the env vars that shaped them.
888
714
  export function foundryProject(baseDir, { env = process.env, host = diskHost } = {}) {
889
715
  const root = toPosix(resolve(baseDir))
890
716
  const profile = foundryProfile(env)
@@ -903,20 +729,16 @@ export function foundryProject(baseDir, { env = process.env, host = diskHost } =
903
729
  const provided = providerRemappings(root, { userRemappings, libs: config.libs, autoDetect: config.autoDetect, profile, files, ownership, host })
904
730
  .map((r) => displayRelative(relativePreservingBoundary(r, root)))
905
731
 
906
- // `forge build` re-reads them as config remappings, dropping aliases of its own input dirs.
732
+ // `forge build` re-reads them as config remappings, dropping aliases of its own input dirs...
907
733
  const build = new Remappings([], [config.src, config.test, config.script].map((p) => `${p}/`))
908
- for (const s of provided) {
909
- const r = parseRemapping(s)
910
- if (r) build.push(r)
911
- }
734
+ for (const r of provided.map((s) => parseRemapping(s)).filter(Boolean)) build.push(r)
912
735
  // ...and hands them to solc as the config's `RelativeRemapping`s: slash-terminated.
913
736
  const remappings = build.intoInner()
914
737
  .map((r) => parseRemapping(displayRelative(relativePreservingBoundary(r, root))))
915
738
  .filter(Boolean)
916
739
  .map(toSolcRemapping)
917
740
 
918
- // One read from outside the root (an `extends = "../base.toml"`) stays `../`, for --manifests to
919
- // refuse (it can't be carried).
741
+ // One read from outside the root (`extends = "../base.toml"`) stays `../`, for --manifests to refuse.
920
742
  const relFiles = [...files].map((f) => projectRelative(root, f, host))
921
743
  const envUsed = [...(profiled ? [`FOUNDRY_PROFILE=${env.FOUNDRY_PROFILE}`] : []), ...(envName === null ? [] : [envName])]
922
744
  return { remappings, libs: config.libs, files: relFiles, envUsed, ownership }