@exodus/stasis 1.0.0-beta.3 → 1.0.0-beta.5
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.
- package/README.md +7 -1
- package/bin/stasis.js +236 -17
- package/package.json +36 -9
- package/src/audit-corrections.js +68 -0
- package/src/audit.js +153 -108
- package/src/bundle-reader.js +77 -0
- package/src/cmd/build.js +3 -5
- package/src/cmd/bundle.js +571 -376
- package/src/cmd/github-bundle.js +39 -0
- package/src/cmd/output.js +36 -0
- package/src/cmd/sbom.js +3 -11
- package/src/diff.js +6 -6
- package/src/json-stream.js +283 -0
- package/src/loaders/bash.js +17 -36
- package/src/loaders/cargo.js +1699 -0
- package/src/loaders/foundry.js +923 -0
- package/src/loaders/paths.js +33 -0
- package/src/loaders/php.js +208 -124
- package/src/loaders/rust.js +3234 -166
- package/src/loaders/solidity-ownership.js +531 -0
- package/src/loaders/solidity.js +412 -137
- package/src/loaders/toml.js +68 -0
- package/src/metro-resolver.js +8 -23
- package/src/mock.js +3 -5
- package/src/resolve-fields.js +331 -0
- package/src/resolve-node.js +416 -0
- package/src/resolve-typescript.js +427 -0
- package/src/rollup.js +5 -0
- package/src/sbom.js +32 -18
- package/src/scan.js +79 -43
- package/src/vfs-bundle/entries.js +140 -0
- package/src/vfs-bundle/github.js +193 -0
- package/src/vfs-bundle/soldeer.js +125 -0
- package/src/vfs-bundle/tree.js +606 -0
- package/src/vfs-bundle.js +74 -0
- package/src/why.js +434 -0
- package/src/apis/npm/index.js +0 -36
- package/src/apis/npm/semver.cjs +0 -42
|
@@ -0,0 +1,68 @@
|
|
|
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.
|
|
6
|
+
|
|
7
|
+
import { TomlError, parseToml } from '@preventive/lockfile/toml.js'
|
|
8
|
+
|
|
9
|
+
export { TomlError }
|
|
10
|
+
|
|
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.
|
|
14
|
+
export function matchClose(text, open) {
|
|
15
|
+
const close = { '[': ']', '(': ')', '{': '}' }[text[open]]
|
|
16
|
+
let depth = 0
|
|
17
|
+
for (let i = open; i < text.length; i++) {
|
|
18
|
+
if (text[i] === text[open]) depth++
|
|
19
|
+
else if (text[i] === close && --depth === 0) return i
|
|
20
|
+
}
|
|
21
|
+
return text.length - 1
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Split on commas outside brackets/braces/parentheses/strings.
|
|
25
|
+
export function splitTopLevel(text) {
|
|
26
|
+
const parts = []
|
|
27
|
+
let depth = 0
|
|
28
|
+
let start = 0
|
|
29
|
+
let inStr = false
|
|
30
|
+
for (let i = 0; i < text.length; i++) {
|
|
31
|
+
const ch = text[i]
|
|
32
|
+
if (inStr) {
|
|
33
|
+
if (ch === '\\') i++
|
|
34
|
+
else if (ch === '"') inStr = false
|
|
35
|
+
continue
|
|
36
|
+
}
|
|
37
|
+
if (ch === '"') inStr = true
|
|
38
|
+
else if (ch === '(' || ch === '[' || ch === '{') depth++
|
|
39
|
+
else if (ch === ')' || ch === ']' || ch === '}') depth--
|
|
40
|
+
else if (ch === ',' && depth === 0) {
|
|
41
|
+
parts.push(text.slice(start, i))
|
|
42
|
+
start = i + 1
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
parts.push(text.slice(start))
|
|
46
|
+
return parts
|
|
47
|
+
}
|
|
48
|
+
|
|
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.
|
|
54
|
+
export const readToml = (text, file = null) => nameErrors(file, () => parseToml(text))
|
|
55
|
+
|
|
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.
|
|
58
|
+
export function nameErrors(file, read, classes = [TomlError]) {
|
|
59
|
+
try {
|
|
60
|
+
return read()
|
|
61
|
+
} catch (err) {
|
|
62
|
+
if (file === null || !classes.some((c) => err instanceof c)) throw err
|
|
63
|
+
throw Object.assign(new err.constructor(`${file}: ${err.message}`), err)
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Whether a TOML value is a table (a TomlFloat or TomlDateTime is an object too).
|
|
68
|
+
export const isTomlTable = (value) => value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === null
|
package/src/metro-resolver.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { readFileSync, realpathSync, statSync } from 'node:fs'
|
|
2
1
|
import { createRequire, isBuiltin } from 'node:module'
|
|
3
2
|
import { dirname, isAbsolute, join } from 'node:path'
|
|
4
3
|
import { pathToFileURL } from 'node:url'
|
|
5
4
|
|
|
5
|
+
import { diskHost } from '@exodus/stasis-core/host'
|
|
6
6
|
import { isTypeDeclaration } from '@exodus/stasis-core/util'
|
|
7
|
+
import { readJson } from './resolve-typescript.js'
|
|
7
8
|
|
|
8
9
|
// Adapter that drives the PROJECT's own `metro-resolver` from stasis's static scanner, so
|
|
9
10
|
// `stasis bundle --metro --metro-resolver` resolves modules EXACTLY the way that project's
|
|
@@ -23,29 +24,10 @@ import { isTypeDeclaration } from '@exodus/stasis-core/util'
|
|
|
23
24
|
// redirect via its own bundled helper, so the `redirectModulePath` we place on the context is
|
|
24
25
|
// an inert placeholder that satisfies the type but is never consulted for base resolution.
|
|
25
26
|
|
|
26
|
-
function readJson(file) {
|
|
27
|
-
let text
|
|
28
|
-
try {
|
|
29
|
-
text = readFileSync(file, 'utf8')
|
|
30
|
-
} catch {
|
|
31
|
-
return null // absent / unreadable -- no package manifest here
|
|
32
|
-
}
|
|
33
|
-
// A manifest that EXISTS but is malformed must fail closed (Metro would throw, not resolve past it).
|
|
34
|
-
try {
|
|
35
|
-
return JSON.parse(text)
|
|
36
|
-
} catch (cause) {
|
|
37
|
-
throw new Error(`Invalid package.json: ${file}`, { cause })
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
|
|
41
27
|
// 'f' | 'd' | null for a path, without throwing.
|
|
42
28
|
function pathType(p) {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
return s.isFile() ? 'f' : s.isDirectory() ? 'd' : null
|
|
46
|
-
} catch {
|
|
47
|
-
return null
|
|
48
|
-
}
|
|
29
|
+
const s = diskHost.stat(p)
|
|
30
|
+
return s?.isFile() ? 'f' : s?.isDirectory() ? 'd' : null
|
|
49
31
|
}
|
|
50
32
|
|
|
51
33
|
// A `.d.ts` is types-only, erased at runtime, so the resolver must never land on one: report it as
|
|
@@ -87,7 +69,10 @@ export function createMetroResolver({
|
|
|
87
69
|
conditionNames = ['react-native'],
|
|
88
70
|
conditionsByPlatform = { web: ['browser'] },
|
|
89
71
|
enablePackageExports = true,
|
|
72
|
+
host = diskHost,
|
|
90
73
|
} = {}) {
|
|
74
|
+
// It loads the project's metro-resolver, which reads the disk: never off it.
|
|
75
|
+
if (host !== diskHost) throw new Error('createMetroResolver: metro-resolver reads the disk, so it is not supported off disk')
|
|
91
76
|
const require = createRequire(join(projectDir, 'noop.js'))
|
|
92
77
|
let resolve
|
|
93
78
|
try {
|
|
@@ -118,7 +103,7 @@ export function createMetroResolver({
|
|
|
118
103
|
if (!type) return { exists: false }
|
|
119
104
|
let realPath = abs
|
|
120
105
|
try {
|
|
121
|
-
realPath =
|
|
106
|
+
realPath = diskHost.realpath(abs)
|
|
122
107
|
} catch { /* keep the lexical path when realpath fails (e.g. a broken symlink) */ }
|
|
123
108
|
return { exists: true, type, realPath }
|
|
124
109
|
},
|
package/src/mock.js
CHANGED
|
@@ -184,13 +184,11 @@ process.on('exit', () => {
|
|
|
184
184
|
// exits cleanly and the loader's beforeExit hook writes the bundle.
|
|
185
185
|
const noop = () => undefined
|
|
186
186
|
const pending = () => new Promise(() => {})
|
|
187
|
-
|
|
188
|
-
for (const name of
|
|
187
|
+
const TIMERS = ['setTimeout', 'setInterval', 'setImmediate', 'clearTimeout', 'clearInterval', 'clearImmediate']
|
|
188
|
+
for (const name of TIMERS) globalThis[name] = noop
|
|
189
189
|
|
|
190
190
|
const timers = require('node:timers')
|
|
191
|
-
for (const name of
|
|
192
|
-
mock.method(timers, name, noop)
|
|
193
|
-
}
|
|
191
|
+
for (const name of TIMERS) mock.method(timers, name, noop)
|
|
194
192
|
|
|
195
193
|
const timersPromises = require('node:timers/promises')
|
|
196
194
|
mock.method(timersPromises, 'setTimeout', pending)
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { isBuiltin } from 'node:module'
|
|
2
|
+
import { dirname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path'
|
|
3
|
+
import { pathToFileURL } from 'node:url'
|
|
4
|
+
|
|
5
|
+
import { isTypeDeclaration, stripTypeDeclaration, toPosix } from '@exodus/stasis-core/util'
|
|
6
|
+
import {
|
|
7
|
+
isDir,
|
|
8
|
+
isFile,
|
|
9
|
+
locatePackage,
|
|
10
|
+
nearestPackage,
|
|
11
|
+
readJson,
|
|
12
|
+
resolveTypescriptFallback,
|
|
13
|
+
typescriptSiblings,
|
|
14
|
+
} from './resolve-typescript.js'
|
|
15
|
+
import { diskHost } from '@exodus/stasis-core/host'
|
|
16
|
+
|
|
17
|
+
// Static module resolver for legacy package fields (`react-native`/`browser`/`main` + browser-spec
|
|
18
|
+
// redirect maps) and platform suffixes (`.ios`/`.android`/`.native`), reproducing Metro/React-Native
|
|
19
|
+
// resolution that Node's own resolver (used by scan.js) can't. `exports`-bearing packages are
|
|
20
|
+
// delegated to Node. No user code is executed (only package.json is stat/read).
|
|
21
|
+
//
|
|
22
|
+
// Returns, for each specifier:
|
|
23
|
+
// { url } resolved to a real file (file: URL string)
|
|
24
|
+
// { empty } a browser/react-native field mapped it to `false` (empty module)
|
|
25
|
+
// { builtin } a Node builtin
|
|
26
|
+
// null unresolved
|
|
27
|
+
|
|
28
|
+
// Metro divergence toggle. When a package's browser map maps its OWN entry to `false` (under
|
|
29
|
+
// Metro's matching rules, which include bare keys like {"buf": false} for main "./buf.js"),
|
|
30
|
+
// Metro's `getPackageEntryPoint` ignores the non-string replacement and keeps `main`. The
|
|
31
|
+
// `--metro` resolver matches that by default; flip this to `false` to fail closed instead:
|
|
32
|
+
// a `false` match on the entry then yields an EMPTY module. Note the off state is deliberately
|
|
33
|
+
// stricter than both tools -- for a bare-key `false`, Metro keeps `main` and esbuild would not
|
|
34
|
+
// match the entry at all -- it exists as an escape hatch, not an esbuild-parity mode. This only
|
|
35
|
+
// affects the `--metro` path; the `--mainFields` path always empties (matching esbuild).
|
|
36
|
+
// Tests can override per-resolver via createFieldResolver's `metroKeepEntryOnBrowserFalse`.
|
|
37
|
+
const METRO_KEEP_ENTRY_ON_BROWSER_FALSE = true
|
|
38
|
+
|
|
39
|
+
// First mainFields entry that's a non-empty string, else `index` (object-valued fields are redirect maps).
|
|
40
|
+
function packageEntry(pkg, mainFields) {
|
|
41
|
+
for (const name of mainFields) {
|
|
42
|
+
if (typeof pkg?.[name] === 'string' && pkg[name].length > 0) return pkg[name]
|
|
43
|
+
}
|
|
44
|
+
return 'index'
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Merge object-valued mainFields (browser-spec maps) into one redirect map. Iterate in REVERSE
|
|
48
|
+
// so earlier mainFields win on conflict. Keys are verbatim: `./x` relative vs bare `x` (kept bare).
|
|
49
|
+
function mergeRedirectMap(pkg, mainFields) {
|
|
50
|
+
const map = new Map()
|
|
51
|
+
for (let i = mainFields.length - 1; i >= 0; i--) {
|
|
52
|
+
const field = pkg?.[mainFields[i]]
|
|
53
|
+
if (!field || typeof field !== 'object') continue
|
|
54
|
+
for (const [key, value] of Object.entries(field)) {
|
|
55
|
+
if (typeof value !== 'string' && value !== false) continue
|
|
56
|
+
map.set(key, value)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return map
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Metro's entry-variant list for `main` (getPackageEntryPoint, metro-resolver
|
|
63
|
+
// PackageResolve.js): the main spelling and its ./-toggled twin, each expanded to
|
|
64
|
+
// [self, +'.js', +'.json', ext-stripped]. ORDER MATTERS -- the first variant with ANY mapping
|
|
65
|
+
// (string or false) decides, so this must reproduce Metro's list exactly, duplicates included.
|
|
66
|
+
function metroEntryVariants(main) {
|
|
67
|
+
const toggled = main.startsWith('./') ? main.slice(2) : `./${main}`
|
|
68
|
+
return [main, toggled].flatMap((v) => [v, `${v}.js`, `${v}.json`, v.replace(/\.(?:js|json)$/u, '')])
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Resolve the package ENTRY (from mainFields) through the package's own redirect map.
|
|
72
|
+
// Returns { entry } (the redirected or original entry to resolve) or { empty: true }.
|
|
73
|
+
// Both halves of the entry semantics -- WHICH keys match, and what `false` means -- live here
|
|
74
|
+
// so no caller can get one without the other:
|
|
75
|
+
// - metro: Metro's getPackageEntryPoint. First matching variant (Metro's order) wins; a string
|
|
76
|
+
// redirects; `false` (any non-string) keeps `main`, unless the keep-on-false toggle is off,
|
|
77
|
+
// in which case it fails closed to an empty module (see METRO_KEEP_ENTRY_ON_BROWSER_FALSE).
|
|
78
|
+
// - default (--mainFields): esbuild-shaped candidates; `false` empties the entry, matching
|
|
79
|
+
// esbuild. The extension-STRIPPED bare spelling is not probed: for an extensioned main,
|
|
80
|
+
// esbuild treats it as a bare module name, not the entry. (For an extensionless main the
|
|
81
|
+
// `bare` candidate covers it -- esbuild does match that spelling; verified empirically.)
|
|
82
|
+
function resolveEntryThroughMap(map, main, opts) {
|
|
83
|
+
if (map.size === 0) return { entry: main }
|
|
84
|
+
let cands
|
|
85
|
+
if (opts.metro) {
|
|
86
|
+
cands = metroEntryVariants(main)
|
|
87
|
+
} else {
|
|
88
|
+
const bare = main.replace(/^\.\//u, '')
|
|
89
|
+
const stripped = bare.replace(/\.(?:js|json)$/u, '')
|
|
90
|
+
cands = [
|
|
91
|
+
`./${bare}`, bare,
|
|
92
|
+
`./${stripped}`,
|
|
93
|
+
`./${stripped}.js`, `${stripped}.js`,
|
|
94
|
+
`./${stripped}.json`, `${stripped}.json`,
|
|
95
|
+
]
|
|
96
|
+
}
|
|
97
|
+
for (const cand of cands) {
|
|
98
|
+
const v = map.get(cand)
|
|
99
|
+
if (typeof v === 'string') return { entry: v }
|
|
100
|
+
if (v === false) {
|
|
101
|
+
if (opts.metro && opts.metroKeepEntryOnBrowserFalse) return { entry: main }
|
|
102
|
+
return { empty: true }
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return { entry: main }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const fileResolution = (path) => ({ url: pathToFileURL(path).toString() })
|
|
109
|
+
|
|
110
|
+
// Match a package-relative path (`./x`) against the redirect map, trying `.js`/`.json` appended.
|
|
111
|
+
function matchRedirect(map, relPath) {
|
|
112
|
+
if (map.size === 0) return undefined
|
|
113
|
+
for (const cand of [relPath, `${relPath}.js`, `${relPath}.json`]) {
|
|
114
|
+
if (map.has(cand)) return map.get(cand)
|
|
115
|
+
}
|
|
116
|
+
return undefined
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Probe `base` for a source file in platform order: bare name first, then per ext
|
|
120
|
+
// `base.<platform>.<ext>`, `base.native.<ext>` (native only), `base.<ext>`. `platform: null`
|
|
121
|
+
// disables suffixes. Under metro, every SUFFIXED candidate first passes through the candidate's
|
|
122
|
+
// own package redirect map -- mirroring Metro's resolveSourceFileForExt, which runs
|
|
123
|
+
// redirectModulePath on each non-bare candidate: `false` short-circuits the whole probe to an
|
|
124
|
+
// empty module (e.g. browser { "./index.ios.js": false }), and a string redirect re-lands the
|
|
125
|
+
// candidate package-root-relative. Returns a path, { empty: true } (metro only), or null.
|
|
126
|
+
function resolveSourceFile(base, opts) {
|
|
127
|
+
// A path that literally names a `.d.ts` names no runtime module (types are erased). Probe its
|
|
128
|
+
// declaration-free stem instead, so an entry field pointing at `dist/index.d.ts` lands on the real
|
|
129
|
+
// `dist/index.js` beside it rather than bundling the declaration -- or failing the package
|
|
130
|
+
// outright by falling back to a different index. The probe below still refuses a literal hit.
|
|
131
|
+
base = stripTypeDeclaration(base)
|
|
132
|
+
// Candidates share base's directory, hence its package scope; resolve it lazily, once.
|
|
133
|
+
let scope
|
|
134
|
+
const redirectCandidate = (p) => {
|
|
135
|
+
if (scope === undefined) {
|
|
136
|
+
const pkg = nearestPackage(base, opts.host)
|
|
137
|
+
scope = pkg ? { pkgDir: pkg.pkgDir, map: mergeRedirectMap(pkg.pkg, opts.mainFields) } : null
|
|
138
|
+
}
|
|
139
|
+
if (!scope || scope.map.size === 0) return p
|
|
140
|
+
const rel = `./${toPosix(relative(scope.pkgDir, p))}`
|
|
141
|
+
const r = matchRedirect(scope.map, rel)
|
|
142
|
+
if (r === false) return false
|
|
143
|
+
if (typeof r === 'string') return isAbsolute(r) ? r : resolvePath(scope.pkgDir, r)
|
|
144
|
+
return p
|
|
145
|
+
}
|
|
146
|
+
// `derived` marks a candidate that is not the literal base; Metro redirect-checks those only.
|
|
147
|
+
const probePath = (p, derived) => {
|
|
148
|
+
if (opts.metro && derived) {
|
|
149
|
+
const r = redirectCandidate(p)
|
|
150
|
+
if (r === false) return { empty: true }
|
|
151
|
+
p = r
|
|
152
|
+
}
|
|
153
|
+
// A `.d.ts` is types-only, erased at runtime: never a resolution target, so a package whose
|
|
154
|
+
// entry field points at one falls through to its real `.js` instead of bundling the declaration.
|
|
155
|
+
if (isTypeDeclaration(p)) return null
|
|
156
|
+
return isFile(p, opts.host) ? p : null
|
|
157
|
+
}
|
|
158
|
+
// `suffix` is everything appended to `base`.
|
|
159
|
+
const probe = (suffix) => probePath(`${base}${suffix}`, suffix !== '')
|
|
160
|
+
const tryExt = (sourceExt) => {
|
|
161
|
+
if (opts.platform) {
|
|
162
|
+
const hit = probe(`.${opts.platform}${sourceExt}`)
|
|
163
|
+
if (hit) return hit
|
|
164
|
+
}
|
|
165
|
+
if (opts.preferNative && sourceExt !== '') {
|
|
166
|
+
const hit = probe(`.native${sourceExt}`)
|
|
167
|
+
if (hit) return hit
|
|
168
|
+
}
|
|
169
|
+
return probe(sourceExt)
|
|
170
|
+
}
|
|
171
|
+
const bare = tryExt('')
|
|
172
|
+
if (bare) return bare
|
|
173
|
+
// --typescript: tsc's extension substitution. A base naming a JS output extension probes its TS
|
|
174
|
+
// source siblings once the literal file (the bare probe above) is absent, so the on-disk `.js`
|
|
175
|
+
// always wins over its `.ts` twin. Literal siblings only -- no platform suffixes (tsc has none);
|
|
176
|
+
// extensionless bases keep going through the appended-extension loop below (sourceExts carries
|
|
177
|
+
// ts, and tsx under --jsx). Placed before that loop so `x.js` -> `x.ts` beats a pathological
|
|
178
|
+
// `x.js.<ext>`, matching tsc's candidate order.
|
|
179
|
+
if (opts.typescript) {
|
|
180
|
+
for (const cand of typescriptSiblings(base, { tsx: opts.sourceExts.includes('tsx') })) {
|
|
181
|
+
const hit = probePath(cand, true)
|
|
182
|
+
if (hit) return hit
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
for (const ext of opts.sourceExts) {
|
|
186
|
+
const hit = tryExt(`.${ext}`)
|
|
187
|
+
if (hit) return hit
|
|
188
|
+
}
|
|
189
|
+
return null
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Resolve absolute `base` as a file (ext probing) else as a directory (package.json `main` via
|
|
193
|
+
// mainFields + entry redirect, else `index`). `exports` is NOT consulted — Node applies it only to
|
|
194
|
+
// bare package-name imports, not to a path landing on a directory.
|
|
195
|
+
function resolveFileOrDir(base, opts) {
|
|
196
|
+
// resolveSourceFile yields a path, { empty: true } (a metro candidate-redirect hit), or null.
|
|
197
|
+
const asResolution = (hit) => (hit == null ? null : typeof hit === 'string' ? fileResolution(hit) : hit)
|
|
198
|
+
const file = asResolution(resolveSourceFile(base, opts))
|
|
199
|
+
if (file) return file
|
|
200
|
+
if (isDir(base, opts.host)) {
|
|
201
|
+
const dpkg = readJson(join(base, 'package.json'), opts.host)
|
|
202
|
+
if (dpkg) {
|
|
203
|
+
const r = resolveEntryThroughMap(mergeRedirectMap(dpkg, opts.mainFields), packageEntry(dpkg, opts.mainFields), opts)
|
|
204
|
+
if (r.empty) return { empty: true }
|
|
205
|
+
// Node's LOAD_AS_DIRECTORY resolves `main` as a file, else as a directory index
|
|
206
|
+
// (`main: "./lib/"` -> lib/index.js); a broken `main` falls back to the package index below.
|
|
207
|
+
const entryBase = join(base, r.entry)
|
|
208
|
+
const inner = asResolution(resolveSourceFile(entryBase, opts) ?? resolveSourceFile(join(entryBase, 'index'), opts))
|
|
209
|
+
if (inner) return inner
|
|
210
|
+
}
|
|
211
|
+
const index = asResolution(resolveSourceFile(join(base, 'index'), opts))
|
|
212
|
+
if (index) return index
|
|
213
|
+
}
|
|
214
|
+
return null
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Build a resolver bound to options: `conditions` gates `exports` packages (delegated to Node),
|
|
218
|
+
// `mainFields`/`platform`/`preferNative`/`sourceExts` drive the legacy-field + suffix probing.
|
|
219
|
+
// `metro` opts into Metro's package-entry + candidate-redirect semantics (see
|
|
220
|
+
// resolveEntryThroughMap and resolveSourceFile); leave it off for the esbuild-parity
|
|
221
|
+
// `--mainFields` path. `typescript` adds tsc's extension substitution (a missing `x.js` probes
|
|
222
|
+
// its `x.ts` sibling; see resolveSourceFile) plus the shared miss fallback (see below), and
|
|
223
|
+
// `typescriptPaths` (a loadTsconfigPaths matcher) its tsconfig alias mapping.
|
|
224
|
+
// `metroKeepEntryOnBrowserFalse` overrides the module-level toggle
|
|
225
|
+
// (METRO_KEEP_ENTRY_ON_BROWSER_FALSE) per resolver -- primarily so tests can cover both branches.
|
|
226
|
+
// `host` is the filesystem view (@exodus/stasis-core/host), the real disk by default.
|
|
227
|
+
export function createFieldResolver({
|
|
228
|
+
conditions = [],
|
|
229
|
+
mainFields = ['main'],
|
|
230
|
+
platform = null,
|
|
231
|
+
preferNative = false,
|
|
232
|
+
sourceExts = ['js', 'json', 'ts'],
|
|
233
|
+
metro = false,
|
|
234
|
+
typescript = false,
|
|
235
|
+
typescriptPaths = null,
|
|
236
|
+
metroKeepEntryOnBrowserFalse = METRO_KEEP_ENTRY_ON_BROWSER_FALSE,
|
|
237
|
+
host = diskHost,
|
|
238
|
+
} = {}) {
|
|
239
|
+
const opts = { platform, preferNative, sourceExts, mainFields, metro, typescript, metroKeepEntryOnBrowserFalse, host }
|
|
240
|
+
// `callConditions` (from scan) is the parent's format-driven condition set, so `exports`
|
|
241
|
+
// delegation matches Node resolving from THAT file; falls back to configured `conditions`.
|
|
242
|
+
const resolve = function resolve(parentFile, specifier, callConditions) {
|
|
243
|
+
const conds = new Set(callConditions ?? conditions)
|
|
244
|
+
const viaNode = (spec) => {
|
|
245
|
+
try {
|
|
246
|
+
return fileResolution(host.resolve(parentFile, spec, conds))
|
|
247
|
+
} catch {
|
|
248
|
+
return null
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
// `#name` subpath imports use the `imports` field + conditions; Node's algorithm handles them.
|
|
252
|
+
if (specifier.startsWith('#')) return viaNode(specifier)
|
|
253
|
+
|
|
254
|
+
let spec = specifier
|
|
255
|
+
// Redirect via the IMPORTER's browser/react-native map, BEFORE the builtin check on purpose:
|
|
256
|
+
// a map entry can disable or shim a builtin (`{"crypto": false}` / `"crypto-browserify"`).
|
|
257
|
+
const imp = nearestPackage(parentFile, host)
|
|
258
|
+
if (imp) {
|
|
259
|
+
const map = mergeRedirectMap(imp.pkg, mainFields)
|
|
260
|
+
let r
|
|
261
|
+
if (spec.startsWith('.') || isAbsolute(spec)) {
|
|
262
|
+
const abs = isAbsolute(spec) ? spec : resolvePath(dirname(parentFile), spec)
|
|
263
|
+
r = matchRedirect(map, `./${toPosix(relative(imp.pkgDir, abs))}`)
|
|
264
|
+
} else {
|
|
265
|
+
r = map.get(spec) // a bare specifier (`mod`, `mod/sub`) matches the map's bare keys
|
|
266
|
+
}
|
|
267
|
+
if (r === false) return { empty: true }
|
|
268
|
+
if (typeof r === 'string') {
|
|
269
|
+
// Browser-map targets are relative to the PACKAGE ROOT, not the importing file; a
|
|
270
|
+
// bare-module target re-enters resolution below.
|
|
271
|
+
if (r.startsWith('.') || isAbsolute(r)) {
|
|
272
|
+
return resolveFileOrDir(isAbsolute(r) ? r : resolvePath(imp.pkgDir, r), opts)
|
|
273
|
+
}
|
|
274
|
+
spec = r
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// A builtin the browser map did not remap resolves to the builtin itself.
|
|
279
|
+
if (isBuiltin(spec)) return { builtin: true }
|
|
280
|
+
|
|
281
|
+
if (spec.startsWith('.') || isAbsolute(spec)) {
|
|
282
|
+
const base = isAbsolute(spec) ? spec : resolvePath(dirname(parentFile), spec)
|
|
283
|
+
return resolveFileOrDir(base, opts)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const loc = locatePackage(dirname(parentFile), spec, host)
|
|
287
|
+
if (!loc) return null
|
|
288
|
+
const pkg = readJson(join(loc.pkgDir, 'package.json'), host) ?? {}
|
|
289
|
+
// `exports` wins over mainFields; Node's algorithm resolves it (with conditions) correctly.
|
|
290
|
+
if (pkg.exports != null) return viaNode(spec)
|
|
291
|
+
// A bare package import resolves its directory via the same dir algorithm as any other.
|
|
292
|
+
if (loc.subpath === '') return resolveFileOrDir(loc.pkgDir, opts)
|
|
293
|
+
const sub = `./${loc.subpath}`
|
|
294
|
+
const r = matchRedirect(mergeRedirectMap(pkg, mainFields), sub)
|
|
295
|
+
if (r === false) return { empty: true }
|
|
296
|
+
const target = typeof r === 'string' ? r : sub
|
|
297
|
+
return resolveFileOrDir(join(loc.pkgDir, target), opts)
|
|
298
|
+
}
|
|
299
|
+
if (!typescript) return resolve
|
|
300
|
+
// --typescript: when the whole field flow leaves the specifier unresolved, give tsc's mapping
|
|
301
|
+
// the same shot the scanner's fallback gets, via the shared dispatcher. On this path it covers
|
|
302
|
+
// the layers the field resolver delegates to Node -- `exports`-bearing packages and `#` subpath
|
|
303
|
+
// imports, whose targets may name compiled files existing only as TS source -- plus tsconfig
|
|
304
|
+
// `paths` aliases; misses only, so no field/redirect/suffix resolution is ever overridden.
|
|
305
|
+
// (Relative paths re-probe tsc-style too -- redundant after resolveSourceFile, but harmless.)
|
|
306
|
+
return function resolveWithTypescriptFallback(parentFile, specifier, callConditions) {
|
|
307
|
+
const resolved = resolve(parentFile, specifier, callConditions)
|
|
308
|
+
if (resolved) return resolved
|
|
309
|
+
const hit = resolveTypescriptFallback(parentFile, specifier, {
|
|
310
|
+
conditions: new Set(callConditions ?? conditions),
|
|
311
|
+
tsx: sourceExts.includes('tsx'),
|
|
312
|
+
paths: typescriptPaths,
|
|
313
|
+
host,
|
|
314
|
+
})
|
|
315
|
+
return hit == null ? null : fileResolution(hit)
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// True when `format` is an ESM family (drives the base condition set, mirroring scan).
|
|
320
|
+
function isModuleFormat(format) {
|
|
321
|
+
return format === 'module' || format === 'module-typescript'
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// Condition set for a parent of the given format: Node's format-driven base (matching scan's
|
|
325
|
+
// #conditionsFor) plus extras. Order is irrelevant (Node membership-tests against exports key order).
|
|
326
|
+
export function resolveConditions(format, extras = []) {
|
|
327
|
+
const base = isModuleFormat(format)
|
|
328
|
+
? ['node', 'import', 'module-sync', 'node-addons']
|
|
329
|
+
: ['node', 'require', 'module-sync', 'node-addons']
|
|
330
|
+
return [...new Set([...base, ...extras])]
|
|
331
|
+
}
|