@exodus/stasis 1.0.0-beta.8 → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +7 -2
  2. package/bin/stasis.js +263 -446
  3. package/package.json +38 -13
  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 +1718 -908
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +48 -21
  15. package/src/cmd/output.js +24 -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 +221 -475
  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 +170 -235
  44. package/src/resolve-node.js +33 -46
  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 +241 -278
  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 +54 -46
  57. package/src/vfs-bundle/github.js +115 -92
  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 +434 -259
  63. package/src/vfs-bundle/yarnclean.js +79 -0
  64. package/src/vfs-bundle.js +25 -51
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +79 -231
@@ -1,16 +1,7 @@
1
- // Based on DeepView's Solidity loader.
2
- // https://github.com/PreventiveMeasures/deepview/blob/main/src/loaders/solidity.js
3
- // Produces a `{ sources, resolutions }` pair. Imports resolve the way solc does under the project's
4
- // build tool: remappings (discovered the way `forge build` does for a Foundry project, see
5
- // foundry.js), then a Foundry library's include path, solc's base path (the project root), and
6
- // Hardhat's/Node's node_modules lookup. The mapping/config files are read, not added to `sources`.
7
- // Dependencies are untrusted input: an import only ever reaches a `.sol` file inside the project,
8
- // a dependency's imports only its own and other dependencies' files (by real path), and nothing
9
- // is read through a link a dependency planted out of itself (solidityOwnership). The project is read
10
- // through a `host` (@exodus/stasis-core/host), the disk's by default.
1
+ // Based on DeepView's Solidity loader (https://github.com/PreventiveMeasures/deepview/blob/main/src/loaders/solidity.js).
2
+ // Dependencies are untrusted: an import never leaves the project nor crosses a link one plants (solidityOwnership).
11
3
 
12
- import { readFile } from 'node:fs/promises'
13
- import { dirname, isAbsolute, join, posix, relative, resolve } from 'node:path'
4
+ import { isAbsolute, join, posix, relative, resolve } from 'node:path'
14
5
 
15
6
  import { diskHost } from '@exodus/stasis-core/host'
16
7
  import { assertRealPathWithinBase, relativeEscapes, toPosix } from '@exodus/stasis-core/util'
@@ -21,19 +12,15 @@ import {
21
12
  foundryLibs,
22
13
  foundryProfile,
23
14
  foundryProject,
24
- foundryTomlRemappings,
25
15
  parseRemappingLines,
26
16
  readFoundryTomlRemappings,
27
17
  shownFrom,
28
18
  toSolcRemapping,
29
19
  } from './foundry.js'
20
+ import { applyToDir, isDotRelative } from './paths.js'
30
21
  import { decodeUtf8, projectOwnership, projectRelative, readUtf8OrNull, realpathOrNull, solidityOwnership } from './solidity-ownership.js'
31
- import { assertWithinBase } from './paths.js'
32
22
 
33
- // --- Import scan ------------------------------------------------------------------------------
34
-
35
- // The scan's ASCII classes, by char code: identifier start [A-Za-z_$], identifier part [\w$], digit,
36
- // and a number literal's [\w.].
23
+ // By char code: identifier start [A-Za-z_$], identifier part [\w$], digit, and a number literal's [\w.].
37
24
  const isIdentStart = (c) => (c >= 97 && c <= 122) || (c >= 65 && c <= 90) || c === 95 || c === 36
38
25
  const isDigit = (c) => c >= 48 && c <= 57
39
26
  const isIdentPart = (c) => isIdentStart(c) || isDigit(c)
@@ -42,9 +29,8 @@ const STRING_ESCAPES = { n: '\n', r: '\r', t: '\t', b: '\b', f: '\f', v: '\v', 0
42
29
 
43
30
  const utf8 = (s) => [...Buffer.from(s, 'utf8')]
44
31
 
45
- // A string literal starting at `text[i]` (a quote): `{ value, end }`, `value` null when it's
46
- // unterminated on its line (solc rejects those). A literal is bytes, as in solc: `\xNN` is one
47
- // byte, `\uNNNN` and plain text their UTF-8, and the path is those bytes read as UTF-8.
32
+ // `value` null where unterminated on its line, as solc rejects it. A literal is bytes, as in solc: `\xNN` one
33
+ // byte, `\uNNNN` and plain text their UTF-8, and the path those bytes read as UTF-8.
48
34
  function readStringLiteral(text, i) {
49
35
  const quote = text.charCodeAt(i)
50
36
  let bytes = null // set at the first escape; until then the literal is a plain slice
@@ -86,11 +72,7 @@ function readStringLiteral(text, i) {
86
72
  return { value: null, end: j }
87
73
  }
88
74
 
89
- // The path of every import directive, in source order. The text is tokenized far enough to skip
90
- // comments and string literals, so a commented-out `// import "./Old.sol";` or a string holding
91
- // the word `import` is never taken for one. An import is the `import` keyword followed, before its
92
- // `;`, by the path literal: `import "p";`, `import "p" as X;`, `import * as X from "p";`,
93
- // `import {A, B as C} from "p";` -- over any number of lines.
75
+ // Tokenized far enough that a commented-out import, or a string holding the word, is never taken for one.
94
76
  export function extractSolImports(content) {
95
77
  const specs = []
96
78
  const n = content.length
@@ -130,29 +112,11 @@ export function extractSolImports(content) {
130
112
  return specs
131
113
  }
132
114
 
133
- // --- Remappings ---------------------------------------------------------------------------------
134
-
135
- // Loader-side shape: `{ context, prefix, target }` (context null = global).
136
115
  const toLoaderRemapping = ({ context, name, path }) => ({ context, prefix: name, target: path })
137
116
 
138
- // remappings.txt text -> remappings as written, one `[context:]prefix=target` per line (lines
139
- // trimmed, blank ones skipped; an empty target is solc's, valid). A line that isn't one throws.
140
- export function parseRemappings(content) {
141
- return parseRemappingLines(content, { emptyPath: true }).map(toLoaderRemapping)
142
- }
143
-
144
- // foundry.toml text -> the `remappings` of `[profile.default]`, overlaid by the selected profile's
145
- // (FOUNDRY_PROFILE in `env`) when it sets them.
146
- export function parseRemappingsFromToml(tomlContent, { env = process.env } = {}) {
147
- return foundryTomlRemappings(tomlContent, foundryProfile(env)).map(toLoaderRemapping)
148
- }
149
-
150
- // Read a mapping file -> its remappings as listed (no discovery around it) and the files read. A
151
- // foundry.toml (its selected profile, with its `extends` base) is forge's, and so is a
152
- // remappings.txt when `forge` says forge reads it: slash-terminated the way forge reads them.
153
- // Otherwise (solc, Hardhat) a remappings.txt applies as written. Messages name files `show(file)`;
154
- // files are read through `host`.
155
- function readMapping(mappingFile, { env, forge, host, show = (f) => f }) {
117
+ // A foundry.toml's and, with `forge`, a remappings.txt's are slash-terminated as forge reads them; else (solc,
118
+ // Hardhat) a remappings.txt applies as written.
119
+ function readMapping(mappingFile, { env, forge, host, show }) {
156
120
  if (mappingFile.endsWith('.toml')) {
157
121
  const { remappings, files, profiled } = readFoundryTomlRemappings(mappingFile, foundryProfile(env), { show, host })
158
122
  return { remappings: remappings.map(toSolcRemapping), files, profiled }
@@ -164,26 +128,8 @@ function readMapping(mappingFile, { env, forge, host, show = (f) => f }) {
164
128
  return { remappings: listed.map(forge ? toSolcRemapping : toLoaderRemapping), files: [mappingFile] }
165
129
  }
166
130
 
167
- // Read a foundry.toml/remappings.txt mapping file -> its remappings (see readMapping; `forge`
168
- // defaults to a remappings.txt applying as written). The file itself is not added to sources.
169
- export function readRemappingsFile(mappingFile, { env = process.env, forge = false, host = diskHost } = {}) {
170
- return readMapping(mappingFile, { env, forge, host }).remappings
171
- }
172
-
173
- // --- Resolution ---------------------------------------------------------------------------------
174
-
175
- // What resolves the imports of the project at `baseDir`:
176
- // `{ remappings, libs, ownership, files, envUsed }`.
177
- // - `mappingFile` (foundry.toml / remappings.txt): exactly the remappings it lists (see readMapping).
178
- // - else, with a foundry.toml at the root: what `forge build` uses (foundry.js) -- remappings.txt,
179
- // the profile's remappings, dependencies' own configs, auto-detected `lib/` remappings and their
180
- // contexts.
181
- // - else a remappings.txt at the root (solc / Hardhat 3), taken as written.
182
- // `libs` are forge's lib dirs whenever the root has a foundry.toml (an absolute import inside a
183
- // library resolves against it); `ownership` tells the dependencies' files from the project's
184
- // (solidityOwnership: forge's libs, Soldeer's `dependencies/`, git submodules, node_modules);
185
- // `files` the project-relative config files read (`../` for one outside the project); `envUsed`
186
- // the environment variables that shaped the result. The project is read through `host`.
131
+ // The remappings `mappingFile` lists, else what `forge build` uses with a foundry.toml at the root, else a
132
+ // root remappings.txt as written.
187
133
  export function discoverSolidityConfig(baseDir, { mappingFile, env = process.env, host = diskHost } = {}) {
188
134
  const forge = isFile(join(baseDir, FOUNDRY_TOML), host)
189
135
  if (forge && !mappingFile) return foundryProject(baseDir, { env, host })
@@ -193,8 +139,7 @@ export function discoverSolidityConfig(baseDir, { mappingFile, env = process.env
193
139
  if (mappingFile) {
194
140
  const abs = resolve(baseDir, mappingFile)
195
141
  const { remappings, files, profiled: mappingProfiled } = readMapping(abs, { env, forge, host, show })
196
- // The profile picks the mapping file's remappings (a .toml) or the root foundry.toml's libs: the
197
- // files read are both's.
142
+ // The profile picks the mapping file's remappings (a .toml) or the root foundry.toml's libs.
198
143
  const envUsed = profiled || mappingProfiled ? [`FOUNDRY_PROFILE=${env.FOUNDRY_PROFILE}`] : []
199
144
  return { remappings, libs, ownership, files: [...new Set([...files, ...libsFiles].map((f) => projectRelative(baseDir, f, host)))], envUsed }
200
145
  }
@@ -203,10 +148,8 @@ export function discoverSolidityConfig(baseDir, { mappingFile, env = process.env
203
148
  return { remappings: readMapping(txt, { env, forge, host, show }).remappings, libs, ownership, files: [REMAPPINGS_TXT], envUsed: [] }
204
149
  }
205
150
 
206
- // Solc's remapping choice for the source unit `name` imported from `fromFile`: among the
207
- // remappings whose context is a prefix of `fromFile` and whose prefix is a prefix of `name`, the
208
- // longest context wins, then the longest prefix, then the one listed last. The target replaces the
209
- // prefix verbatim (`//` collapsed). Null when none applies.
151
+ // As solc remaps: of those whose context and prefix match, the longest context wins, then the longest prefix,
152
+ // then the one listed last; its target replaces the prefix verbatim (`//` collapsed).
210
153
  export function applyRemappings(name, fromFile, remappings) {
211
154
  let best = null
212
155
  for (const r of remappings) {
@@ -219,29 +162,6 @@ export function applyRemappings(name, fromFile, remappings) {
219
162
  return posix.normalize(best.target + name.slice(best.prefix.length)).replace(/^\.\//u, '')
220
163
  }
221
164
 
222
- // A relative import (first segment `.` or `..`) as solc resolves it: against the importing file's
223
- // directory. Null when it climbs above the root: solc clamps there (`../../B.sol` from `src/A.sol`
224
- // is `B.sol`), but an import reaching out of the project is refused rather than redirected.
225
- function resolveRelativeImport(specifier, fromFile) {
226
- const resolved = fromFile.includes('/') ? fromFile.slice(0, fromFile.lastIndexOf('/')).split('/') : []
227
- for (const part of specifier.split('/')) {
228
- if (part === '.' || part === '') continue
229
- if (part === '..') {
230
- if (resolved.length === 0) return null
231
- resolved.pop()
232
- } else {
233
- resolved.push(part)
234
- }
235
- }
236
- return resolved.join('/')
237
- }
238
-
239
- const isRelativeImport = (specifier) => {
240
- const first = specifier.split('/')[0]
241
- return first === '.' || first === '..'
242
- }
243
-
244
- // `<baseDir>/<spec>` when a real file sits there, as a clean project-relative path.
245
165
  function projectFile(baseDir, spec, host) {
246
166
  if (isAbsolute(spec)) return null
247
167
  const rel = toPosix(relative(baseDir, resolve(baseDir, spec)))
@@ -252,10 +172,8 @@ function projectFile(baseDir, spec, host) {
252
172
  // No `.`/`..`/empty segment: a bare spec can't wander out of the directory it's looked up in.
253
173
  const isPlainSpec = (spec) => spec.split('/').every((p) => p !== '' && p !== '.' && p !== '..')
254
174
 
255
- // Forge's absolute import inside a library (`lib/dep/src/A.sol` importing `src/B.sol`): tried
256
- // against each directory from the parent of the importer's up to (not including) its lib dir, as
257
- // foundry-compilers' `resolve_absolute_library` does; forge passes the matching one to solc as an
258
- // include path.
175
+ // Forge's absolute import inside a library (`src/B.sol` from `lib/dep/src/A.sol`), as foundry-compilers'
176
+ // `resolve_absolute_library` finds it, forge passing the match to solc as an include path.
259
177
  function libraryFile(baseDir, spec, fromFile, libs, host) {
260
178
  const lib = libs.map((l) => posix.normalize(toPosix(l)).replace(/\/$/u, '')).find((l) => fromFile.startsWith(`${l}/`))
261
179
  if (!lib) return null
@@ -266,9 +184,7 @@ function libraryFile(baseDir, spec, fromFile, libs, host) {
266
184
  return null
267
185
  }
268
186
 
269
- // A package import (`pkg/path.sol`, `@scope/pkg/path.sol`) by file path through node_modules, from
270
- // the importing file's directory up to the root (Hardhat and Node; a package's `exports` map
271
- // doesn't apply to Solidity sources).
187
+ // As Hardhat and Node find a package's file; its `exports` map doesn't apply to Solidity sources.
272
188
  function nodeModulesFile(baseDir, spec, fromFile, host) {
273
189
  const parts = spec.split('/')
274
190
  if (parts.length < (spec.startsWith('@') ? 3 : 2)) return null
@@ -281,11 +197,12 @@ function nodeModulesFile(baseDir, spec, fromFile, host) {
281
197
  }
282
198
  }
283
199
 
284
- // Where an import resolves, as `{ path }`, or `{ reason }` when it may not be read (`reason: null`:
285
- // it names no file). See resolveSolImport.
200
+ // `{ reason: null }` for an import naming no file.
286
201
  function resolveImport(specifier, fromFile, { remappings = [], baseDir, libs = [], ownership, host = diskHost } = {}) {
287
- const relativeImport = isRelativeImport(specifier)
288
- const name = relativeImport ? resolveRelativeImport(specifier, fromFile) : specifier
202
+ const relativeImport = isDotRelative(specifier)
203
+ // solc clamps a relative import climbing above the root there, but one reaching out of the project is
204
+ // refused, not redirected.
205
+ const name = relativeImport ? applyToDir(fromFile, specifier.split('/')) : specifier
289
206
  if (name === null) return { reason: 'it climbs above the project root' }
290
207
  let path = applyRemappings(name, fromFile, remappings)
291
208
  if (path === null && relativeImport) path = name
@@ -305,35 +222,17 @@ function resolveImport(specifier, fromFile, { remappings = [], baseDir, libs = [
305
222
  return { path }
306
223
  }
307
224
 
308
- // Resolve a Solidity import to a baseDir-relative POSIX path, the way solc does: a relative import
309
- // (`./`, `../`) is taken against the importing file (root escape -> null), then remappings apply
310
- // (longest context, then longest prefix; see applyRemappings). An unremapped non-relative import
311
- // is then looked up, when `baseDir` is given, inside the importer's library (forge's include path;
312
- // `libs` are forge's lib dirs), as a project file (solc's base path), and through node_modules by
313
- // file path (Hardhat / Node). Returns null when nothing resolves, or when the result isn't a `.sol`
314
- // file inside the root, crosses a link a dependency planted out of itself, or is the project's own
315
- // file imported by a dependency's -- by real path, with `ownership` (solidityOwnership's; by default
316
- // only node_modules holds dependencies). The project is read through `host`.
317
- export function resolveSolImport(specifier, fromFile, options = {}) {
318
- return resolveImport(specifier, fromFile, options).path ?? null
319
- }
225
+ // Relative, remapped, then in the importer's library, the project, node_modules; null too where refused.
226
+ export const resolveSolImport = (specifier, fromFile, options = {}) => resolveImport(specifier, fromFile, options).path ?? null
320
227
 
321
- // The files that describe a Solidity build (bundled by `--manifests`) besides the config files
322
- // discovery read: the root's dependency pins, and each package's manifests. (`hardhat.config.*` is
323
- // code that may hold keys, so it is never carried.)
228
+ // Not `hardhat.config.*`, code that may hold keys.
324
229
  export const SOLIDITY_ROOT_MANIFESTS = [FOUNDRY_TOML, REMAPPINGS_TXT, 'foundry.lock', 'soldeer.lock', '.gitmodules', 'package.json']
325
230
  export const SOLIDITY_PACKAGE_MANIFESTS = ['package.json', FOUNDRY_TOML, REMAPPINGS_TXT]
326
231
 
327
- // --- The walk -----------------------------------------------------------------------------------
328
-
329
232
  const warnUnresolved = (spec, from, reason) =>
330
233
  console.warn(`[loader.solidity] ${reason ? 'Refused' : 'Missing'} import: ${spec} from ${from}${reason ? ` (${reason})` : ''}`)
331
234
 
332
- // Build `{ sources, resolutions, missing }` from already-loaded Solidity sources plus remappings.
333
- // Imports resolve as resolveSolImport does (`libs`, `ownership`, `host`: see there); as a final
334
- // fallback a specifier naming no file but matching a stored key verbatim is accepted. `missing`
335
- // lists every `{ spec, from }` that didn't resolve or resolved outside `sources`, with the
336
- // `reason` when it was refused.
235
+ // A specifier naming no file but a stored key verbatim resolves to it.
337
236
  export function buildSolidityTree(sources, { remappings = [], baseDir, libs = [], host = diskHost, ownership = baseDir && solidityOwnership(baseDir, { host }) } = {}) {
338
237
  const resolutions = new Map()
339
238
  const missing = []
@@ -342,11 +241,9 @@ export function buildSolidityTree(sources, { remappings = [], baseDir, libs = []
342
241
  const specMap = new Map()
343
242
  for (const spec of extractSolImports(content)) {
344
243
  const r = resolveImport(spec, path, options)
345
- let resolved = r.path && sources.has(r.path) ? r.path : null
346
- if (!resolved && !r.reason && sources.has(spec)) resolved = spec
347
- if (resolved) {
348
- specMap.set(spec, resolved)
349
- } else {
244
+ const resolved = r.path && sources.has(r.path) ? r.path : !r.reason && sources.has(spec) ? spec : null
245
+ if (resolved) specMap.set(spec, resolved)
246
+ else {
350
247
  warnUnresolved(spec, path, r.reason)
351
248
  missing.push(r.reason ? { spec, from: path, reason: r.reason } : { spec, from: path })
352
249
  }
@@ -356,11 +253,7 @@ export function buildSolidityTree(sources, { remappings = [], baseDir, libs = []
356
253
  return { sources, resolutions, missing }
357
254
  }
358
255
 
359
- // Walk the project from `entries`, following resolved imports and reading each file once, a wave at
360
- // a time: the files of one, then the imports they name. Caller-listed entries are also accepted as
361
- // verbatim non-relative import targets naming no file (Foundry-style `import "src/A.sol"`). An entry
362
- // that crosses a dependency's link out of itself (see solidityOwnership) is refused. The project is
363
- // read through `host`.
256
+ // Entries are taken as verbatim import targets naming no file too (Foundry-style `import "src/A.sol"`).
364
257
  export function collectSolidityFilesFromDisk(baseDir, entries, remappings, { libs = [], host = diskHost, ownership = solidityOwnership(baseDir, { host }) } = {}) {
365
258
  const sources = new Map()
366
259
  const knownEntries = new Set(entries)
@@ -381,18 +274,13 @@ export function collectSolidityFilesFromDisk(baseDir, entries, remappings, { lib
381
274
  }
382
275
  })
383
276
  const next = []
384
- for (const entry of reads) {
385
- if (!entry) continue
386
- const [relPath, content] = entry
277
+ for (const [relPath, content] of reads.filter(Boolean)) {
387
278
  sources.set(relPath, content)
388
279
  for (const spec of extractSolImports(content)) {
389
280
  const r = resolveImport(spec, relPath, options)
390
281
  const resolved = r.path ?? (!r.reason && knownEntries.has(spec) ? spec : null)
391
- if (resolved) {
392
- if (!sources.has(resolved)) next.push(resolved)
393
- } else {
394
- warnUnresolved(spec, relPath, r.reason)
395
- }
282
+ if (resolved) next.push(resolved)
283
+ else warnUnresolved(spec, relPath, r.reason)
396
284
  }
397
285
  }
398
286
  wave = next
@@ -400,15 +288,11 @@ export function collectSolidityFilesFromDisk(baseDir, entries, remappings, { lib
400
288
  return sources
401
289
  }
402
290
 
403
- // Every `.sol` file under the project-relative directory `dir`, sorted, symlinks followed as forge
404
- // (walkdir, `follow_links`) collects a source dir: a symlinked directory whose real path is one on
405
- // the current walk (the walk root included) is a loop and skipped; anything else is walked, so two
406
- // links to one directory are two directories. A dir's real path is its parent's plus its name
407
- // unless it's a symlink.
291
+ // Symlinks followed as forge's walkdir (`follow_links`) collects a source dir: a linked directory whose real
292
+ // path is on the current walk is a loop and skipped; two links to one directory are two directories.
408
293
  function solidityFilesUnder(baseDir, dir, host) {
409
294
  const out = []
410
- // The real paths of the directories on the current walk; one may repeat (a real directory
411
- // reached again through a link is walked, as walkdir does, and checked only at links).
295
+ // One may repeat: a real directory reached again through a link is walked, as walkdir does, checked only at links.
412
296
  const stack = []
413
297
  const walk = (rel, real) => {
414
298
  stack.push(real)
@@ -432,16 +316,12 @@ function solidityFilesUnder(baseDir, dir, host) {
432
316
  return out.toSorted()
433
317
  }
434
318
 
435
- // Project-relative entries with each directory replaced by the `.sol` files under it (deduped, in
436
- // order). A `.sol` entry is kept as is (a missing one is reported by the walk); a directory that
437
- // is missing or holds no `.sol` file is skipped with a warning, as forge skips an absent `script/`,
438
- // and it's an error only when no entry yields a file (when none exists, a mistyped path). The
439
- // project is read through `host`.
319
+ // A directory missing or holding no `.sol` file is skipped with a warning, as forge skips an absent `script/`.
440
320
  export function expandSolidityEntries(baseDir, entries, host = diskHost) {
441
321
  const out = new Set()
442
322
  const shown = (entry) => (entry === '.' ? './' : `${entry}/`)
443
- for (const e of entries) {
444
- const entry = e === '' ? '.' : e
323
+ const named = entries.map((e) => (e === '' ? '.' : e))
324
+ for (const entry of named) {
445
325
  const dir = isDir(join(baseDir, entry), host)
446
326
  if (!dir && entry.endsWith('.sol')) {
447
327
  out.add(entry)
@@ -453,33 +333,7 @@ export function expandSolidityEntries(baseDir, entries, host = diskHost) {
453
333
  }
454
334
  if (out.size === 0) {
455
335
  if (entries.every((e) => host.stat(join(baseDir, e)) === null)) throw new Error(`No such file or directory: ${entries[0]}`)
456
- throw new Error(`No .sol files under ${entries.map((e) => shown(e === '' ? '.' : e)).join(', ')} (a directory entry stands for the Solidity sources under it)`)
336
+ throw new Error(`No .sol files under ${named.map(shown).join(', ')} (a directory entry stands for the Solidity sources under it)`)
457
337
  }
458
338
  return [...out]
459
339
  }
460
-
461
- // High-level entry: a `.sol.txt` listing whose optional first line is a `*.toml`/`remappings.txt`
462
- // mapping file (resolved relative to the listing); the remaining lines are `*.sol` files. Without
463
- // a mapping line, the remappings are discovered as for `stasis bundle` (discoverSolidityConfig).
464
- export async function loadSolidity(solTxtFile, { env = process.env } = {}) {
465
- const baseDir = dirname(resolve(solTxtFile))
466
- const listing = decodeUtf8(await readFile(solTxtFile), solTxtFile)
467
- const lines = listing.split('\n').map((l) => l.trim()).filter(Boolean)
468
- if (lines.length === 0) throw new Error(`Empty Solidity listing: ${solTxtFile}`)
469
-
470
- let mappingFile
471
- if (lines[0].endsWith('.toml') || lines[0].endsWith('remappings.txt')) {
472
- mappingFile = lines.shift()
473
- assertWithinBase(baseDir, mappingFile, 'Mapping path')
474
- }
475
-
476
- if (!lines.every((line) => line.endsWith('.sol'))) {
477
- throw new Error(`Solidity listing must only contain .sol files: ${solTxtFile}`)
478
- }
479
-
480
- const entries = lines.map((l) => l.replace(/^\.\//u, ''))
481
- for (const e of entries) assertWithinBase(baseDir, e, 'Entry path')
482
- const { remappings, libs, ownership } = discoverSolidityConfig(baseDir, { mappingFile, env })
483
- const sources = collectSolidityFilesFromDisk(baseDir, entries, remappings, { libs, ownership })
484
- return buildSolidityTree(sources, { remappings, baseDir, libs, ownership })
485
- }
@@ -1,16 +1,11 @@
1
- // TOML for the build descriptions the loaders take -- Cargo.toml, Cargo.lock, foundry.toml -- read
2
- // by @preventive/lockfile's strict TOML 1.0 parser into a tree of tables, and refused where it
3
- // isn't TOML, or isn't the TOML those files are written in: a bad escape, an unterminated string, a
4
- // key or table defined twice, a local date, U+FFFD where a lenient decoder replaced bytes ... each a
5
- // TomlError naming the file and line, never a guessed value.
1
+ // TOML for Cargo.toml, Cargo.lock and foundry.toml, by @preventive/lockfile's strict TOML 1.0 parser:
2
+ // what isn't TOML is a TomlError naming the file and line, never a guessed value.
6
3
 
7
4
  import { TomlError, parseToml } from '@preventive/lockfile/toml.js'
8
5
 
9
6
  export { TomlError }
10
7
 
11
- // --- Bracket helpers (for the Rust scanner) ----------------------------------------------
12
-
13
- // Index of the bracket closing the one opened at `open`, or the last index when unbalanced.
8
+ // The index of the bracket closing the one at `open`; the last index when unbalanced.
14
9
  export function matchClose(text, open) {
15
10
  const close = { '[': ']', '(': ')', '{': '}' }[text[open]]
16
11
  let depth = 0
@@ -21,7 +16,7 @@ export function matchClose(text, open) {
21
16
  return text.length - 1
22
17
  }
23
18
 
24
- // Split on commas outside brackets/braces/parentheses/strings.
19
+ // Split on commas outside brackets, braces, parentheses and strings.
25
20
  export function splitTopLevel(text) {
26
21
  const parts = []
27
22
  let depth = 0
@@ -46,15 +41,10 @@ export function splitTopLevel(text) {
46
41
  return parts
47
42
  }
48
43
 
49
- // --- The reader -----------------------------------------------------------------------------
50
-
51
- // The table tree of TOML `text` (parseToml): tables are null-prototype objects, arrays arrays, and
52
- // values strings, booleans, numbers (an integer past 2^53 a BigInt), TomlFloat and TomlDateTime.
53
- // Throws a TomlError on anything else, naming `file` when given.
44
+ // Tables are null-prototype objects; an integer past 2^53 is a BigInt.
54
45
  export const readToml = (text, file = null) => nameErrors(file, () => parseToml(text))
55
46
 
56
- // `read()`, with an error of one of `classes` it throws (@preventive/lockfile's, whose message
57
- // leads with where it is) leading with `file` too, its fields kept; null `file` names none.
47
+ // `read()`, with an error of one of `classes` re-thrown with `file: ` leading its message, its fields kept.
58
48
  export function nameErrors(file, read, classes = [TomlError]) {
59
49
  try {
60
50
  return read()
@@ -64,5 +54,5 @@ export function nameErrors(file, read, classes = [TomlError]) {
64
54
  }
65
55
  }
66
56
 
67
- // Whether a TOML value is a table (a TomlFloat or TomlDateTime is an object too).
57
+ // The prototype check: a TomlFloat or TomlDateTime is an object too.
68
58
  export const isTomlTable = (value) => value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === null
package/src/lockfile.js CHANGED
@@ -1,4 +1 @@
1
- // Public-export adapter: backs `@exodus/stasis/lockfile`. The implementation lives in
2
- // @exodus/stasis-core; internal tooling and tests import `@exodus/stasis-core/lockfile`
3
- // directly, so this file exists only to back the package's `exports` map.
4
1
  export * from '@exodus/stasis-core/lockfile'
@@ -0,0 +1,41 @@
1
+ // `stasis build --metro=PLATFORM`: a Metro asset built into the module Metro builds of it and copied out as
2
+ // `--assets-dest` copies it, from the artifact's bytes, never disk: @preventive/rn's, but for the registry it requires.
3
+ import { posix } from 'node:path'
4
+
5
+ import { METRO_SOURCE_EXTS } from './resolve-fields.js'
6
+
7
+ // React Native's Metro config's `assetRegistryPath`: a project's own would be read off its Metro config, which is code.
8
+ export const ASSET_REGISTRY = 'react-native/Libraries/Image/AssetRegistry'
9
+
10
+ const REGISTRY_ROOT = /^((?:.*\/)?node_modules\/react-native)\/Libraries\/Image\/AssetRegistry\./u
11
+
12
+ // Resolved as Metro resolves it among the code files `carried` (by project path): in the react-native nearest up
13
+ // from the asset, else the only one (pnpm's). Throws where the artifact carries none, or several none of them nearest.
14
+ export function assetRegistryResolver(platform, carried) {
15
+ const pick = (root) => {
16
+ for (const ext of METRO_SOURCE_EXTS) {
17
+ for (const suffix of [`.${platform}`, '.native', '']) {
18
+ const file = `${root}/Libraries/Image/AssetRegistry${suffix}.${ext}`
19
+ if (carried.has(file)) return file
20
+ }
21
+ }
22
+ return undefined
23
+ }
24
+ const roots = new Set(carried.keys().map((file) => REGISTRY_ROOT.exec(file)?.[1]).filter((root) => root !== undefined && pick(root) !== undefined))
25
+ const nearest = (rel) => {
26
+ for (let dir = posix.dirname(rel); ; dir = posix.dirname(dir)) {
27
+ const root = posix.join(dir, 'node_modules', 'react-native')
28
+ if (posix.basename(dir) !== 'node_modules' && roots.has(root)) return root
29
+ if (dir === '.' || dir === '/' || dir.startsWith('..')) return undefined
30
+ }
31
+ }
32
+ return (rel) => {
33
+ const root = roots.size === 1 ? [...roots][0] : nearest(rel)
34
+ if (root !== undefined) return pick(root)
35
+ if (roots.size === 0) {
36
+ throw new Error(`stasis build: --metro builds '${rel}' into a module requiring ${ASSET_REGISTRY}, which the artifact `
37
+ + 'doesn\'t carry; bundle it with `stasis bundle --metro --resources=...` from a project with react-native installed')
38
+ }
39
+ throw new Error(`stasis build: --metro found several ${ASSET_REGISTRY} for '${rel}', none of them nearest: ${[...roots].join(', ')}`)
40
+ }
41
+ }