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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +1 -1
  2. package/bin/stasis.js +26 -11
  3. package/package.json +10 -9
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +113 -233
  6. package/src/babel.js +39 -122
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +5 -9
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +50 -166
  11. package/src/cmd/bundle-options.js +110 -167
  12. package/src/cmd/bundle.js +861 -1344
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +46 -27
  15. package/src/cmd/output.js +17 -12
  16. package/src/cmd/sbom.js +3 -8
  17. package/src/cmd/tokens.js +10 -23
  18. package/src/define.js +34 -97
  19. package/src/diff.js +72 -128
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +10 -25
  22. package/src/installed.js +265 -0
  23. package/src/json-stream.js +4 -9
  24. package/src/loader-mock.js +3 -8
  25. package/src/loader.js +1 -5
  26. package/src/loaders/bash.js +41 -93
  27. package/src/loaders/cargo.js +298 -805
  28. package/src/loaders/foundry.js +109 -285
  29. package/src/loaders/paths.js +13 -13
  30. package/src/loaders/php.js +210 -489
  31. package/src/loaders/rust.js +507 -1430
  32. package/src/loaders/solidity-ownership.js +48 -128
  33. package/src/loaders/solidity.js +39 -122
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +9 -33
  37. package/src/metro-resolver.js +20 -47
  38. package/src/metro-transformer.js +0 -5
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +2 -5
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +90 -220
  44. package/src/resolve-node.js +27 -45
  45. package/src/resolve-typescript.js +109 -313
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +52 -128
  49. package/src/scan.js +136 -283
  50. package/src/sixel.js +18 -41
  51. package/src/table.js +14 -35
  52. package/src/validate-notes.d.ts +3 -2
  53. package/src/validate-notes.js +25 -19
  54. package/src/validate.d.ts +38 -11
  55. package/src/validate.js +478 -512
  56. package/src/vfs-bundle/entries.js +40 -57
  57. package/src/vfs-bundle/github.js +88 -121
  58. package/src/vfs-bundle/glob.js +4 -45
  59. package/src/vfs-bundle/lazy.js +27 -56
  60. package/src/vfs-bundle/prisma.js +167 -110
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +295 -318
  63. package/src/vfs-bundle/yarnclean.js +10 -31
  64. package/src/vfs-bundle.js +23 -64
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +75 -231
  67. package/src/installed-commits.js +0 -184
@@ -1,59 +1,29 @@
1
1
  import { basename, dirname, extname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path'
2
2
 
3
- import { isTypeDeclaration, relativeEscapes } from '@exodus/stasis-core/util'
3
+ import { isTypeDeclaration, memoized, relativeEscapes } from '@exodus/stasis-core/util'
4
4
  import { diskHost } from '@exodus/stasis-core/host'
5
- import { untouchedMemo } from './vfs-bundle/lazy.js'
6
-
7
- // tsc-style module resolution (`--typescript`), shared by BOTH JS resolvers -- scan.js's built-in
8
- // Node resolver and resolve-fields.js's legacy-field resolver -- so the flag means one thing
9
- // everywhere: when normal resolution misses and tsc would land on an on-disk TypeScript source,
10
- // complete the miss with that file. It never rewrites a resolution that succeeded, so an on-disk
11
- // `.js` always beats its `.ts` twin. The rules, in the shapes they apply to:
12
- // - extension substitution: `./x.js` -> `./x.ts` (`.jsx` -> `.tsx`, `.mjs` -> `.mts`,
13
- // `.cjs` -> `.cts`) -- tsc never rewrites specifiers, so TS sources import each other by their
14
- // OUTPUT names, and the specifier names a file that only exists as its TS source;
15
- // - extension/index completion for an extensionless path (`./util` -> `./util.ts`,
16
- // `./dir` -> `./dir/index.ts`), incl. through a directory's package.json `main`;
17
- // - the same substitution applied to manifest-declared targets: a package `main`, an `exports`
18
- // target, a `#name` `imports` target naming a compiled file whose only on-disk form is TS;
19
- // - tsc's `outDir` -> `rootDir` inversion: a workspace package's unbuilt output (`./dist/x.js`)
20
- // maps to the source tsc builds it from (`./src/x.ts`; see fromOutputSource), here and in the
21
- // field resolvers' own probes;
22
- // - tsconfig `compilerOptions.paths` aliases (see loadTsconfigPaths), consulted for bare
23
- // specifiers nothing else resolved. Node never probed an alias target, so its completion also
24
- // tries the JS extensions after the TS ones (`@/x` -> x.ts, then x.js), as tsc does.
25
- // This module also homes the generic manifest helpers (readJson/locatePackage/nearestPackage)
26
- // both resolvers share -- it is the dependency-free lower layer, importing from neither.
27
-
28
- // tsc's extension substitution table: the JS output extensions mapped back to the TS source
29
- // siblings that may sit on disk in their place. JS_OUTPUT_EXTS is derived, so the two cannot drift.
5
+ import { hostMemo } from './vfs-bundle/lazy.js'
6
+
7
+ // tsc-style module resolution (`--typescript`) for scan.js and resolve-fields.js: it only completes a miss with
8
+ // an on-disk TypeScript source, so a resolution that succeeded is never rewritten (an on-disk `.js` beats its `.ts`).
9
+
30
10
  const TS_SIBLING_EXTS = new Map([
31
11
  ['.js', ['.ts', '.tsx']],
32
12
  ['.jsx', ['.tsx']],
33
13
  ['.mjs', ['.mts']],
34
14
  ['.cjs', ['.cts']],
35
15
  ])
36
- const JS_OUTPUT_EXTS = new Set(TS_SIBLING_EXTS.keys())
37
16
 
38
- // The TS source siblings of a path/specifier naming a JS output extension (./x.js -> ./x.ts).
39
- // Returns [] for a non-substitutable name (extensionless, already-TS, .json, unknown, dotfile --
40
- // extname sees no extension in './.js', matching the extensionless gates downstream). Candidates
41
- // spelling a type declaration (./x.d.js -> ./x.d.ts) are returned too: every probe site refuses
42
- // declarations (types-only, erased at runtime), so the screen lives at probe time, once.
17
+ // A declaration's spelling (./x.d.js -> ./x.d.ts) is among them: every probe site refuses one.
43
18
  export function typescriptSiblings(name) {
44
19
  const ext = extname(name)
45
- const exts = TS_SIBLING_EXTS.get(ext)
46
- if (!exts) return []
47
20
  const stem = name.slice(0, -ext.length)
48
- return exts.map((e) => `${stem}${e}`)
21
+ return TS_SIBLING_EXTS.get(ext)?.map((e) => `${stem}${e}`) ?? []
49
22
  }
50
23
 
51
- // Extensions that never take the appended-`.ts` completion: JS outputs (substitution territory)
52
- // and the extensions a resolver could already land on directly. Anything else (`./x.service`) is
53
- // completed like an extensionless name, matching tsc's candidate list.
54
- const NO_COMPLETION_EXTS = new Set([...JS_OUTPUT_EXTS, '.ts', '.tsx', '.mts', '.cts', '.json'])
24
+ // Never completed by appending `.ts`; any other extension (`./x.service`) is, as tsc's candidate list has it.
25
+ const NO_COMPLETION_EXTS = new Set([...TS_SIBLING_EXTS.keys(), '.ts', '.tsx', '.mts', '.cts', '.json'])
55
26
 
56
- // `path`'s real path, or `path` itself where it has none (not on disk).
57
27
  function realpathOr(path, host) {
58
28
  try {
59
29
  return host.realpath(path)
@@ -62,22 +32,17 @@ function realpathOr(path, host) {
62
32
  }
63
33
  }
64
34
 
65
- export function isFile(p, host = diskHost) {
66
- return host.stat(p)?.isFile() ?? false
67
- }
68
-
69
- export function isDir(p, host = diskHost) {
70
- return host.stat(p)?.isDirectory() ?? false
71
- }
35
+ export const isFile = (p, host = diskHost) => host.stat(p)?.isFile() ?? false
36
+ export const isDir = (p, host = diskHost) => host.stat(p)?.isDirectory() ?? false
72
37
 
73
- export function readJson(file, host = diskHost) {
38
+ export function readManifest(file, host = diskHost) {
74
39
  let text
75
40
  try {
76
41
  text = host.readFile(file).toString('utf8')
77
42
  } catch {
78
- return null // absent / unreadable -- no manifest here
43
+ return null
79
44
  }
80
- // A manifest that EXISTS but is malformed must fail closed (Node throws rather than resolving past it).
45
+ // A manifest that exists but is malformed fails closed, as Node throws rather than resolving past it.
81
46
  try {
82
47
  return JSON.parse(text)
83
48
  } catch (cause) {
@@ -85,96 +50,51 @@ export function readJson(file, host = diskHost) {
85
50
  }
86
51
  }
87
52
 
88
- // Nearest node_modules/<pkg> up from `fromDir` (handles @scope/name). Returns { pkgDir, subpath }
89
- // (subpath '' = bare package import), or null if not installed up the tree.
90
53
  export function locatePackage(fromDir, spec, host = diskHost) {
91
54
  const parts = spec.split('/')
92
55
  const pkgLen = spec.startsWith('@') ? 2 : 1
93
56
  if (parts.length < pkgLen || parts.slice(0, pkgLen).some((p) => !p)) return null
94
57
  const pkgName = parts.slice(0, pkgLen).join('/')
95
58
  const subpath = parts.slice(pkgLen).join('/')
96
- let dir = fromDir
97
- while (true) {
98
- // Skip a dir literally named node_modules (basename, not endsWith — `my-node_modules` must not match).
99
- if (basename(dir) !== 'node_modules') {
100
- const pkgDir = join(dir, 'node_modules', pkgName)
101
- if (isDir(pkgDir, host)) return { pkgDir, subpath }
102
- }
103
- const parent = dirname(dir)
104
- if (parent === dir) return null
105
- dir = parent
59
+ for (let dir = fromDir; ; dir = dirname(dir)) {
60
+ const pkgDir = join(dir, 'node_modules', pkgName)
61
+ if (basename(dir) !== 'node_modules' && isDir(pkgDir, host)) return { pkgDir, subpath }
62
+ if (dirname(dir) === dir) return null
106
63
  }
107
64
  }
108
65
 
109
- // Nearest package.json at/above `file`'s dir — the package whose fields (browser/RN map, imports)
110
- // govern the file's own imports. `read` reads a manifest, as readJson does.
111
- export function nearestPackage(file, host = diskHost, read = readJson) {
112
- let dir = dirname(file)
113
- while (true) {
66
+ export function nearestPackage(file, host = diskHost, read = readManifest) {
67
+ for (let dir = dirname(file); ; dir = dirname(dir)) {
114
68
  const pkgPath = join(dir, 'package.json')
115
- if (isFile(pkgPath, host)) {
116
- const pkg = read(pkgPath, host)
117
- if (pkg) return { pkgDir: dir, pkg }
118
- }
119
- const parent = dirname(dir)
120
- if (parent === dir) return null
121
- dir = parent
69
+ const pkg = isFile(pkgPath, host) ? read(pkgPath, host) : null
70
+ if (pkg) return { pkgDir: dir, pkg }
71
+ if (dirname(dir) === dir) return null
122
72
  }
123
73
  }
124
74
 
125
- // A probe candidate is a target only if it names a real file that is not a type declaration
126
- // (a `.d.ts` is types-only, erased at runtime -- tsc records it for types, never for emit).
127
- const probe = (p, host) => (!isTypeDeclaration(p) && isFile(p, host) ? p : null)
75
+ // A `.d.ts` is types-only, erased at runtime: no resolution lands on one.
76
+ export const isSourceFile = (path, host = diskHost) => !isTypeDeclaration(path) && isFile(path, host)
77
+ const firstSource = (candidates, host) => candidates.find((path) => isSourceFile(path, host)) ?? null
128
78
 
129
- // The extensions tsc's completion appends, in its order (tryAddingExtensions): .ts, .tsx, then --
130
- // with `js`, for a path Node never probed (a tsconfig paths target) -- .js, .jsx. A path Node
131
- // already completed needs only the TS ones. .d.ts (tsc's third) is never a target (see probe).
79
+ // tsc's tryAddingExtensions order; `.js`/`.jsx` only with `js`, for a path Node never probed (a tsconfig paths target).
132
80
  const completionExts = (js) => (js ? ['.ts', '.tsx', '.js', '.jsx'] : ['.ts', '.tsx'])
133
81
 
134
- // LOAD_INDEX with tsc's completions: dir/index.ts, dir/index.tsx (+ index.js/index.jsx with `js`).
135
- // Without `js`, Node already probed the .js/.json indexes before the fallback ever runs.
136
- function probeIndex(dir, exts, host) {
137
- for (const ext of exts) {
138
- const hit = probe(join(dir, `index${ext}`), host)
139
- if (hit) return hit
140
- }
141
- return null
142
- }
82
+ const probeIndex = (dir, exts, host) => firstSource(exts.map((ext) => join(dir, `index${ext}`)), host)
143
83
 
144
- // Probe an absolute `base` the way tsc completes a missed path: the literal file (manifest-declared
145
- // targets are never probed by Node, so a paths/main target can hit literally), its TS siblings,
146
- // the appended-extension completion, and -- when `dir` allows and `base` is a directory -- the
147
- // directory's package.json `main` (substituted + completed like any path, mirroring Node's
148
- // LOAD_AS_DIRECTORY) then its index. `dirOnly` skips the file rules for specs Node treats as
149
- // directory-only ('.', '..', a trailing '/'), so './' never probes the pathological '.ts' dotfile.
150
- // `completion`/`dir` are off for exports/imports targets: Node requires those to name exact files,
151
- // so only substitution applies (matching tsc's node16 rules). `js` completes JS extensions too, for
152
- // a base Node never probed (see completionExts). `outputs` maps what still misses to an unbuilt
153
- // output's source (fromOutputSource).
84
+ // `dirOnly` skips the file rules ('.', '..', a trailing '/'). Exports and imports targets name exact files, so they
85
+ // take neither `completion` nor `dir`.
154
86
  function probeTypescriptTarget(base, { js = false, dirOnly = false, completion = true, dir = true, outputs = null, host = diskHost } = {}) {
155
- const rules = { js, dirOnly, completion, dir, host }
156
87
  const exts = completionExts(js)
157
88
  if (!dirOnly) {
158
- const literal = probe(base, host)
159
- if (literal) return literal
160
- for (const cand of typescriptSiblings(base)) {
161
- const hit = probe(cand, host)
162
- if (hit) return hit
163
- }
164
- if (completion && !NO_COMPLETION_EXTS.has(extname(base))) {
165
- for (const ext of exts) {
166
- const hit = probe(`${base}${ext}`, host)
167
- if (hit) return hit
168
- }
169
- }
89
+ const completed = completion && !NO_COMPLETION_EXTS.has(extname(base)) ? exts.map((ext) => `${base}${ext}`) : []
90
+ const hit = firstSource([base, ...typescriptSiblings(base), ...completed], host)
91
+ if (hit) return hit
170
92
  }
171
93
  if (dir && isDir(base, host)) {
172
- const pkg = readJson(join(base, 'package.json'), host)
173
- const main = typeof pkg?.main === 'string' && pkg.main.length > 0 ? pkg.main : null
174
- if (main) {
175
- // LOAD_AS_FILE(main) with substitution/completion, then LOAD_INDEX(main), each of its source
176
- // too where it is unbuilt; a broken main falls through to the package index, like Node.
177
- const entry = resolvePath(base, main)
94
+ const pkg = readManifest(join(base, 'package.json'), host)
95
+ if (typeof pkg?.main === 'string' && pkg.main.length > 0) {
96
+ // A broken main falls through to the package index, like Node.
97
+ const entry = resolvePath(base, pkg.main)
178
98
  const fromMain = (path) => probeTypescriptTarget(path, { js, dir: false, host }) ?? probeIndex(path, exts, host)
179
99
  const hit = fromMain(entry) ?? fromOutputSource(entry, fromMain, { outputs, host, pkgDir: base })
180
100
  if (hit) return hit
@@ -182,15 +102,10 @@ function probeTypescriptTarget(base, { js = false, dirOnly = false, completion =
182
102
  const hit = probeIndex(base, exts, host)
183
103
  if (hit) return hit
184
104
  }
185
- return fromOutputSource(base, (input) => probeTypescriptTarget(input, rules), { outputs, host })
105
+ return fromOutputSource(base, (input) => probeTypescriptTarget(input, { js, dirOnly, completion, dir, host }), { outputs, host })
186
106
  }
187
107
 
188
- // --- tsc's `outDir` -> `rootDir` inversion ---
189
-
190
- // A package's tsc layout, by the tsconfig.json beside its package.json; null without `outDir`
191
- // (outputs then sit beside their sources, which substitution maps) or in node_modules (installed
192
- // packages are used as published). Without `rootDir` the root is the tsconfig's directory, as
193
- // TypeScript 6 takes it; an older tsc infers it from its inputs, which this cannot.
108
+ // Without `rootDir` the root is the tsconfig's dir, as TypeScript 6 takes it (an older tsc infers it from its inputs).
194
109
  export function tsconfigOutputs(pkgDir, host = diskHost) {
195
110
  const dir = realpathOr(pkgDir, host)
196
111
  if (IN_NODE_MODULES.test(dir)) return null
@@ -210,19 +125,16 @@ function leniently(lenient, read) {
210
125
  }
211
126
  }
212
127
 
213
- // tsconfigOutputs, cached as a lazy tree allows (untouchedMemo). `lenient` is for builds that only
214
- // hint, where a tsconfig.json that does not load maps nothing rather than failing the build.
128
+ // `lenient` is for builds that only hint: a tsconfig.json that doesn't load maps nothing rather than failing them.
215
129
  export function tsconfigOutputsOf({ host = diskHost, lenient = false } = {}) {
216
- const layouts = untouchedMemo(host.touches, { retouch: host.retouch })
130
+ const layouts = hostMemo(host)
217
131
  return (pkgDir) => {
218
132
  const dir = realpathOr(pkgDir, host)
219
133
  return layouts(dir, () => leniently(lenient, () => tsconfigOutputs(dir, host)))
220
134
  }
221
135
  }
222
136
 
223
- // The package whose tsc build `path` would be an output of: the nearest package.json beside a
224
- // tsconfig.json, named or not. One without (a `type` marker, a manifest copied into `dist/` to
225
- // publish from) builds nothing. An installed package is none.
137
+ // A package.json with no tsconfig.json beside it builds nothing (a `type` marker, a manifest copied into `dist/`).
226
138
  function packageHolding(path, host) {
227
139
  for (let dir = dirname(path); basename(dir) !== 'node_modules'; dir = dirname(dir)) {
228
140
  if (isFile(join(dir, 'package.json'), host)) {
@@ -234,12 +146,8 @@ function packageHolding(path, host) {
234
146
  return null
235
147
  }
236
148
 
237
- // tsc's mapping of an output back to its input (tryLoadInputFileForPath): where `path` lies under
238
- // its package's `outDir`, `probeSource` of the same place under `rootDir` (`dist/x.js` ->
239
- // `src/x.js`, whose TS siblings substitution finds), else null. Call it only once `path` itself
240
- // missed: the tsconfig.json is read, and can throw, only then. `pkgDir` is the package that names
241
- // `path` (its `main`, an `exports` target), where known: its `outDir` may lie outside it
242
- // (`../../dist/dep`).
149
+ // tsc's tryLoadInputFileForPath. Call it only once `path` missed, as it reads the tsconfig.json. `pkgDir`: the
150
+ // package naming `path`, whose `outDir` may lie outside it.
243
151
  export function fromOutputSource(path, probeSource, { outputs, host = diskHost, pkgDir } = {}) {
244
152
  if (outputs == null) return null
245
153
  const owner = pkgDir ?? packageHolding(path, host)
@@ -249,73 +157,49 @@ export function fromOutputSource(path, probeSource, { outputs, host = diskHost,
249
157
  return relativeEscapes(rel) ? null : probeSource(join(layout.rootDir, rel))
250
158
  }
251
159
 
252
- // --- package `exports`/`imports` map resolution (candidate generation) ---
253
-
254
- // Expand a target value (string | array | conditions object | null) to the target strings the
255
- // active `conditions` select, wildcard-substituted. Mirrors Node's PACKAGE_TARGET_RESOLVE closely
256
- // enough for fallback candidates: a conditions object commits to its FIRST matching key ('default'
257
- // always matches); an array contributes its entries in order (the probe decides).
160
+ // As Node's PACKAGE_TARGET_RESOLVE, a conditions object commits to its first matching key; an array yields all.
258
161
  function expandTarget(value, wildcard, conditions) {
259
- if (typeof value === 'string') {
260
- return [wildcard == null ? value : value.replaceAll('*', wildcard)]
261
- }
262
- if (Array.isArray(value)) {
263
- return value.flatMap((v) => expandTarget(v, wildcard, conditions))
264
- }
265
- if (value !== null && typeof value === 'object') {
266
- for (const [key, v] of Object.entries(value)) {
267
- if (key === 'default' || conditions.has(key)) return expandTarget(v, wildcard, conditions)
268
- }
269
- }
270
- return [] // null (an explicit block) or no matching condition
162
+ if (typeof value === 'string') return [wildcard == null ? value : value.replaceAll('*', wildcard)]
163
+ if (Array.isArray(value)) return value.flatMap((v) => expandTarget(v, wildcard, conditions))
164
+ if (value === null || typeof value !== 'object') return []
165
+ const key = Object.keys(value).find((k) => k === 'default' || conditions.has(k))
166
+ return key === undefined ? [] : expandTarget(value[key], wildcard, conditions)
271
167
  }
272
168
 
273
- // Resolve `key` through an exports/imports-shaped map: exact key first (a key containing '*' is
274
- // never exact), else the best '*' pattern -- longest prefix, then longest key, exactly Node's
275
- // PATTERN_KEY_COMPARE order -- with the matched wildcard substituted into the targets.
276
- function resolveMapKey(map, key, conditions) {
277
- if (Object.hasOwn(map, key) && !key.includes('*')) return expandTarget(map[key], null, conditions)
169
+ // The longest prefix wins (with `longest`, then the longest key), the first of a tie.
170
+ function bestStarMatch(map, spec, { longest = false } = {}) {
278
171
  let best = null
279
- for (const pattern of Object.keys(map)) {
280
- const star = pattern.indexOf('*')
281
- if (star === -1 || pattern.indexOf('*', star + 1) !== -1) continue
282
- const prefix = pattern.slice(0, star)
283
- const suffix = pattern.slice(star + 1)
284
- if (key.length < prefix.length + suffix.length || !key.startsWith(prefix) || !key.endsWith(suffix)) continue
285
- if (best === null || prefix.length > best.prefix.length
286
- || (prefix.length === best.prefix.length && pattern.length > best.pattern.length)) {
287
- best = { pattern, prefix, suffix }
172
+ for (const key of Object.keys(map)) {
173
+ const star = key.indexOf('*')
174
+ if (star === -1 || key.indexOf('*', star + 1) !== -1) continue
175
+ const suffix = key.slice(star + 1)
176
+ if (spec.length < key.length - 1 || !spec.startsWith(key.slice(0, star)) || !spec.endsWith(suffix)) continue
177
+ if (best === null || star > best.star || (longest && star === best.star && key.length > best.key.length)) {
178
+ best = { key, star, wildcard: spec.slice(star, spec.length - suffix.length) }
288
179
  }
289
180
  }
290
- if (!best) return []
291
- const wildcard = key.slice(best.prefix.length, key.length - best.suffix.length)
292
- return expandTarget(map[best.pattern], wildcard, conditions)
181
+ return best
293
182
  }
294
183
 
295
- // A './' map target is only followed when it stays inside the package, like Node's
296
- // PACKAGE_TARGET_RESOLVE invalid-target rules ('..' hops and node_modules re-entry are refused).
297
- function validRelativeTarget(target) {
298
- return target.startsWith('./')
299
- && !target.split('/').some((seg) => seg === '..' || seg === 'node_modules')
184
+ // Exact key first (never one with a '*'), else the best pattern, in Node's PATTERN_KEY_COMPARE order.
185
+ function resolveMapKey(map, key, conditions) {
186
+ if (Object.hasOwn(map, key) && !key.includes('*')) return expandTarget(map[key], null, conditions)
187
+ const match = bestStarMatch(map, key, { longest: true })
188
+ return match === null ? [] : expandTarget(map[match.key], match.wildcard, conditions)
300
189
  }
301
190
 
302
- // Candidate targets for `subpathKey` ('.', './sub', or '#name') through a package's exports or
303
- // imports map. Exports sugar (a bare string/array/conditions object) is the '.' target.
191
+ // Node's PACKAGE_TARGET_RESOLVE refuses a target leaving the package ('..' hops and node_modules re-entry).
192
+ const validRelativeTarget = (target) => target.startsWith('./') && !target.split('/').some((seg) => seg === '..' || seg === 'node_modules')
193
+
194
+ // Exports sugar (a bare string, array or conditions object) is the '.' target.
304
195
  function manifestTargets(map, subpathKey, conditions) {
305
196
  if (map == null) return []
306
- let byKey = map
307
- if (typeof map !== 'object' || Array.isArray(map)
308
- || Object.keys(map).every((k) => !k.startsWith('.') && !k.startsWith('#'))) {
309
- if (subpathKey !== '.') return []
310
- byKey = { '.': map }
311
- }
312
- return resolveMapKey(byKey, subpathKey, conditions).filter((t) => validRelativeTarget(t))
197
+ const sugar = typeof map !== 'object' || Array.isArray(map) || Object.keys(map).every((k) => !k.startsWith('.') && !k.startsWith('#'))
198
+ if (sugar && subpathKey !== '.') return []
199
+ return resolveMapKey(sugar ? { '.': map } : map, subpathKey, conditions).filter(validRelativeTarget)
313
200
  }
314
201
 
315
- // tsc's mapping of `key` ('.' or './sub') through the `exports` of the package in `pkgDir` (or of
316
- // a '#name' key through its `imports`): the targets `conditions` select, substitution only (Node
317
- // requires exports/imports targets to name exact files) or an unbuilt output's source (`outputs`);
318
- // the first on disk, or null.
202
+ // `key`: '.', './sub' or '#name'. Substitution only, as Node requires exports and imports targets to name exact files.
319
203
  export function typescriptExportsTarget(pkgDir, exports, key, { conditions = new Set(), outputs = (dir) => tsconfigOutputs(dir, host), host = diskHost } = {}) {
320
204
  const probeTarget = (path) => probeTypescriptTarget(path, { completion: false, dir: false, host })
321
205
  for (const target of manifestTargets(exports, key, conditions)) {
@@ -326,10 +210,7 @@ export function typescriptExportsTarget(pkgDir, exports, key, { conditions = new
326
210
  return null
327
211
  }
328
212
 
329
- // --- tsconfig `compilerOptions.paths` ---
330
-
331
- // tsconfig.json is JSONC: strip // and /* */ comments and trailing commas (never inside string
332
- // literals), then JSON.parse. A config that exists but does not parse must fail closed.
213
+ // tsconfig.json is JSONC. A config that exists but does not parse fails closed.
333
214
  function parseJsonc(text, file) {
334
215
  if (text.charCodeAt(0) === 0xFE_FF) text = text.slice(1) // BOM
335
216
  let out = ''
@@ -354,14 +235,9 @@ function parseJsonc(text, file) {
354
235
  i = end === -1 ? text.length : end + 1
355
236
  continue
356
237
  }
357
- if (c === ',') {
358
- pendingComma = out.length
359
- } else if (c === '}' || c === ']') {
360
- if (pendingComma !== -1) out = `${out.slice(0, pendingComma)}${out.slice(pendingComma + 1)}`
361
- pendingComma = -1
362
- } else if (pendingComma !== -1 && !/\s/u.test(c)) {
363
- pendingComma = -1
364
- }
238
+ if ((c === '}' || c === ']') && pendingComma !== -1) out = `${out.slice(0, pendingComma)}${out.slice(pendingComma + 1)}`
239
+ if (c === ',') pendingComma = out.length
240
+ else if (!/\s/u.test(c)) pendingComma = -1
365
241
  out += c
366
242
  }
367
243
  try {
@@ -371,9 +247,7 @@ function parseJsonc(text, file) {
371
247
  }
372
248
  }
373
249
 
374
- // Resolve an `extends` target like tsc: relative/absolute against the extending file (with the
375
- // implied .json), bare through node_modules (the spelled path, its .json twin, or the package's
376
- // tsconfig.json). A named base that cannot be found fails closed -- its options are load-bearing.
250
+ // A named base that cannot be found fails closed: its options are load-bearing.
377
251
  function resolveExtendsTarget(fromFile, target, host) {
378
252
  if (target.startsWith('./') || target.startsWith('../') || isAbsolute(target)) {
379
253
  const p = resolvePath(dirname(fromFile), target)
@@ -389,12 +263,7 @@ function resolveExtendsTarget(fromFile, target, host) {
389
263
  throw new Error(`tsconfig extends target not found: '${target}' (from ${fromFile})`)
390
264
  }
391
265
 
392
- // The configs a tsconfig's `extends` chain reads, as { file, raw }: each base (in the order
393
- // `extends` names them) before the config extending it, and `file` last. A base two configs share
394
- // is listed under each, so folding the list in order, later over earlier, is tsc's nested merge,
395
- // where the second extender's resolved options carry the shared base's again. Like tsc's, the
396
- // cycle check is per branch: `extending` holds the configs extending `file`, and only a config that
397
- // extends itself, directly or not, throws.
266
+ // Each base before the config extending it, so folding them in order is tsc's nested merge. The cycle check is per branch.
398
267
  function* tsconfigChain(file, host, extending = new Set()) {
399
268
  if (extending.has(file)) throw new Error(`tsconfig extends cycle at ${file}`)
400
269
  const raw = parseJsonc(host.readFile(file).toString('utf8'), file)
@@ -404,8 +273,7 @@ function* tsconfigChain(file, host, extending = new Set()) {
404
273
  yield { file, raw }
405
274
  }
406
275
 
407
- // tsc's path-valued compilerOptions (a list's element by element), each made absolute against the
408
- // dir of the config declaring it, or, when it starts with `${configDir}`, against the loaded one's.
276
+ // tsc's path-valued options: against the declaring config's dir, or for `${configDir}` the loaded one's.
409
277
  const TSCONFIG_PATH_OPTIONS = new Set(['baseUrl', 'declarationDir', 'generateCpuProfile', 'generateTrace', 'outDir', 'outFile', 'rootDir', 'tsBuildInfoFile'])
410
278
  const TSCONFIG_PATH_LIST_OPTIONS = new Set(['rootDirs', 'typeRoots'])
411
279
  const CONFIG_DIR = '${configDir}'
@@ -414,10 +282,7 @@ const tsconfigPath = (value, dir, configDir) => {
414
282
  return value.startsWith(CONFIG_DIR) ? resolvePath(configDir, value.replace(CONFIG_DIR, './')) : resolvePath(dir, value)
415
283
  }
416
284
 
417
- // The `compilerOptions` a tsconfig resolves to across its `extends` chain, merged one level deep
418
- // as tsc merges them: each base in order, the extending file's own over them (`null` unsetting an
419
- // option), each path-valued option absolute, and `paths` as declared, with tsc's `pathsBasePath`,
420
- // the dir of the config declaring it.
285
+ // Merged one level deep across the `extends` chain, as tsc merges them (`null` unsetting an option).
421
286
  export function loadTsconfigCompilerOptions(file, host = diskHost) {
422
287
  let options = {}
423
288
  for (const { file: at, raw } of tsconfigChain(file, host)) {
@@ -433,97 +298,55 @@ export function loadTsconfigCompilerOptions(file, host = diskHost) {
433
298
  return options
434
299
  }
435
300
 
436
- // Load a tsconfig's `compilerOptions.paths` into a matcher, following `extends`. Returns null when
437
- // `file` is null or the effective config declares no paths. matchPaths(spec) returns the absolute
438
- // substituted targets of the BEST-matching key -- exact match first, else the '*' pattern with the
439
- // longest matched prefix, exactly one key, its targets in order (tsc tries no other key when they
440
- // all miss) -- resolved against `baseUrl`, or against the declaring config's dir without one
441
- // (TS 4.1 paths-without-baseUrl), or, starting with `${configDir}`, against `file`'s. Only
442
- // `baseUrl`/`paths` are used; malformed shapes (a non-array value, more than one '*' in a key or
443
- // target) fail closed like tsc's config errors.
301
+ // Only the one best key's targets: tsc tries no other when they miss. A malformed shape fails closed.
444
302
  export function loadTsconfigPaths(file, host = diskHost) {
445
303
  if (file == null) return null
446
304
  const { paths, pathsBasePath, baseUrl } = loadTsconfigCompilerOptions(file, host)
447
305
  if (paths == null || typeof paths !== 'object' || Object.keys(paths).length === 0) return null
448
- const starCount = (s) => s.split('*').length - 1
449
306
  for (const [key, targets] of Object.entries(paths)) {
450
307
  if (!Array.isArray(targets) || targets.some((t) => typeof t !== 'string')) {
451
308
  throw new Error(`tsconfig paths['${key}'] must be an array of strings (${file})`)
452
309
  }
453
- for (const t of [key, ...targets]) {
454
- if (starCount(t) > 1) throw new Error(`tsconfig paths pattern '${t}' has more than one '*' (${file})`)
455
- }
310
+ const starred = [key, ...targets].find((t) => t.split('*').length > 2)
311
+ if (starred !== undefined) throw new Error(`tsconfig paths pattern '${starred}' has more than one '*' (${file})`)
456
312
  }
457
313
  const base = typeof baseUrl === 'string' ? baseUrl : pathsBasePath
458
314
  return {
459
315
  matchPaths(spec) {
460
- let targets = null
461
- if (Object.hasOwn(paths, spec) && !spec.includes('*')) {
462
- targets = paths[spec].map((t) => ({ target: t, wildcard: null }))
463
- } else {
464
- let best = null
465
- for (const key of Object.keys(paths)) {
466
- const star = key.indexOf('*')
467
- if (star === -1) continue
468
- const prefix = key.slice(0, star)
469
- const suffix = key.slice(star + 1)
470
- if (spec.length < prefix.length + suffix.length || !spec.startsWith(prefix) || !spec.endsWith(suffix)) continue
471
- if (best === null || prefix.length > best.prefix.length) best = { key, prefix, suffix }
472
- }
473
- if (!best) return []
474
- const wildcard = spec.slice(best.prefix.length, spec.length - best.suffix.length)
475
- targets = paths[best.key].map((t) => ({ target: t, wildcard }))
476
- }
477
- return targets.map(({ target, wildcard }) =>
478
- tsconfigPath(wildcard == null ? target : target.replace('*', wildcard), base, dirname(file)))
316
+ const exact = Object.hasOwn(paths, spec) && !spec.includes('*')
317
+ const match = exact ? { key: spec, wildcard: null } : bestStarMatch(paths, spec)
318
+ if (match === null) return []
319
+ return paths[match.key].map((target) =>
320
+ tsconfigPath(match.wildcard === null ? target : target.replace('*', match.wildcard), base, dirname(file)))
479
321
  },
480
322
  }
481
323
  }
482
324
 
483
- // The tsconfig an explicit `--tsconfig` names, resolved against `baseDir`; it must exist (fail
484
- // closed on a typo). Without one, each package's own applies (packageTsconfigPaths).
485
325
  export function discoverTsconfig(baseDir, explicit, host = diskHost) {
486
326
  const p = resolvePath(baseDir, explicit)
487
327
  if (!isFile(p, host)) throw new Error(`tsconfig not found: ${explicit}`)
488
328
  return p
489
329
  }
490
330
 
491
- // Whether `dir` holds a package: a package.json naming one. One with no name is a `type` marker,
492
- // its files the package's above (as vfs-bundle's holdsPackage reads it).
493
- const holdsNamedPackage = (dir, host) => isFile(join(dir, 'package.json'), host) && readJson(join(dir, 'package.json'), host)?.name !== undefined
494
-
495
- // Whether `dir` declares a monorepo's workspaces: a pnpm-workspace.yaml, or a package.json
496
- // `workspaces` (npm's and yarn's).
497
- const declaresWorkspaces = (dir, host) => isFile(join(dir, 'pnpm-workspace.yaml'), host) || Boolean(readJson(join(dir, 'package.json'), host)?.workspaces)
498
-
499
- // The `paths` --typescript honours without --tsconfig: those of the tsconfig.json beside the
500
- // package.json of the package the importing file is in, as a matcher whose matchPaths(spec,
501
- // parentFile) is loadTsconfigPaths's for that config. The project is read up from `cwd` as the
502
- // State reads it: the directories holding a package.json, up to one holding .git or
503
- // pnpm-workspace.yaml, or up to `projectCwd` (the State's PROJECT_CWD, as yarn sets it). In a monorepo -- where one of those declares workspaces -- a file's package is
504
- // the nearest directory at or above it, up to that workspace root, holding a named package.json
505
- // (the root itself where none below it does); outside one, every file takes the one config beside
506
- // the nearest named package.json at or above `cwd` (or the top-most package.json, where none is
507
- // named). Never in node_modules: no walk enters a node_modules directory, and resolveTypescriptFallback
508
- // matches no alias for a file under one. Each config loads once, when first matched; with `lenient`,
509
- // one that doesn't load matches nothing instead of throwing. `outputs` is tsconfigOutputsOf's, as
510
- // lenient.
331
+ // A package.json with no name is a `type` marker: its files are the package's above.
332
+ const holdsNamedPackage = (dir, host) => isFile(join(dir, 'package.json'), host) && readManifest(join(dir, 'package.json'), host)?.name !== undefined
333
+ const declaresWorkspaces = (dir, host) => isFile(join(dir, 'pnpm-workspace.yaml'), host) || Boolean(readManifest(join(dir, 'package.json'), host)?.workspaces)
334
+
335
+ // The project is read up from `cwd` as the State reads it. In a monorepo a file's package is the nearest named one up
336
+ // to the workspace root (else the root); outside one, the nearest named one at or above `cwd` (else the top-most).
511
337
  export function packageTsconfigPaths(cwd, { host = diskHost, lenient = false, projectCwd } = {}) {
512
338
  const stop = projectCwd ? realpathOr(resolvePath(projectCwd), host) : null
513
- const dirs = [] // cwd and above, while the State's walk would go on; real paths, as importers are read
339
+ const dirs = [] // real paths, as importers are read
514
340
  for (let dir = realpathOr(resolvePath(cwd), host); basename(dir) !== 'node_modules'; dir = dirname(dir)) {
515
341
  dirs.push(dir)
516
- if (dir === stop) break
517
- if (host.stat(join(dir, '.git')) !== null || isFile(join(dir, 'pnpm-workspace.yaml'), host)) break
342
+ if (dir === stop || host.stat(join(dir, '.git')) !== null || isFile(join(dir, 'pnpm-workspace.yaml'), host)) break
518
343
  if (dirname(dir) === dir) break
519
344
  }
520
345
  const workspaceRoot = dirs.find((dir) => declaresWorkspaces(dir, host)) ?? null
521
346
  const projectPackage = workspaceRoot === null
522
347
  ? dirs.find((dir) => holdsNamedPackage(dir, host)) ?? dirs.findLast((dir) => isFile(join(dir, 'package.json'), host)) ?? null
523
348
  : null
524
- // The package directory `parentFile` is in, or null outside the workspace root. By its real path,
525
- // as inNodeModules reads it: a linked workspace package reached through node_modules takes its
526
- // own config, read where it lies, so a relative `extends` resolves as tsc resolves it.
349
+ // By real path: a linked workspace package takes its own config, so a relative `extends` resolves as tsc's does.
527
350
  const packageOf = (parentFile) => {
528
351
  if (workspaceRoot === null) return projectPackage
529
352
  for (let dir = dirname(realpathOr(parentFile, host)); basename(dir) !== 'node_modules'; dir = dirname(dir)) {
@@ -532,14 +355,10 @@ export function packageTsconfigPaths(cwd, { host = diskHost, lenient = false, pr
532
355
  }
533
356
  return null
534
357
  }
535
- const matchers = new Map() // package dir -> loadTsconfigPaths matcher, or null
536
- const matcherOf = (dir) => {
537
- if (!matchers.has(dir)) {
538
- const file = join(dir, 'tsconfig.json')
539
- matchers.set(dir, isFile(file, host) ? leniently(lenient, () => loadTsconfigPaths(file, host)) : null)
540
- }
541
- return matchers.get(dir)
542
- }
358
+ const matcherOf = memoized((dir) => {
359
+ const file = join(dir, 'tsconfig.json')
360
+ return isFile(file, host) ? leniently(lenient, () => loadTsconfigPaths(file, host)) : null
361
+ })
543
362
  return {
544
363
  matchPaths(spec, parentFile) {
545
364
  const dir = packageOf(parentFile)
@@ -549,33 +368,14 @@ export function packageTsconfigPaths(cwd, { host = diskHost, lenient = false, pr
549
368
  }
550
369
  }
551
370
 
552
- // --- the fallback dispatcher ---
553
-
554
- // Specs Node resolves as a directory only ('.', '..', a './..'-style tail, a trailing '/'):
555
- // the file rules are skipped for them, exactly as Node skips LOAD_AS_FILE.
371
+ // Specs Node resolves as a directory only, skipping LOAD_AS_FILE: '.', '..', a './..'-style tail, a trailing '/'.
556
372
  const DIR_ONLY_SPEC = /(?:^|\/)\.{1,2}$|\/$/u
557
-
558
- // A node_modules path segment, the last one included (the directory itself).
559
373
  const IN_NODE_MODULES = /(?:^|[\\/])node_modules(?:[\\/]|$)/u
560
374
 
561
- // Whether `file` lies in node_modules, by its real path where it has one (by its own, where it
562
- // doesn't): --typescript maps nothing from or into an installed package. A monorepo's workspace
563
- // packages, linked in through node_modules, really lie outside it, so they keep the mapping.
375
+ // By real path: workspace packages linked in through node_modules really lie outside it, so they keep the mapping.
564
376
  export const inNodeModules = (file, host = diskHost) => IN_NODE_MODULES.test(realpathOr(file, host))
565
377
 
566
- // Resolve `spec` from `parentFile` the way tsc would complete a resolution BOTH Node and the
567
- // legacy-field resolver missed. Returns the absolute path of the on-disk source, or null -- always
568
- // null from or into node_modules (inNodeModules). `conditions` gates exports/imports maps (same set
569
- // the failed resolution used); `paths` is a tsconfig paths matcher (loadTsconfigPaths, or
570
- // packageTsconfigPaths), or null. Dispatch by shape:
571
- // '#name' -> the parent package's `imports` targets, substitution only;
572
- // relative/abs -> path substitution/completion (+ directory main/index);
573
- // bare -> tsconfig paths aliases first (tsc consults them before node_modules; JS
574
- // completion too, as Node never probed the target), then
575
- // the named package: its `exports` targets (substitution only) when it has
576
- // them, else its `main`/index (bare root) or subpath (substitution/completion).
577
- // Any path naming a package's unbuilt output maps to its source (fromOutputSource), by
578
- // `paths.outputs` where `paths` has it.
378
+ // Always null from or into node_modules. `paths`: a tsconfig paths matcher, whose `outputs` map unbuilt outputs.
579
379
  export function resolveTypescriptFallback(parentFile, spec, { conditions = new Set(), paths = null, host = diskHost } = {}) {
580
380
  if (inNodeModules(parentFile, host)) return null
581
381
  const hit = typescriptTarget(parentFile, spec, { conditions, paths, host })
@@ -600,14 +400,10 @@ function typescriptTarget(parentFile, spec, { conditions, paths, host }) {
600
400
  }
601
401
  const loc = locatePackage(dirname(parentFile), spec, host)
602
402
  if (!loc) return null
603
- const pkg = readJson(join(loc.pkgDir, 'package.json'), host) ?? {}
403
+ const pkg = readManifest(join(loc.pkgDir, 'package.json'), host) ?? {}
604
404
  if (pkg.exports != null) {
605
- // `exports` fully governs a bare import (main is not a fallback); targets name exact files.
606
405
  return typescriptExportsTarget(loc.pkgDir, pkg.exports, loc.subpath === '' ? '.' : `./${loc.subpath}`, { conditions, outputs, host })
607
406
  }
608
- if (loc.subpath === '') {
609
- // Bare package root: LOAD_AS_DIRECTORY only (never `node_modules/dep.ts`).
610
- return probeTypescriptTarget(loc.pkgDir, { dirOnly: true, outputs, host })
611
- }
612
- return probeTypescriptTarget(join(loc.pkgDir, loc.subpath), { dirOnly: DIR_ONLY_SPEC.test(spec), outputs, host })
407
+ // A bare package root is LOAD_AS_DIRECTORY only (never `node_modules/dep.ts`).
408
+ return probeTypescriptTarget(join(loc.pkgDir, loc.subpath), { dirOnly: loc.subpath === '' || DIR_ONLY_SPEC.test(spec), outputs, host })
613
409
  }