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

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