@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
@@ -2,238 +2,145 @@ import { isBuiltin } from 'node:module'
2
2
  import { dirname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path'
3
3
  import { pathToFileURL } from 'node:url'
4
4
 
5
- import { isTypeDeclaration, stripTypeDeclaration, toPosix } from '@exodus/stasis-core/util'
5
+ import { isAssetFile } from '@preventive/rn/metro-assets.js'
6
+ import { createMetroResolver, defaults as metroDefaults } from '@preventive/rn/metro-resolver.js'
7
+ import { memoized, toPosix } from '@exodus/stasis-core/util'
6
8
  import {
9
+ fromOutputSource,
7
10
  inNodeModules,
8
11
  isDir,
9
- isFile,
12
+ isSourceFile,
10
13
  locatePackage,
11
14
  nearestPackage,
12
- readJson,
15
+ readManifest,
13
16
  resolveTypescriptFallback,
17
+ tsconfigOutputsOf,
14
18
  typescriptSiblings,
15
19
  } from './resolve-typescript.js'
16
20
  import { diskHost } from '@exodus/stasis-core/host'
17
- import { createNodeResolver } from './resolve-node.js'
21
+ import { metroHost, scanResolution, stripTypeDeclaration } from './metro-resolver.js'
22
+ import { RELATIVE_REQUEST, createNodeResolver } from './resolve-node.js'
23
+ import { hostMemo } from './vfs-bundle/lazy.js'
18
24
 
19
- // Static module resolver for legacy package fields (`react-native`/`browser`/`main` + browser-spec
20
- // redirect maps) and platform suffixes (`.ios`/`.android`/`.native`), reproducing Metro/React-Native
21
- // resolution that Node's own resolver (used by scan.js) can't. `exports`-bearing packages are
22
- // delegated to Node's algorithm, under a bundler's conditions rather than Node's (see
23
- // resolveConditions). No user code is executed (only package.json is stat/read).
24
- //
25
- // Returns, for each specifier:
26
- // { url } resolved to a file, by its real path (file: URL string; see fileResolution)
27
- // { empty } a browser/react-native field mapped it to `false` (empty module)
28
- // { builtin } a Node builtin: a `node:` specifier, or a builtin name no installed package resolves
29
- // null unresolved
30
- //
31
- // Browser and React Native targets have no Node builtins, so a bare builtin name (`buffer`,
32
- // `events`, `util`, `process`, ...) resolves to the installed npm package of that name, as esbuild
33
- // (platform browser), webpack 5 (target web) and Metro bundle it. Where nothing is installed it
34
- // stays a builtin, as the --metro-resolver adapter reports Metro's miss on one (metro-resolver.js),
35
- // rather than an unresolved edge: Metro and webpack fail the build there.
25
+ // Legacy package fields (`react-native`/`browser`/`main`, their redirect maps) and platform suffixes, as Metro resolves
26
+ // them: -> { url } | { empty } (mapped to `false`) | { builtin } | null. Targets without Node builtins take a bare builtin
27
+ // name (`buffer`) for the installed package so named, as esbuild, webpack 5 and Metro do, else for the builtin.
36
28
 
37
- // Metro divergence toggle. When a package's browser map maps its OWN entry to `false` (under
38
- // Metro's matching rules, which include bare keys like {"buf": false} for main "./buf.js"),
39
- // Metro's `getPackageEntryPoint` ignores the non-string replacement and keeps `main`. The
40
- // `--metro` resolver matches that by default; flip this to `false` to fail closed instead:
41
- // a `false` match on the entry then yields an EMPTY module. Note the off state is deliberately
42
- // stricter than both tools -- for a bare-key `false`, Metro keeps `main` and esbuild would not
43
- // match the entry at all -- it exists as an escape hatch, not an esbuild-parity mode. This only
44
- // affects the `--metro` path; the `--mainFields` path always empties (matching esbuild).
45
- // Tests can override per-resolver via createFieldResolver's `metroKeepEntryOnBrowserFalse`.
46
- const METRO_KEEP_ENTRY_ON_BROWSER_FALSE = true
29
+ // Object-valued fields are redirect maps, never an entry.
30
+ const packageEntry = (pkg, mainFields) =>
31
+ mainFields.map((name) => pkg[name]).find((entry) => typeof entry === 'string' && entry.length > 0) ?? 'index'
47
32
 
48
- // First mainFields entry that's a non-empty string, else `index` (object-valued fields are redirect maps).
49
- function packageEntry(pkg, mainFields) {
50
- for (const name of mainFields) {
51
- if (typeof pkg?.[name] === 'string' && pkg[name].length > 0) return pkg[name]
52
- }
53
- return 'index'
54
- }
55
-
56
- // Merge object-valued mainFields (browser-spec maps) into one redirect map. Iterate in REVERSE
57
- // so earlier mainFields win on conflict. Keys are verbatim: `./x` relative vs bare `x` (kept bare).
33
+ // Earlier mainFields win on conflict. Keys are verbatim: `./x` relative vs bare `x`.
58
34
  function mergeRedirectMap(pkg, mainFields) {
59
35
  const map = new Map()
60
- for (let i = mainFields.length - 1; i >= 0; i--) {
61
- const field = pkg?.[mainFields[i]]
36
+ for (const name of mainFields.toReversed()) {
37
+ const field = pkg?.[name]
62
38
  if (!field || typeof field !== 'object') continue
63
39
  for (const [key, value] of Object.entries(field)) {
64
- if (typeof value !== 'string' && value !== false) continue
65
- map.set(key, value)
40
+ if (typeof value === 'string' || value === false) map.set(key, value)
66
41
  }
67
42
  }
68
43
  return map
69
44
  }
70
45
 
71
- // Metro's entry-variant list for `main` (getPackageEntryPoint, metro-resolver
72
- // PackageResolve.js): the main spelling and its ./-toggled twin, each expanded to
73
- // [self, +'.js', +'.json', ext-stripped]. ORDER MATTERS -- the first variant with ANY mapping
74
- // (string or false) decides, so this must reproduce Metro's list exactly, duplicates included.
75
- function metroEntryVariants(main) {
76
- const toggled = main.startsWith('./') ? main.slice(2) : `./${main}`
77
- return [main, toggled].flatMap((v) => [v, `${v}.js`, `${v}.json`, v.replace(/\.(?:js|json)$/u, '')])
78
- }
79
-
80
- // Resolve the package ENTRY (from mainFields) through the package's own redirect map.
81
- // Returns { entry } (the redirected or original entry to resolve) or { empty: true }.
82
- // Both halves of the entry semantics -- WHICH keys match, and what `false` means -- live here
83
- // so no caller can get one without the other:
84
- // - metro: Metro's getPackageEntryPoint. First matching variant (Metro's order) wins; a string
85
- // redirects; `false` (any non-string) keeps `main`, unless the keep-on-false toggle is off,
86
- // in which case it fails closed to an empty module (see METRO_KEEP_ENTRY_ON_BROWSER_FALSE).
87
- // - default (--mainFields): esbuild-shaped candidates; `false` empties the entry, matching
88
- // esbuild. The extension-STRIPPED bare spelling is not probed: for an extensioned main,
89
- // esbuild treats it as a bare module name, not the entry. (For an extensionless main the
90
- // `bare` candidate covers it -- esbuild does match that spelling; verified empirically.)
91
- function resolveEntryThroughMap(map, main, opts) {
46
+ // As esbuild maps the package entry: the extension-stripped bare spelling is no candidate, esbuild taking it as a
47
+ // bare module name (an extensionless main's is `bare` itself, which it matches).
48
+ function resolveEntryThroughMap(map, main) {
92
49
  if (map.size === 0) return { entry: main }
93
- let cands
94
- if (opts.metro) {
95
- cands = metroEntryVariants(main)
96
- } else {
97
- const bare = main.replace(/^\.\//u, '')
98
- const stripped = bare.replace(/\.(?:js|json)$/u, '')
99
- cands = [
100
- `./${bare}`, bare,
101
- `./${stripped}`,
102
- `./${stripped}.js`, `${stripped}.js`,
103
- `./${stripped}.json`, `${stripped}.json`,
104
- ]
105
- }
106
- for (const cand of cands) {
50
+ const bare = main.replace(/^\.\//u, '')
51
+ const stripped = bare.replace(/\.(?:js|json)$/u, '')
52
+ for (const cand of [`./${bare}`, bare, `./${stripped}`, `./${stripped}.js`, `${stripped}.js`, `./${stripped}.json`, `${stripped}.json`]) {
107
53
  const v = map.get(cand)
108
54
  if (typeof v === 'string') return { entry: v }
109
- if (v === false) {
110
- if (opts.metro && opts.metroKeepEntryOnBrowserFalse) return { entry: main }
111
- return { empty: true }
112
- }
55
+ if (v === false) return { empty: true }
113
56
  }
114
57
  return { entry: main }
115
58
  }
116
59
 
117
- // A resolved file by its REAL path (through `host`, so a Vfs host's links are followed too), as Node,
118
- // Metro and esbuild record one: under pnpm's isolated layout `node_modules/debug` links into
119
- // `node_modules/.pnpm/debug@x/node_modules/debug`, whose own imports (a sibling `ms`) resolve only
120
- // from where it really lies. Probing stays on the path as reached, so a candidate and the package
121
- // scope read from it (resolveSourceFile's metro redirect) are one spelling; only the hit is
122
- // realpathed. null where the file has no real path (gone since it was probed).
60
+ // By real path, as Node, Metro and esbuild record a file: under pnpm a package's imports resolve only from where it lies.
123
61
  function fileResolution(path, host) {
124
- let real
125
62
  try {
126
- real = host.realpath(path)
63
+ return { url: pathToFileURL(host.realpath(path)).toString() }
127
64
  } catch {
128
65
  return null
129
66
  }
130
- return { url: pathToFileURL(real).toString() }
131
67
  }
132
68
 
133
- // Match a package-relative path (`./x`) against the redirect map, trying `.js`/`.json` appended.
134
- function matchRedirect(map, relPath) {
135
- if (map.size === 0) return undefined
136
- for (const cand of [relPath, `${relPath}.js`, `${relPath}.json`]) {
137
- if (map.has(cand)) return map.get(cand)
69
+ // Map keys are strings, so a miss gets undefined.
70
+ const matchRedirect = (map, relPath) => map.get([relPath, `${relPath}.js`, `${relPath}.json`].find((cand) => map.has(cand)))
71
+
72
+ // Each resolver reads its own manifests, so a build on the disk reads each as it is then.
73
+ function manifestReader(host) {
74
+ const manifests = hostMemo(host)
75
+ return (path) => manifests(path, () => readManifest(path, host))
76
+ }
77
+
78
+ export const METRO_SOURCE_EXTS = metroDefaults.sourceExts
79
+ export const METRO_ASSET_EXTS = new Set(metroDefaults.assetExts)
80
+ export const METRO_ASSET_RESOLUTIONS = metroDefaults.assetResolutions
81
+ const METRO_OWN_CONDITIONS = new Set(['default', 'import', 'require'])
82
+
83
+ // --metro --typescript: an absent JS output is its first TS sibling on disk, else an unbuilt output's source.
84
+ function typescriptView(view, { outputs, host }) {
85
+ const sibling = (path) => typescriptSiblings(path).find((candidate) => view.isFile(candidate)) ?? null
86
+ const source = (path) => {
87
+ const pick = sibling(path) ?? fromOutputSource(path, (input) => (view.isFile(input) ? input : sibling(input)), { outputs, host })
88
+ return pick === null || inNodeModules(pick, host) ? null : pick
89
+ }
90
+ const substituted = (path) => (view.isFile(path) || view.isDirectory(path) ? null : source(path))
91
+ return {
92
+ ...view,
93
+ isFile: (path) => view.isFile(path) || substituted(path) !== null,
94
+ realpath: (path) => view.realpath(substituted(path) ?? path),
138
95
  }
139
- return undefined
140
96
  }
141
97
 
142
- // Probe `base` for a source file in platform order: bare name first, then per ext
143
- // `base.<platform>.<ext>`, `base.native.<ext>` (native only), `base.<ext>`. `platform: null`
144
- // disables suffixes. Under metro, every SUFFIXED candidate first passes through the candidate's
145
- // own package redirect map -- mirroring Metro's resolveSourceFileForExt, which runs
146
- // redirectModulePath on each non-bare candidate: `false` short-circuits the whole probe to an
147
- // empty module (e.g. browser { "./index.ios.js": false }), and a string redirect re-lands the
148
- // candidate package-root-relative. Returns a path, { empty: true } (metro only), or null.
149
98
  function resolveSourceFile(base, opts) {
150
- // A path that literally names a `.d.ts` names no runtime module (types are erased). Probe its
151
- // declaration-free stem instead, so an entry field pointing at `dist/index.d.ts` lands on the real
152
- // `dist/index.js` beside it rather than bundling the declaration -- or failing the package
153
- // outright by falling back to a different index. The probe below still refuses a literal hit.
99
+ // An entry field naming `dist/index.d.ts` lands on the `dist/index.js` beside it.
154
100
  base = stripTypeDeclaration(base)
155
- // Candidates share base's directory, hence its package scope; resolve it lazily, once.
156
- let scope
157
- const redirectCandidate = (p) => {
158
- if (scope === undefined) {
159
- const pkg = nearestPackage(base, opts.host)
160
- scope = pkg ? { pkgDir: pkg.pkgDir, map: mergeRedirectMap(pkg.pkg, opts.mainFields) } : null
161
- }
162
- if (!scope || scope.map.size === 0) return p
163
- const rel = `./${toPosix(relative(scope.pkgDir, p))}`
164
- const r = matchRedirect(scope.map, rel)
165
- if (r === false) return false
166
- if (typeof r === 'string') return isAbsolute(r) ? r : resolvePath(scope.pkgDir, r)
167
- return p
168
- }
169
- // `derived` marks a candidate that is not the literal base; Metro redirect-checks those only.
170
- const probePath = (p, derived) => {
171
- if (opts.metro && derived) {
172
- const r = redirectCandidate(p)
173
- if (r === false) return { empty: true }
174
- p = r
175
- }
176
- // A `.d.ts` is types-only, erased at runtime: never a resolution target, so a package whose
177
- // entry field points at one falls through to its real `.js` instead of bundling the declaration.
178
- if (isTypeDeclaration(p)) return null
179
- return isFile(p, opts.host) ? p : null
180
- }
181
- // `suffix` is everything appended to `base`.
182
- const probe = (suffix) => probePath(`${base}${suffix}`, suffix !== '')
183
- const tryExt = (sourceExt) => {
184
- if (opts.platform) {
185
- const hit = probe(`.${opts.platform}${sourceExt}`)
186
- if (hit) return hit
187
- }
188
- if (opts.preferNative && sourceExt !== '') {
189
- const hit = probe(`.native${sourceExt}`)
190
- if (hit) return hit
191
- }
192
- return probe(sourceExt)
193
- }
101
+ const probe = (suffix) => (isSourceFile(`${base}${suffix}`, opts.host) ? `${base}${suffix}` : null)
102
+ const tryExt = (ext) => (opts.platform && probe(`.${opts.platform}${ext}`))
103
+ || (opts.preferNative && ext !== '' && probe(`.native${ext}`))
104
+ || probe(ext)
194
105
  const bare = tryExt('')
195
106
  if (bare) return bare
196
- // --typescript: tsc's extension substitution. A base naming a JS output extension probes its TS
197
- // source siblings once the literal file (the bare probe above) is absent, so the on-disk `.js`
198
- // always wins over its `.ts` twin. Literal siblings only -- no platform suffixes (tsc has none);
199
- // extensionless bases keep going through the appended-extension loop below (sourceExts carries
200
- // ts and tsx). Placed before that loop so `x.js` -> `x.ts` beats a pathological
201
- // `x.js.<ext>`, matching tsc's candidate order. Never into node_modules: where tsc's pick, the
202
- // first sibling on disk, lies there by its real path, nothing maps (inNodeModules), as the shared
203
- // fallback refuses its own -- never a later sibling tsc wouldn't pick. The resolver drops
204
- // `typescript` for an importer there.
107
+ // tsc's substitution comes once the literal file is absent, before the appended extensions, as tsc orders them.
108
+ // Its pick, the first sibling on disk, maps nothing in node_modules, never to a later sibling.
205
109
  if (opts.typescript) {
206
- for (const cand of typescriptSiblings(base)) {
207
- const hit = probePath(cand, true)
208
- if (hit === null) continue
209
- return typeof hit === 'string' && inNodeModules(hit, opts.host) ? null : hit
210
- }
110
+ const sibling = typescriptSiblings(base).find((candidate) => isSourceFile(candidate, opts.host))
111
+ if (sibling !== undefined) return inNodeModules(sibling, opts.host) ? null : sibling
211
112
  }
212
113
  for (const ext of opts.sourceExts) {
213
114
  const hit = tryExt(`.${ext}`)
214
115
  if (hit) return hit
215
116
  }
117
+ // Not for a directory: resolveFileOrDir probes its index, which maps.
118
+ if (opts.typescript && !isDir(base, opts.host)) {
119
+ const source = (input) => {
120
+ const hit = resolveSourceFile(input, { ...opts, outputs: null })
121
+ return hit === null || inNodeModules(hit, opts.host) ? null : hit
122
+ }
123
+ return fromOutputSource(base, source, opts)
124
+ }
216
125
  return null
217
126
  }
218
127
 
219
- // Resolve absolute `base` as a file (ext probing) else as a directory (package.json `main` via
220
- // mainFields + entry redirect, else `index`). `exports` is NOT consulted — Node applies it only to
221
- // bare package-name imports, not to a path landing on a directory.
222
- function resolveFileOrDir(base, opts) {
223
- // resolveSourceFile yields a path, { empty: true } (a metro candidate-redirect hit), or null.
224
- const asResolution = (hit) => (hit == null ? null : typeof hit === 'string' ? fileResolution(hit, opts.host) : hit)
128
+ // `exports` is not consulted: Node applies it only to bare package names.
129
+ function resolveFileOrDir(base, opts, tried) {
130
+ const asResolution = (hit) => (hit === null ? null : fileResolution(hit, opts.host))
225
131
  const file = asResolution(resolveSourceFile(base, opts))
226
132
  if (file) return file
227
133
  if (isDir(base, opts.host)) {
228
- const dpkg = readJson(join(base, 'package.json'), opts.host)
134
+ const dpkg = opts.read(join(base, 'package.json'))
229
135
  if (dpkg) {
230
- const r = resolveEntryThroughMap(mergeRedirectMap(dpkg, opts.mainFields), packageEntry(dpkg, opts.mainFields), opts)
136
+ const r = resolveEntryThroughMap(mergeRedirectMap(dpkg, opts.mainFields), packageEntry(dpkg, opts.mainFields))
231
137
  if (r.empty) return { empty: true }
232
- // Node's LOAD_AS_DIRECTORY resolves `main` as a file, else as a directory index
233
- // (`main: "./lib/"` -> lib/index.js); a broken `main` falls back to the package index below.
138
+ // Node's LOAD_AS_DIRECTORY: `main` as a file, else as a directory index; a broken one falls back to the index.
234
139
  const entryBase = join(base, r.entry)
235
- const inner = asResolution(resolveSourceFile(entryBase, opts) ?? resolveSourceFile(join(entryBase, 'index'), opts))
140
+ const entryOpts = { ...opts, pkgDir: base } // the package naming the entry, for its unbuilt output
141
+ const inner = asResolution(resolveSourceFile(entryBase, entryOpts) ?? resolveSourceFile(join(entryBase, 'index'), entryOpts))
236
142
  if (inner) return inner
143
+ tried.push(entryBase)
237
144
  }
238
145
  const index = asResolution(resolveSourceFile(join(base, 'index'), opts))
239
146
  if (index) return index
@@ -241,71 +148,80 @@ function resolveFileOrDir(base, opts) {
241
148
  return null
242
149
  }
243
150
 
244
- // Build a resolver bound to options: `conditions` (a resolveConditions set) gates `exports`
245
- // packages (delegated to Node's algorithm), `mainFields`/`platform`/`preferNative`/`sourceExts`
246
- // drive the legacy-field + suffix probing.
247
- // `metro` opts into Metro's package-entry + candidate-redirect semantics (see
248
- // resolveEntryThroughMap and resolveSourceFile); leave it off for the esbuild-parity
249
- // `--mainFields` path. `typescript` adds tsc's extension substitution (a missing `x.js` probes
250
- // its `x.ts` sibling; see resolveSourceFile) plus the shared miss fallback (see below), and
251
- // `typescriptPaths` (a tsconfig paths matcher; see resolveTypescriptFallback) its tsconfig alias mapping.
252
- // `metroKeepEntryOnBrowserFalse` overrides the module-level toggle
253
- // (METRO_KEEP_ENTRY_ON_BROWSER_FALSE) per resolver -- primarily so tests can cover both branches.
254
- // `host` is the filesystem view (@exodus/stasis-core/host), the real disk by default.
151
+ // `kept`: a Map kept across a lazy tree's rounds (untouchedMemo's `across`).
255
152
  export function createFieldResolver({
256
153
  conditions = [],
257
154
  mainFields = ['main'],
258
155
  platform = null,
259
156
  preferNative = false,
260
- sourceExts = ['js', 'jsx', 'json', 'ts', 'tsx'],
157
+ sourceExts = METRO_SOURCE_EXTS,
261
158
  metro = false,
159
+ assetExts = METRO_ASSET_EXTS,
160
+ assetResolutions = METRO_ASSET_RESOLUTIONS,
262
161
  typescript = false,
263
162
  typescriptPaths = null,
264
- metroKeepEntryOnBrowserFalse = METRO_KEEP_ENTRY_ON_BROWSER_FALSE,
265
163
  host = diskHost,
164
+ kept,
266
165
  } = {}) {
267
- const opts = { platform, preferNative, sourceExts, mainFields, metro, typescript, metroKeepEntryOnBrowserFalse, host }
268
- // An importer in node_modules gets no --typescript mapping (inNodeModules), wherever its import lands.
166
+ const read = manifestReader(host)
167
+ const outputs = typescript ? typescriptPaths?.outputs ?? tsconfigOutputsOf({ host }) : null
168
+ const opts = { platform, preferNative, sourceExts, mainFields, typescript, outputs, host, read }
169
+ // An importer in node_modules gets no --typescript mapping, wherever its import lands.
269
170
  const fromNodeModules = { ...opts, typescript: false }
270
- // Node answers a builtin name with the builtin itself, so an `exports`-bearing package named like
271
- // one (see the header) resolves through this instead, with builtins off; built on first use.
171
+ // Node answers a builtin name with the builtin, so a package named like one resolves through this, builtins off.
272
172
  let packageResolver
273
- // `callConditions` (from scan) is the parent's format-driven condition set, so `exports`
274
- // delegation matches Node resolving from THAT file; falls back to configured `conditions`.
275
- const resolve = function resolve(parentFile, specifier, callConditions) {
173
+ const nodeResolver = () => (packageResolver ??= createNodeResolver(host))
174
+ // --typescript resolves Metro's misses again over typescriptView, never from node_modules, so it never overrides Metro.
175
+ const metroResolver = memoized(({ conditionNames, substituting }) => {
176
+ const view = metroHost(host, mainFields)
177
+ return createMetroResolver({ host: substituting ? typescriptView(view, opts) : view, sourceExts, assetExts, assetResolutions, mainFields, conditionNames, conditionsByPlatform: {}, preferNativePlatform: preferNative })
178
+ }, ({ conditionNames, substituting }) => `${substituting}\0${conditionNames.join('\0')}`)
179
+ const viaMetro = (parentFile, specifier, conds) => {
180
+ const conditionNames = [...conds].filter((name) => !METRO_OWN_CONDITIONS.has(name))
181
+ const request = { platform, isESMImport: conds.has('import') }
182
+ let resolution = metroResolver({ conditionNames, substituting: false })(parentFile, specifier, request)
183
+ if (resolution === null && typescript && !inNodeModules(parentFile, host)) resolution = metroResolver({ conditionNames, substituting: true })(parentFile, specifier, request)
184
+ const remapped = () => {
185
+ const imp = nearestPackage(parentFile, host, read)
186
+ return imp !== null && matchRedirect(mergeRedirectMap(imp.pkg, mainFields), specifier) !== undefined
187
+ }
188
+ return scanResolution(resolution, resolution === null && isBuiltin(specifier) && !remapped())
189
+ }
190
+ // `callConditions`: scan's, by the parent's format. What a miss tried goes in `tried`, the missTargets.
191
+ const resolve = function resolve(parentFile, specifier, callConditions, tried) {
276
192
  const fileOpts = typescript && inNodeModules(parentFile, host) ? fromNodeModules : opts
277
193
  const conds = new Set(callConditions ?? conditions)
194
+ const probe = (base) => {
195
+ const hit = resolveFileOrDir(base, fileOpts, tried)
196
+ if (hit === null) tried.push(base)
197
+ return hit
198
+ }
278
199
  const viaNode = (spec) => {
279
200
  try {
280
201
  if (!isBuiltin(spec)) return fileResolution(host.resolve(parentFile, spec, conds), host)
281
- packageResolver ??= createNodeResolver(host)
282
- return fileResolution(packageResolver.resolve(parentFile, spec, conds, { builtins: false }), host)
283
- } catch {
202
+ return fileResolution(nodeResolver().resolve(parentFile, spec, conds, { builtins: false }), host)
203
+ } catch (error) {
204
+ if (typeof error.target === 'string') tried.push(error.target)
284
205
  return null
285
206
  }
286
207
  }
287
- // A bare specifier (`mod`, `mod/sub`) through node_modules.
288
208
  const viaPackage = (spec) => {
289
209
  const loc = locatePackage(dirname(parentFile), spec, host)
290
210
  if (!loc) return null
291
- const pkg = readJson(join(loc.pkgDir, 'package.json'), host) ?? {}
292
- // `exports` wins over mainFields; Node's algorithm resolves it (with conditions) correctly.
211
+ const pkg = read(join(loc.pkgDir, 'package.json')) ?? {}
293
212
  if (pkg.exports != null) return viaNode(spec)
294
- // A bare package import resolves its directory via the same dir algorithm as any other.
295
- if (loc.subpath === '') return resolveFileOrDir(loc.pkgDir, fileOpts)
213
+ if (loc.subpath === '') return probe(loc.pkgDir)
296
214
  const sub = `./${loc.subpath}`
297
215
  const r = matchRedirect(mergeRedirectMap(pkg, mainFields), sub)
298
216
  if (r === false) return { empty: true }
299
- const target = typeof r === 'string' ? r : sub
300
- return resolveFileOrDir(join(loc.pkgDir, target), fileOpts)
217
+ return probe(join(loc.pkgDir, typeof r === 'string' ? r : sub))
301
218
  }
302
- // `#name` subpath imports use the `imports` field + conditions; Node's algorithm handles them.
219
+ if (metro) return viaMetro(parentFile, specifier, conds)
303
220
  if (specifier.startsWith('#')) return viaNode(specifier)
304
221
 
305
222
  let spec = specifier
306
- // Redirect via the IMPORTER's browser/react-native map, BEFORE the builtin check on purpose:
307
- // a map entry can disable or shim a builtin (`{"crypto": false}` / `"crypto-browserify"`).
308
- const imp = nearestPackage(parentFile, host)
223
+ // The importer's map applies before the builtin check: it can disable or shim a builtin (`{"crypto": false}`).
224
+ const imp = nearestPackage(parentFile, host, read)
309
225
  if (imp) {
310
226
  const map = mergeRedirectMap(imp.pkg, mainFields)
311
227
  let r
@@ -313,58 +229,45 @@ export function createFieldResolver({
313
229
  const abs = isAbsolute(spec) ? spec : resolvePath(dirname(parentFile), spec)
314
230
  r = matchRedirect(map, `./${toPosix(relative(imp.pkgDir, abs))}`)
315
231
  } else {
316
- r = map.get(spec) // a bare specifier (`mod`, `mod/sub`) matches the map's bare keys
232
+ r = map.get(spec)
317
233
  }
318
234
  if (r === false) return { empty: true }
319
235
  if (typeof r === 'string') {
320
- // Browser-map targets are relative to the PACKAGE ROOT, not the importing file; a
321
- // bare-module target re-enters resolution below.
322
- if (r.startsWith('.') || isAbsolute(r)) {
323
- return resolveFileOrDir(isAbsolute(r) ? r : resolvePath(imp.pkgDir, r), fileOpts)
324
- }
236
+ // A path target is relative to the package root, not the importing file; a bare one is resolved below.
237
+ if (r.startsWith('.') || isAbsolute(r)) return probe(isAbsolute(r) ? r : resolvePath(imp.pkgDir, r))
325
238
  spec = r
326
239
  }
327
240
  }
328
-
329
- if (spec.startsWith('.') || isAbsolute(spec)) {
330
- const base = isAbsolute(spec) ? spec : resolvePath(dirname(parentFile), spec)
331
- return resolveFileOrDir(base, fileOpts)
332
- }
333
-
334
- // A builtin the browser map did not remap: its `node:` form names the builtin itself; a bare
335
- // name is the installed package of that name (see the header), the builtin where none resolves.
241
+ if (spec.startsWith('.') || isAbsolute(spec)) return probe(isAbsolute(spec) ? spec : resolvePath(dirname(parentFile), spec))
336
242
  if (isBuiltin(spec)) return spec.startsWith('node:') ? { builtin: true } : (viaPackage(spec) ?? { builtin: true })
337
243
  return viaPackage(spec)
338
244
  }
339
- if (!typescript) return resolve
340
- // --typescript: when the whole field flow leaves the specifier unresolved, give tsc's mapping
341
- // the same shot the scanner's fallback gets, via the shared dispatcher. On this path it covers
342
- // the layers the field resolver delegates to Node -- `exports`-bearing packages and `#` subpath
343
- // imports, whose targets may name compiled files existing only as TS source -- plus tsconfig
344
- // `paths` aliases; misses only, so no field/redirect/suffix resolution is ever overridden.
345
- // (Relative paths re-probe tsc-style too -- redundant after resolveSourceFile, but harmless.)
346
- return function resolveWithTypescriptFallback(parentFile, specifier, callConditions) {
347
- const resolved = resolve(parentFile, specifier, callConditions)
348
- if (resolved) return resolved
349
- const hit = resolveTypescriptFallback(parentFile, specifier, {
350
- conditions: new Set(callConditions ?? conditions),
351
- paths: typescriptPaths,
352
- host,
353
- })
354
- return hit == null ? null : fileResolution(hit, host)
245
+ // --typescript: a miss of the whole field flow, and only a miss, gets the scanner's fallback too.
246
+ const resolveWithTypescriptFallback = (parentFile, specifier, callConditions, tried) => {
247
+ const resolved = resolve(parentFile, specifier, callConditions, tried)
248
+ // Under --metro an asset is Metro's asset rule's to resolve, as tsc never does.
249
+ if (resolved || !typescript || (metro && isAssetFile(specifier, assetExts))) return resolved
250
+ const conds = new Set(callConditions ?? conditions)
251
+ const hit = resolveTypescriptFallback(parentFile, specifier, { conditions: conds, paths: typescriptPaths, host })
252
+ if (hit != null) return fileResolution(hit, host)
253
+ const aliased = typescriptPaths !== null && !RELATIVE_REQUEST.test(specifier) && !isAbsolute(specifier) && !specifier.startsWith('#') && !inNodeModules(parentFile, host)
254
+ if (aliased) tried.push(...typescriptPaths.matchPaths(specifier, parentFile))
255
+ return null
355
256
  }
257
+ // Once per directory (all a file's resolving reads), specifier and conditions, kept as the manifests are and in `kept`.
258
+ const resolutions = hostMemo(host, { across: kept })
259
+ const of = (parentFile, specifier, callConditions) => resolutions(`${dirname(parentFile)}\0${specifier}\0${[...callConditions ?? conditions].join('\0')}`, () => {
260
+ const tried = []
261
+ return { resolution: resolveWithTypescriptFallback(parentFile, specifier, callConditions, tried), tried }
262
+ })
263
+ return Object.assign((parentFile, specifier, callConditions) => of(parentFile, specifier, callConditions).resolution, {
264
+ missTargets: (parentFile, specifier, callConditions) => of(parentFile, specifier, callConditions).tried,
265
+ })
356
266
  }
357
267
 
358
- // True when `format` is an ESM family (drives the base condition set, mirroring scan).
359
- function isModuleFormat(format) {
360
- return format === 'module' || format === 'module-typescript'
361
- }
362
-
363
- // Condition set for a parent of the given format, as scan's #conditionSet gives a custom resolver:
364
- // `import` or `require` by format, `default` (which Node's resolver matches anyway), plus extras.
365
- // A bundler's base, not Node's: esbuild, webpack and Metro assert `import`/`require` and
366
- // `default`, never `node`, so an `exports` map listing `node` first can't win over the extras.
367
- // Order is irrelevant (Node membership-tests against exports key order).
268
+ // As scan's #conditionSet gives a custom resolver: a bundler's base, not Node's. esbuild, webpack and Metro assert
269
+ // `import`/`require` and `default`, never `node`, so an `exports` map listing `node` first can't win over the extras.
368
270
  export function resolveConditions(format, extras = []) {
369
- return [...new Set([isModuleFormat(format) ? 'import' : 'require', 'default', ...extras])]
271
+ const esm = format === 'module' || format === 'module-typescript'
272
+ return [...new Set([esm ? 'import' : 'require', 'default', ...extras])]
370
273
  }