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

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 +19 -6
  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 +853 -1344
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +18 -22
  15. package/src/cmd/output.js +15 -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 +77 -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,8 +1,3 @@
1
- // PHP include-graph + Composer-autoload loader. Statically scans PHP (never runs
2
- // it) into `{ sources, resolutions, missing }`. Literal includes are strict
3
- // (unresolved -> `missing`); Composer-autoloaded class refs are best-effort
4
- // (unresolved -> silently skipped).
5
-
6
1
  import { isUtf8 } from 'node:buffer'
7
2
  import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
8
3
  import { readFile } from 'node:fs/promises'
@@ -11,18 +6,17 @@ import { isDeepStrictEqual } from 'node:util'
11
6
 
12
7
  import { isValidRepoField } from '@exodus/stasis-core/bundle'
13
8
  import { checkoutCommit, parseGithubRepository } from '@exodus/stasis-core/bundle-util'
14
- import { assertRealPathWithinBase, fileInBucket, isPlainObject, relativeEscapes, toPosix } from '@exodus/stasis-core/util'
9
+ import { archiveIntegrity, assertRealPathWithinBase, fileInBucket, isPlainObject, moduleInfo, relativeEscapes, toPosix, upsert } from '@exodus/stasis-core/util'
15
10
  import { LockfileError, parseComposerLock } from '@preventive/lockfile/composer.js'
16
11
  import { isDir, isFile } from '../resolve-typescript.js'
17
12
  import { applyToDir, isDotRelative } from './paths.js'
18
13
  import { readUtf8OrNull } from './solidity-ownership.js'
19
14
  import { nameErrors } from './toml.js'
20
15
 
21
- // Cap concurrent reads per wave to avoid EMFILE on large directory globs.
16
+ // Reads at once: a wave can be huge (a dynamic include's directory), and opening every file at once EMFILE.
22
17
  const READ_CONCURRENCY = 64
23
18
 
24
- // End index (exclusive) of the heredoc/nowdoc opener at `start`, or `start` if
25
- // not a valid opener. Consumes to EOF when unterminated.
19
+ // The end of the heredoc/nowdoc opening at `start`, or `start` where none does; an unterminated one runs to the end.
26
20
  function heredocEnd(code, start) {
27
21
  const n = code.length
28
22
  let j = start + 3
@@ -32,120 +26,91 @@ function heredocEnd(code, start) {
32
26
  while (j < n && /\w/u.test(code[j])) label += code[j++]
33
27
  if (label === '') return start
34
28
  if (quote && code[j] === quote) j++
35
- let p = code.indexOf('\n', j)
36
- if (p === -1) return n
37
- p += 1
38
- while (p <= n) {
39
- let q = p
29
+ for (let nl = code.indexOf('\n', j); nl !== -1; nl = code.indexOf('\n', nl + 1)) {
30
+ let q = nl + 1
40
31
  while (q < n && (code[q] === ' ' || code[q] === '\t')) q++
41
- if (code.startsWith(label, q)) {
42
- const after = code[q + label.length]
43
- if (after === undefined || !/\w/u.test(after)) {
44
- const nl = code.indexOf('\n', q)
45
- return nl === -1 ? n : nl
46
- }
32
+ if (code.startsWith(label, q) && !/\w/u.test(code[q + label.length] ?? '')) {
33
+ const end = code.indexOf('\n', q)
34
+ return end === -1 ? n : end
47
35
  }
48
- const nl = code.indexOf('\n', p)
49
- if (nl === -1) return n
50
- p = nl + 1
51
36
  }
52
37
  return n
53
38
  }
54
39
 
55
- // Blank everything that isn't executable PHP (comments, heredocs/nowdocs, and
56
- // unless `keepStrings` string literals) to spaces, preserving newlines so byte
57
- // offsets stay aligned with the input. `#[` (a PHP 8 attribute) is left intact.
40
+ // Comments, heredocs/nowdocs and (unless `keepStrings`) string literals blanked, newlines kept so offsets stay
41
+ // the input's. `#[` (a PHP 8 attribute) is code.
58
42
  function maskNonCode(code, keepStrings) {
59
43
  const n = code.length
60
- const blank = (s) => s.replace(/[^\n]/gu, ' ')
61
44
  let out = ''
62
45
  let i = 0
63
46
  while (i < n) {
64
47
  const c = code[i]
48
+ let end = i + 1
49
+ let masked = true
65
50
  if ((c === '/' && code[i + 1] === '/') || (c === '#' && code[i + 1] !== '[')) {
66
- let end = code.indexOf('\n', i)
51
+ end = code.indexOf('\n', i)
67
52
  if (end === -1) end = n
68
- out += blank(code.slice(i, end))
69
- i = end
70
53
  } else if (c === '/' && code[i + 1] === '*') {
71
54
  const close = code.indexOf('*/', i + 2)
72
- const end = close === -1 ? n : close + 2
73
- out += blank(code.slice(i, end))
74
- i = end
55
+ end = close === -1 ? n : close + 2
75
56
  } else if (c === '<' && code[i + 1] === '<' && code[i + 2] === '<') {
76
- const end = heredocEnd(code, i)
77
- if (end === i) { out += c; i++ } else { out += blank(code.slice(i, end)); i = end }
57
+ end = Math.max(heredocEnd(code, i), i + 1)
58
+ masked = end > i + 1
78
59
  } else if (c === "'" || c === '"') {
79
- let j = i + 1
80
- while (j < n) {
81
- if (code[j] === '\\') { j += 2; continue }
82
- if (code[j] === c) { j++; break }
83
- j++
60
+ while (end < n) {
61
+ if (code[end] === '\\') { end += 2; continue }
62
+ if (code[end++] === c) break
84
63
  }
85
- out += keepStrings ? code.slice(i, j) : blank(code.slice(i, j))
86
- i = j
87
- } else {
88
- out += c
89
- i++
90
- }
64
+ masked = !keepStrings
65
+ } else masked = false
66
+ out += masked ? code.slice(i, end).replace(/[^\n]/gu, ' ') : code.slice(i, end)
67
+ i = end
91
68
  }
92
69
  return out
93
70
  }
94
71
 
95
- // Blank comments/heredocs, keep string literals (include paths live in strings).
96
- function maskCommentsAndHeredocs(content) {
97
- return maskNonCode(content, true)
72
+ // String literals kept, as include paths live in them.
73
+ function maskedPhp(content) {
74
+ const code = maskNonCode(content, true)
75
+ return { code, strings: stringLiterals(code) }
98
76
  }
99
77
 
100
- // Scan string literals -> { start, end, value, quote } with PHP single-quote
101
- // unescaping (only `\\` and the closing quote are escapes; other backslashes
102
- // literal -- good enough for path values).
78
+ // Only `\\` and the closing quote unescaped, as PHP's single quotes do: good enough for path values.
103
79
  function stringLiterals(code) {
104
80
  const out = []
105
81
  let i = 0
106
82
  while (i < code.length) {
107
83
  const q = code[i]
108
- if (q === "'" || q === '"') {
109
- let j = i + 1
110
- let value = ''
111
- while (j < code.length) {
112
- const c = code[j]
113
- if (c === '\\') {
114
- const next = code[j + 1]
115
- value += next === '\\' || next === q ? next : c + (next ?? '')
116
- j += next === undefined ? 1 : 2
117
- continue
118
- }
119
- if (c === q) { j++; break }
120
- value += c
121
- j++
84
+ if (q !== "'" && q !== '"') { i++; continue }
85
+ let j = i + 1
86
+ let value = ''
87
+ while (j < code.length) {
88
+ const c = code[j]
89
+ if (c === '\\') {
90
+ const next = code[j + 1]
91
+ value += next === '\\' || next === q ? next : c + (next ?? '')
92
+ j += next === undefined ? 1 : 2
93
+ continue
122
94
  }
123
- out.push({ start: i, end: j, value, quote: q })
124
- i = j
125
- } else {
126
- i++
95
+ if (c === q) { j++; break }
96
+ value += c
97
+ j++
127
98
  }
99
+ out.push({ start: i, end: j, value, quote: q })
100
+ i = j
128
101
  }
129
102
  return out
130
103
  }
131
104
 
132
- // Whether `pos` is inside one of `strings` (stringLiterals), and the literal starting at `pos`.
133
105
  const inString = (strings, pos) => strings.some(({ start, end }) => pos > start && pos < end)
134
106
  const stringAt = (strings, pos) => strings.find(({ start }) => start === pos)
135
107
 
136
- // Include keyword. The lookbehind rejects method/scope-resolution calls
137
- // (`$x->require`, `Foo::include`); the trailing `\b` stops matching inside
138
- // `requireConfig`. String-literal matches are filtered out by the caller.
108
+ // The lookbehind rejects `$x->require` and `Foo::include`, the `\b` `requireConfig`.
139
109
  const PHP_INCLUDE_KEYWORD_RE = /(?<![\w$>:])(?:require_once|require|include_once|include)\b/gidu
140
-
141
- // Directory anchor (sticky): `__DIR__`/`dirname(__FILE__)` (file's own dir) or
142
- // `dirname(__DIR__[, N])` (N parent levels up).
143
110
  const PHP_DIR_ANCHOR_RE = /__DIR__\b|dirname\s*\(\s*(__FILE__|__DIR__)\s*(?:,\s*(\d+)\s*)?\)/y
144
- // Anchor starts, for scanning path literals anywhere (not just after `require`).
145
111
  const PHP_DIR_ANCHOR_FIND_RE = /(?<![\w$>])(?:__DIR__\b|dirname\s*\(\s*(?:__FILE__|__DIR__))/gu
146
112
 
147
- // Laravel path helpers resolving a string arg relative to the project root (or a
148
- // fixed subdirectory); they name real PHP files the framework require()s.
113
+ // Laravel's helpers taking a path from the project root (or a directory of it): they name PHP files it require()s.
149
114
  const PHP_PATH_HELPERS = new Map([
150
115
  ['base_path', ''],
151
116
  ['app_path', 'app'],
@@ -156,11 +121,9 @@ const PHP_PATH_HELPERS = new Map([
156
121
  ['resource_path', 'resources'],
157
122
  ['storage_path', 'storage'],
158
123
  ])
159
- const PHP_PATH_HELPER_FIND_RE =
160
- /(?<![\w$>:])(base_path|app_path|config_path|database_path|lang_path|public_path|resource_path|storage_path)\s*\(/giu
124
+ const PHP_PATH_HELPER_FIND_RE = new RegExp(String.raw`(?<![\w$>:])(${[...PHP_PATH_HELPERS.keys()].join('|')})\s*\(`, 'giu')
161
125
 
162
- // Interpolation markers inside a double-quoted string (`$var`, `${...}`,
163
- // `{$...}`). Single-quoted strings never interpolate, so a `$` there is literal.
126
+ // A double-quoted string's interpolation; a single-quoted one's `$` is literal.
164
127
  const PHP_INTERPOLATION_RE = /\$[A-Za-z_{]|\{\$/u
165
128
 
166
129
  function skipWs(code, pos) {
@@ -168,30 +131,20 @@ function skipWs(code, pos) {
168
131
  return pos
169
132
  }
170
133
 
171
- // If a directory anchor starts at `pos`, return { end, up } (up = parent levels
172
- // above the file's dir; 0 for `__DIR__`/`dirname(__FILE__)`); else null.
173
134
  function matchDirAnchor(code, pos) {
174
135
  PHP_DIR_ANCHOR_RE.lastIndex = pos
175
136
  const m = PHP_DIR_ANCHOR_RE.exec(code)
176
137
  if (!m) return null
177
- const up = m[1] === '__DIR__' ? (m[2] ? Number(m[2]) : 1) : 0
178
- return { end: PHP_DIR_ANCHOR_RE.lastIndex, up }
138
+ return { end: PHP_DIR_ANCHOR_RE.lastIndex, up: m[1] === '__DIR__' ? (m[2] ? Number(m[2]) : 1) : 0 }
179
139
  }
180
140
 
181
-
182
- // Normalise an include path to a specifier. Dir-relative paths get a `./` prefix
183
- // with the leading separator stripped; empty means the file's own dir (`.`).
184
141
  function normalizeIncludePath(raw, dirRelative) {
185
142
  if (!dirRelative) return raw
186
143
  const rel = raw.replace(/^\/+/u, '')
187
- if (rel === '') return '.'
188
- return isDotRelative(rel) ? rel : `./${rel}`
144
+ return rel === '' ? '.' : isDotRelative(rel) ? rel : `./${rel}`
189
145
  }
190
146
 
191
- // Parse an include/path argument at `start`: an optional directory anchor then a
192
- // concatenation chain of string literals (static literals fold together). Goes
193
- // `dynamic` at the first variable/function/constant/interpolation; `prefix` is
194
- // the static path up to there. Returns null with neither anchor nor static string.
147
+ // Null with neither a directory anchor nor a literal; `dynamic` from the first variable, call or interpolation.
195
148
  function parseArgPath(code, start, strings) {
196
149
  let i = start
197
150
  let dirRelative = false
@@ -204,32 +157,22 @@ function parseArgPath(code, start, strings) {
204
157
  if (code[i] !== '.') return null
205
158
  i = skipWs(code, i + 1)
206
159
  }
207
-
160
+ if (!dirRelative && !stringAt(strings, i)) return null
208
161
  let prefix = '/..'.repeat(up)
209
- let dynamic = false
210
- let sawStatic = false
211
162
  for (;;) {
212
163
  const lit = stringAt(strings, i)
213
- if (!lit) { dynamic = true; break }
164
+ if (!lit) return { dirRelative, up, prefix, dynamic: true }
214
165
  const interp = lit.quote === '"' ? lit.value.search(PHP_INTERPOLATION_RE) : -1
215
- if (interp >= 0) { prefix += lit.value.slice(0, interp); sawStatic = true; dynamic = true; break }
166
+ if (interp >= 0) return { dirRelative, up, prefix: prefix + lit.value.slice(0, interp), dynamic: true }
216
167
  prefix += lit.value
217
- sawStatic = true
218
168
  i = skipWs(code, lit.end)
219
- if (code[i] === '.') { i = skipWs(code, i + 1); continue }
220
- break
169
+ if (code[i] !== '.') return { dirRelative, up, prefix, dynamic: false }
170
+ i = skipWs(code, i + 1)
221
171
  }
222
- if (!dirRelative && !sawStatic) return null
223
- return { dirRelative, up, prefix, dynamic, sawStatic }
224
172
  }
225
173
 
226
- // Scan `require`/`include` statements, classifying each as a concrete `file` or
227
- // -- when the path is dynamic but has a static directory prefix -- a `dir` whose
228
- // `.php` files are all bundled (any could be the runtime target).
229
- function scanIncludes(content) {
230
- const code = maskCommentsAndHeredocs(content)
231
- const strings = stringLiterals(code)
232
-
174
+ // A dynamic include's static directory prefix (`dir`): any `.php` file in it may be its target at runtime.
175
+ function scanIncludes({ code, strings }) {
233
176
  const out = []
234
177
  for (const m of code.matchAll(PHP_INCLUDE_KEYWORD_RE)) {
235
178
  if (inString(strings, m.index)) continue
@@ -237,39 +180,27 @@ function scanIncludes(content) {
237
180
  if (code[i] === '(') i = skipWs(code, i + 1)
238
181
  const arg = parseArgPath(code, i, strings)
239
182
  if (!arg) continue
240
- const { dirRelative, up, prefix, dynamic, sawStatic } = arg
241
-
242
- if (!dynamic) {
243
- if (sawStatic) out.push({ kind: 'file', spec: normalizeIncludePath(prefix, dirRelative) })
244
- continue
183
+ const { dirRelative, up, prefix, dynamic } = arg
184
+ if (!dynamic) out.push({ kind: 'file', spec: normalizeIncludePath(prefix, dirRelative) })
185
+ else if (dirRelative || prefix.includes('/')) {
186
+ let dir = prefix.includes('/') ? prefix.slice(0, prefix.lastIndexOf('/')) : ''
187
+ if (dir === '' && up > 0) dir = '/..'.repeat(up)
188
+ out.push({ kind: 'dir', spec: normalizeIncludePath(dir, dirRelative) })
245
189
  }
246
- // Dynamic path: fall back to the static dir prefix; a bare path with no separator has none.
247
- if (!dirRelative && !prefix.includes('/')) continue
248
- const lastSlash = prefix.lastIndexOf('/')
249
- let dir = lastSlash >= 0 ? prefix.slice(0, lastSlash) : ''
250
- if (dir === '' && up > 0) dir = '/..'.repeat(up)
251
- out.push({ kind: 'dir', spec: normalizeIncludePath(dir, dirRelative) })
252
190
  }
253
191
  return out
254
192
  }
255
193
 
256
- // Dir-anchored static `.php` path literals anywhere in the file (not just after
257
- // `require`) -- frameworks pass these to code that require()s them internally.
258
- // Best-effort: bundled only if they resolve to an existing file.
259
- function scanPathLiterals(content) {
260
- const code = maskCommentsAndHeredocs(content)
261
- const strings = stringLiterals(code)
262
-
194
+ // `.php` path literals outside a `require`, which frameworks require() themselves.
195
+ function scanPathLiterals({ code, strings }) {
263
196
  const out = []
264
- // Dir-anchored literals: `__DIR__ . '/x.php'` (resolve against the file).
265
197
  for (const m of code.matchAll(PHP_DIR_ANCHOR_FIND_RE)) {
266
198
  if (inString(strings, m.index)) continue
267
199
  const arg = parseArgPath(code, m.index, strings)
268
- if (!arg || arg.dynamic || !arg.sawStatic || !arg.dirRelative) continue
200
+ if (!arg || arg.dynamic || !arg.dirRelative) continue
269
201
  const spec = normalizeIncludePath(arg.prefix, true)
270
202
  if (spec.endsWith('.php')) out.push({ spec, anchor: 'file' })
271
203
  }
272
- // Laravel path helpers: `base_path('routes/web.php')` (resolve against project root).
273
204
  for (const m of code.matchAll(PHP_PATH_HELPER_FIND_RE)) {
274
205
  if (inString(strings, m.index)) continue
275
206
  const lit = stringAt(strings, skipWs(code, m.index + m[0].length))
@@ -284,64 +215,44 @@ function scanPathLiterals(content) {
284
215
 
285
216
  const includeSpecs = (includes, kind) => includes.filter((e) => e.kind === kind).map((e) => e.spec)
286
217
 
287
- // Statically-resolvable include specifiers (concrete files). See scanIncludes.
288
- export function extractPhpImports(content) {
289
- return includeSpecs(scanIncludes(content), 'file')
290
- }
291
-
292
- // Directory specifiers for dynamic includes; every `.php` file directly inside is
293
- // a candidate target.
294
- export function extractPhpImportDirs(content) {
295
- return includeSpecs(scanIncludes(content), 'dir')
296
- }
297
-
298
- // `.php` path literals used outside a `require` -- dir-anchored (`anchor: 'file'`)
299
- // or via a Laravel path helper (`anchor: 'root'`). De-duplicated; best-effort.
300
- export function extractPhpPathRefs(content) {
301
- const seen = new Set()
302
- return scanPathLiterals(content).filter(({ spec, anchor }) => {
303
- const key = `${anchor}:${spec}`
304
- if (seen.has(key)) return false
305
- seen.add(key)
306
- return true
307
- })
308
- }
218
+ export const extractPhpImports = (content) => includeSpecs(scanIncludes(maskedPhp(content)), 'file')
219
+ export const extractPhpImportDirs = (content) => includeSpecs(scanIncludes(maskedPhp(content)), 'dir')
220
+ const pathRefs = (masked) => [...new Map(scanPathLiterals(masked).map((ref) => [`${ref.anchor}:${ref.spec}`, ref])).values()]
221
+ export const extractPhpPathRefs = (content) => pathRefs(maskedPhp(content))
309
222
 
310
223
  const isFileOnDisk = (baseDir, rel) => isFile(join(baseDir, rel))
311
- const isDirOnDisk = (baseDir, rel) => isDir(join(baseDir, rel))
312
224
 
313
- // Throws on a path holding `\`: no separator to PHP off Windows but part of a name, and stasis
314
- // refuses such a name rather than resolve it, or take it for another path. `from`: the includer.
225
+ // A `\` is no separator to PHP off Windows but part of a name: stasis refuses such a name rather than resolve
226
+ // it, or take it for another path.
315
227
  function refuseBackslash(path, from) {
316
228
  if (path.includes('\\')) throw new Error(`[loader.php] path holds a '\\', which stasis refuses: ${path}${from ? ` (from ${from})` : ''}`)
317
229
  }
318
230
 
319
- // `abs` as a baseDir-relative POSIX path ('' for baseDir itself), or null when it escapes the root.
320
231
  function projectRel(baseDir, abs) {
321
232
  const rel = toPosix(relative(baseDir, abs))
322
233
  return relativeEscapes(rel) ? null : rel
323
234
  }
324
235
 
325
- // Resolve a directory specifier to an existing baseDir-relative dir, or null.
326
- // `./`/`../` resolve against the including file; a bare spec tries file- then
327
- // project-relative.
328
- export function resolvePhpDir(spec, fromFile, baseDir) {
236
+ // `./`/`../` resolve against the including file (null escaping the root; existence unchecked); a bare one next
237
+ // to the includer, then from the project root, the first that is `present`. Absolute ones are refused.
238
+ function resolvePhpSpec(spec, fromFile, baseDir, present) {
329
239
  refuseBackslash(spec, fromFile)
330
- if (isDotRelative(spec)) {
331
- const rel = applyToDir(fromFile, spec.split('/'))
332
- return rel !== null && isDirOnDisk(baseDir, rel) ? rel : null
333
- }
334
- if (baseDir && !isAbsolute(spec)) {
335
- const fileRel = applyToDir(fromFile, spec.split('/'))
336
- if (fileRel && isDirOnDisk(baseDir, fileRel)) return fileRel
337
- const projRel = projectRel(baseDir, resolve(baseDir, spec))
338
- if (projRel && isDirOnDisk(baseDir, projRel)) return projRel
339
- }
340
- return null
240
+ if (isDotRelative(spec)) return applyToDir(fromFile, spec.split('/'))
241
+ if (!baseDir || isAbsolute(spec)) return null
242
+ const fileRel = applyToDir(fromFile, spec.split('/'))
243
+ if (fileRel && present(fileRel)) return fileRel
244
+ const projRel = projectRel(baseDir, resolve(baseDir, spec))
245
+ return projRel && present(projRel) ? projRel : null
246
+ }
247
+
248
+ // A bare specifier resolvePhpSpec found present already.
249
+ export function resolvePhpDir(spec, fromFile, baseDir) {
250
+ const present = (rel) => isDir(join(baseDir, rel))
251
+ const rel = resolvePhpSpec(spec, fromFile, baseDir, present)
252
+ return rel !== null && (!isDotRelative(spec) || present(rel)) ? rel : null
341
253
  }
342
254
 
343
- // The `.php` files directly in `dir` (baseDir-relative). Non-recursive: recursing
344
- // could pull in an unbounded subtree.
255
+ // Not recursive, which could pull in an unbounded subtree.
345
256
  function listPhpFiles(baseDir, dir) {
346
257
  try {
347
258
  return readdirSync(join(baseDir, dir), { withFileTypes: true })
@@ -352,41 +263,17 @@ function listPhpFiles(baseDir, dir) {
352
263
  }
353
264
  }
354
265
 
355
- // Resolve a PHP include specifier to a baseDir-relative POSIX path. `./`/`../`
356
- // resolve against the including file (escaping the root -> null); a bare specifier
357
- // tries a file next to the includer, then project-root-relative. Absolute
358
- // specifiers are rejected. Returns null when nothing resolves. One holding `\` throws
359
- // (see refuseBackslash).
360
- export function resolvePhpImport(specifier, fromFile, { baseDir } = {}) {
361
- refuseBackslash(specifier, fromFile)
362
- if (isDotRelative(specifier)) {
363
- return applyToDir(fromFile, specifier.split('/'))
364
- }
365
-
366
- if (baseDir && !isAbsolute(specifier)) {
367
- const fileRel = applyToDir(fromFile, specifier.split('/'))
368
- if (fileRel && isFileOnDisk(baseDir, fileRel)) return fileRel
369
-
370
- const projRel = projectRel(baseDir, resolve(baseDir, specifier))
371
- if (projRel && isFileOnDisk(baseDir, projRel)) return projRel
372
- }
373
-
374
- return null
375
- }
266
+ export const resolvePhpImport = (specifier, fromFile, { baseDir } = {}) =>
267
+ resolvePhpSpec(specifier, fromFile, baseDir, (rel) => isFileOnDisk(baseDir, rel))
376
268
 
377
- // Normalise a project-root-relative autoload path to POSIX baseDir-relative, or
378
- // null when it escapes root. Re-derives via resolve() so interior `..` escapes
379
- // (`src/foo/../../../secret.php`) are caught -- a leading-`..`/absolute check
380
- // alone would let files outside the project into the bundle. One holding `\`
381
- // throws (see refuseBackslash).
269
+ // Re-derived via resolve() so an interior `..` escaping the root (`src/foo/../../../secret.php`) is caught,
270
+ // which a leading-`..`/absolute check alone would let in.
382
271
  function normalizeProjectRel(baseDir, p) {
383
272
  refuseBackslash(p)
384
273
  return projectRel(baseDir, resolve(baseDir, p))
385
274
  }
386
275
 
387
- // Evaluate a generated-autoload path expr (`$baseDir . '/src'`, a bare quoted
388
- // string) given the `$baseDir`/`$vendorDir` values. Returns null on anything
389
- // unrecognised (function call, unknown variable) rather than guessing.
276
+ // A generated autoload path (`$baseDir . '/src'`, a quoted string); null for anything else rather than a guess.
390
277
  function evalPathExpr(expr, vars) {
391
278
  const s = expr.trim().replace(/,+$/u, '').trim()
392
279
  let out = ''
@@ -394,8 +281,7 @@ function evalPathExpr(expr, vars) {
394
281
  const re = /\$(\w+)|'((?:\\.|[^'\\])*)'|"((?:\\.|[^"\\])*)"|\.|\s+/gy
395
282
  let m
396
283
  while ((m = re.exec(s)) !== null) {
397
- // A sticky regex resets lastIndex to 0 when exec() returns null, so track how
398
- // far we parsed instead of reading lastIndex after the loop.
284
+ // A sticky regex resets lastIndex to 0 when exec() returns null: how far it parsed is kept here.
399
285
  consumed = re.lastIndex
400
286
  if (m[1] !== undefined) {
401
287
  if (vars[m[1]] === undefined) return null
@@ -410,9 +296,7 @@ function evalPathExpr(expr, vars) {
410
296
  return out
411
297
  }
412
298
 
413
- // Parse a Composer generated `autoload_*.php` map (one entry per line). `multi`
414
- // true -> psr-4/psr-0 (key -> dirs[]); false -> classmap/files (key -> file).
415
- // PHP single-quote escapes in keys are unfolded.
299
+ // A Composer `autoload_*.php` map, one entry a line: `multi`, psr-4/psr-0's (key -> dirs); else a file each.
416
300
  function parseGeneratedMap(content, vars, multi) {
417
301
  const out = new Map()
418
302
  for (const line of content.split('\n')) {
@@ -421,13 +305,7 @@ function parseGeneratedMap(content, vars, multi) {
421
305
  const key = m[1].replace(/\\(['\\])/gu, '$1')
422
306
  if (multi) {
423
307
  const am = m[2].match(/^array\s*\(([\s\S]*)\)$/u)
424
- if (!am) continue
425
- const dirs = []
426
- for (const piece of am[1].split(',')) {
427
- const abs = evalPathExpr(piece, vars)
428
- if (abs) dirs.push(abs)
429
- }
430
- out.set(key, dirs)
308
+ if (am) out.set(key, am[1].split(',').map((piece) => evalPathExpr(piece, vars)).filter(Boolean))
431
309
  } else {
432
310
  const abs = evalPathExpr(m[2], vars)
433
311
  if (abs) out.set(key, abs)
@@ -444,51 +322,40 @@ function readJsonIfExists(file) {
444
322
  }
445
323
  }
446
324
 
447
- // The root composer.json (null when absent or unparsable) and its baseDir-relative vendor dir.
448
325
  function readComposerJson(baseDir) {
449
326
  const composerJson = readJsonIfExists(join(baseDir, 'composer.json'))
450
327
  const vendorDir = normalizeProjectRel(baseDir, composerJson?.config?.['vendor-dir'] ?? 'vendor') ?? 'vendor'
451
328
  return { composerJson, vendorDir }
452
329
  }
453
330
 
454
- // The packages `vendor/composer/installed.json` lists, in the Composer 2 ({ packages }) or
455
- // Composer 1 (flat array) shape.
331
+ // Composer 2's `{ packages }`, or Composer 1's flat array.
456
332
  function readInstalledPackages(baseDir, vendorDir) {
457
333
  const json = readJsonIfExists(join(baseDir, vendorDir, 'composer', 'installed.json'))
458
334
  return Array.isArray(json) ? json : (json?.packages ?? [])
459
335
  }
460
336
 
461
- // JSON `text` with each integer as PHP holds it: one past ±(2^53 − 1) a BigInt, as
462
- // @preventive/lockfile reads one, so two values compare equal only where PHP's do.
337
+ // An integer past ±(2^53 − 1) a BigInt, as @preventive/lockfile reads one, so two values compare equal only
338
+ // where PHP's do.
463
339
  const parseJsonExact = (text) => JSON.parse(text, (key, value, { source }) =>
464
340
  (typeof value === 'number' && !Number.isSafeInteger(value) && /^-?\d+$/u.test(source) ? BigInt(source) : value))
465
341
 
466
- // Where installed.json says Composer installed package `p`, baseDir-relative: its install-path,
467
- // from vendor/composer (null for none, as of a metapackage), or <vendor-dir>/<name> where it gives
468
- // none (Composer 1's); null outside baseDir.
342
+ // installed.json's install-path is from vendor/composer, null for a metapackage; Composer 1's gives none.
469
343
  function installedDir(baseDir, vendorDir, p) {
470
344
  const path = p['install-path']
471
345
  if (path === undefined) return projectRel(baseDir, resolve(baseDir, vendorDir, p.name))
472
346
  return typeof path === 'string' ? projectRel(baseDir, resolve(baseDir, vendorDir, 'composer', path)) : null
473
347
  }
474
348
 
475
- // Where Composer's library installer puts a package of the lockfile, baseDir-relative
476
- // (LibraryInstaller::getInstallPath): <vendor-dir>/<name>, under its target-dir where it has one; a
477
- // metapackage nowhere (null). One of a type an installer plugin takes (composer/installers') goes
478
- // elsewhere, where its own composer.json's name finds it.
479
- function lockedDir(baseDir, vendorDir, p) {
480
- return p.type === 'metapackage' ? null : projectRel(baseDir, resolve(baseDir, vendorDir, p.name, p.targetDir ?? ''))
481
- }
349
+ // As LibraryInstaller::getInstallPath puts a package; one an installer plugin takes goes elsewhere, where its
350
+ // own composer.json's name finds it.
351
+ const lockedDir = (baseDir, vendorDir, p) =>
352
+ (p.type === 'metapackage' ? null : projectRel(baseDir, resolve(baseDir, vendorDir, p.name, p.targetDir ?? '')))
482
353
 
483
- // What Composer adds to a package of the lockfile as it installs it, in installed.json.
354
+ // What Composer adds to a locked package in installed.json as it installs it.
484
355
  const INSTALL_FIELDS = new Set(['version_normalized', 'installation-source', 'install-path'])
485
356
 
486
- // That vendor/composer/installed.json (`installedText`, at `installedFile`) is the install of
487
- // composer.lock (`lockText`, read by @preventive/lockfile already): as Composer 2 writes it,
488
- // `{ packages, dev, dev-package-names }`; each package of the lockfile's `packages`, and of its
489
- // `packages-dev` where it was installed with dev, there once and exactly as locked but for
490
- // INSTALL_FIELDS, and nothing else; and the names of those of `packages-dev`, in lowercase and
491
- // sorted, as dev-package-names. Throws where not. Returns the installed.json.
357
+ // Throws unless installed.json is, as Composer 2 writes it, the install of composer.lock: each locked package
358
+ // (packages-dev too, installed with dev) there once, as locked but for INSTALL_FIELDS, and nothing else.
492
359
  function assertInstalledAsLocked(lockText, installedText, { installedFile, vendorDir }) {
493
360
  const differ = (detail) => new Error(`${installedFile} is not the install of composer.lock: ${detail}${vendorDir ? `; remove ${vendorDir} and run \`composer install\`` : ''}`)
494
361
  let installed
@@ -520,8 +387,7 @@ function assertInstalledAsLocked(lockText, installedText, { installedFile, vendo
520
387
  const spec = Object.fromEntries(Object.entries(entry).filter(([key]) => !INSTALL_FIELDS.has(key)))
521
388
  const key = [...new Set([...Object.keys(spec), ...Object.keys(want.spec)])].find((k) => !isDeepStrictEqual(spec[k], want.spec[k]))
522
389
  if (key === 'version' && typeof spec.version === 'string') throw differ(`${name} is installed at ${JSON.stringify(spec.version)}, and locked at ${want.spec.version}`)
523
- // `composer install` takes a package installed at the version and reference locked as it is,
524
- // whatever else of it the lockfile changes.
390
+ // `composer install` takes a package at the version and reference locked as it is, whatever else changed.
525
391
  if (key !== undefined) throw differ(`${name}'s ${JSON.stringify(key)} is not as locked`)
526
392
  }
527
393
  for (const [name, { dev }] of locked) {
@@ -532,40 +398,32 @@ function assertInstalledAsLocked(lockText, installedText, { installedFile, vendo
532
398
  return installed
533
399
  }
534
400
 
535
- // The GitHub repository a Composer package `p` (composer.lock's, or installed.json's) is cloned
536
- // from, at the commit it is installed at: its git `source` on GitHub, at its `reference` where that
537
- // is a full commit and what is installed at `at` (its directory, or null for none) is at it.
538
- // Installed from its source -- as installed.json's `installation-source`, `from`, says, or as it
539
- // must be with no dist, or as a git checkout there shows -- it is a clone Composer checked out at
540
- // the reference, which may have been moved since: so only where that checkout's HEAD is it. Else
541
- // from its dist, which Composer installs by default: only one at the same reference, as one with
542
- // none, or another, is an archive no commit is known of. Packagist takes a package from the root
543
- // of its repository, so `directory` is ''. Undefined otherwise.
544
- function composerRepo({ source, dist }, from, at) {
401
+ // Its git `source`'s `reference`, where a clone's checkout HEAD (installed from source) or its dist's reference
402
+ // is that commit; `directory` '', as Packagist takes a package from its repository's root.
403
+ function composerRepo({ source, dist }, fromSource, at) {
545
404
  if (source?.type !== 'git') return undefined
546
- const fromSource = from === 'source' || dist == null || (at !== null && existsSync(join(at, '.git')))
547
405
  if (fromSource ? at === null || checkoutCommit(at) !== source.reference : dist.reference !== source.reference) return undefined
548
406
  const github = parseGithubRepository(source.url)
549
407
  return github !== null && isValidRepoField('commit', source.reference) ? { github, directory: '', commit: source.reference } : undefined
550
408
  }
551
409
 
552
- // The Composer packages of the project at `baseDir`, `[{ name, version, dir, extra, repo }]`, `dir` where
553
- // the package is installed, baseDir-relative (null for nowhere in baseDir, as a metapackage). Of
554
- // its composer.lock where there is one, read by @preventive/lockfile beside composer.json as
555
- // `composer install` reads them -- one it refuses stops the build -- each package where Composer
556
- // installs it (lockedDir), so no install is needed; else of vendor/composer/installed.json, as
557
- // it is. Where both are, installed.json must be the lockfile's install (assertInstalledAsLocked):
558
- // its packages, each where installed.json says. `repo` is composerRepo's.
410
+ // As installed.json's `installation-source` says, as it must with no dist, or as a git checkout at `at` shows.
411
+ const installedFromSource = ({ dist }, from, at) => from === 'source' || dist == null || (at !== null && existsSync(join(at, '.git')))
412
+
413
+ function composerInstall(p, from, at) {
414
+ const fromSource = installedFromSource(p, from, at)
415
+ return { repo: composerRepo(p, fromSource, at), integrity: fromSource ? undefined : archiveIntegrity('composer', p.dist.shasum) }
416
+ }
417
+
418
+ // Of composer.lock, each where Composer installs it, or where installed.json, which must be its install, says.
559
419
  export function loadComposerPackages(baseDir) {
560
420
  const { vendorDir } = readComposerJson(baseDir)
421
+ const packageAt = (p, dir, from) => ({ name: p.name, version: p.version, dir, extra: p.extra, ...composerInstall(p, from, dir == null ? null : join(baseDir, dir)) })
561
422
  const lockText = readUtf8OrNull(join(baseDir, 'composer.lock'), 'composer.lock')
562
423
  if (lockText === null) {
563
424
  return readInstalledPackages(baseDir, vendorDir)
564
425
  .filter((p) => p?.name && p.version)
565
- .map((p) => {
566
- const dir = installedDir(baseDir, vendorDir, p)
567
- return { name: p.name, version: p.version, dir, extra: p.extra, repo: composerRepo(p, p['installation-source'], dir == null ? null : join(baseDir, dir)) }
568
- })
426
+ .map((p) => packageAt(p, installedDir(baseDir, vendorDir, p), p['installation-source']))
569
427
  }
570
428
 
571
429
  const composerJson = readUtf8OrNull(join(baseDir, 'composer.json'), 'composer.json')
@@ -577,16 +435,10 @@ export function loadComposerPackages(baseDir) {
577
435
  const from = new Map(installed?.packages.map((p) => [p.name, p['installation-source']]))
578
436
  return Object.values(lock.packages)
579
437
  .filter((p) => dirs === null || dirs.has(p.name))
580
- .map((p) => {
581
- const dir = dirs === null ? lockedDir(baseDir, vendorDir, p) : dirs.get(p.name)
582
- return { name: p.name, version: p.version, dir, extra: p.extra, repo: composerRepo(p, from.get(p.name), dir == null ? null : join(baseDir, dir)) }
583
- })
438
+ .map((p) => packageAt(p, dirs === null ? lockedDir(baseDir, vendorDir, p) : dirs.get(p.name), from.get(p.name)))
584
439
  }
585
440
 
586
- // Build the autoload config for `baseDir`, merging the root composer.json
587
- // `autoload`(+dev) with the generated `vendor/composer/autoload_*` maps. All
588
- // paths normalised to POSIX baseDir-relative (escapers dropped). Returns
589
- // `{ psr4, psr0, classmap, files }`, or null when no Composer config is found.
441
+ // Null where there is no Composer config.
590
442
  export function loadComposerAutoload(baseDir) {
591
443
  const { composerJson, vendorDir } = readComposerJson(baseDir)
592
444
 
@@ -597,17 +449,10 @@ export function loadComposerAutoload(baseDir) {
597
449
  let found = false
598
450
 
599
451
  const mergeDirs = (map, prefix, dirs) => map.set(prefix, [...new Set([...(map.get(prefix) ?? []), ...dirs])])
600
- const addPrefixDirs = (map, prefix, paths) => {
601
- const list = Array.isArray(paths) ? paths : [paths]
602
- const dirs = []
603
- for (const p of list) {
604
- const rel = normalizeProjectRel(baseDir, String(p))
605
- if (rel !== null) dirs.push(rel)
606
- }
607
- mergeDirs(map, prefix, dirs)
608
- }
452
+ const addPrefixDirs = (map, prefix, paths) =>
453
+ mergeDirs(map, prefix, [paths].flat().map((p) => normalizeProjectRel(baseDir, String(p))).filter((rel) => rel !== null))
609
454
 
610
- // Root composer.json autoload (+ dev). PSR-4 keys keep their trailing '\'.
455
+ // PSR-4 keys keep their trailing '\'.
611
456
  for (const block of [composerJson?.autoload, composerJson?.['autoload-dev']]) {
612
457
  if (!block || typeof block !== 'object') continue
613
458
  found = true
@@ -619,11 +464,9 @@ export function loadComposerAutoload(baseDir) {
619
464
  }
620
465
  }
621
466
 
622
- // Generated maps. `$vendorDir` = <baseDir>/<vendorDir>, `$baseDir` = <baseDir>.
623
467
  const composerGenDir = join(baseDir, vendorDir, 'composer')
624
468
  const vars = { baseDir: resolve(baseDir), vendorDir: resolve(baseDir, vendorDir) }
625
469
  const toRel = (abs) => projectRel(baseDir, abs) || null
626
- // A generated map's entries; none when the file is absent.
627
470
  const generated = (name, multi) => {
628
471
  const file = join(composerGenDir, name)
629
472
  if (!existsSync(file)) return new Map()
@@ -648,105 +491,63 @@ export function loadComposerAutoload(baseDir) {
648
491
  return { psr4, psr0, classmap, files: [...files] }
649
492
  }
650
493
 
651
- // Resolve a FQCN to a baseDir-relative file via the autoload config, mirroring
652
- // Composer's lookup order: classmap, then longest PSR-4 prefix, then PSR-0. Only
653
- // returns a path that exists on disk (an absent prefix match isn't bundled as a hole).
494
+ // As Composer looks a class up: its classmap, then each matching PSR-4 prefix longest first (falling back from
495
+ // one whose file is absent, to the `""` prefix), then PSR-0's. Only a file on disk, as an absent one is no hole.
654
496
  export function resolveClassFile(fqcn, autoload, baseDir) {
655
497
  if (!autoload || !fqcn) return null
656
498
  const name = fqcn.replace(/^\\+/u, '')
657
499
  if (!name) return null
658
-
659
- const exact = autoload.classmap.get(name)
660
- if (exact && isFileOnDisk(baseDir, exact)) return exact
661
-
662
- // PSR-4: try every matching prefix longest-first (Composer falls back from a
663
- // longer prefix whose file is absent to a shorter one, incl. the `""` prefix).
664
- for (const [prefix, dirs] of matchingPrefixes(autoload.psr4, name)) {
665
- const sub = name.slice(prefix.length).replace(/\\/gu, '/')
666
- for (const dir of dirs) {
667
- const file = dir ? `${dir}/${sub}.php` : `${sub}.php`
668
- if (isFileOnDisk(baseDir, file)) return file
669
- }
670
- }
671
-
672
- // PSR-0: namespace separators AND underscores in the class name map to
673
- // directory separators; the namespace prefix is kept under the mapped dir.
674
- for (const [, dirs] of matchingPrefixes(autoload.psr0, name)) {
675
- const lastNs = name.lastIndexOf('\\')
676
- const nsPart = lastNs === -1 ? '' : name.slice(0, lastNs).replace(/\\/gu, '/')
677
- const clsPart = (lastNs === -1 ? name : name.slice(lastNs + 1)).replace(/_/gu, '/')
678
- const sub = `${nsPart ? `${nsPart}/` : ''}${clsPart}.php`
679
- for (const dir of dirs) {
680
- const file = dir ? `${dir}/${sub}` : sub
681
- if (isFileOnDisk(baseDir, file)) return file
682
- }
683
- }
684
-
685
- return null
686
- }
687
-
688
- // [prefix, dirs] entries whose prefix is a prefix of `name`, longest first --
689
- // prefer the most specific mapping, fall back to shorter (and the `""` fallback).
690
- function matchingPrefixes(map, name) {
691
- return [...map].filter(([prefix]) => name.startsWith(prefix)).toSorted((a, b) => b[0].length - a[0].length)
692
- }
693
-
694
- // The versions and repos of the Composer `packages` (loadComposerPackages: the authoritative source;
695
- // a package's own composer.json usually omits `version`), by where each is installed and by name.
500
+ const within = (dir, sub) => (dir ? `${dir}/${sub}` : sub)
501
+ // PSR-0 maps the class name's underscores to directories too, its namespace kept under the prefix's.
502
+ const ns = name.lastIndexOf('\\') + 1
503
+ const psr0 = `${name.slice(0, ns).replace(/\\/gu, '/')}${name.slice(ns).replace(/_/gu, '/')}.php`
504
+ const psr4 = (prefix) => `${name.slice(prefix.length).replace(/\\/gu, '/')}.php`
505
+ const candidates = [
506
+ ...[autoload.classmap.get(name)].filter(Boolean),
507
+ ...matchingPrefixes(autoload.psr4, name).flatMap(([prefix, dirs]) => dirs.map((dir) => within(dir, psr4(prefix)))),
508
+ ...matchingPrefixes(autoload.psr0, name).flatMap(([, dirs]) => dirs.map((dir) => within(dir, psr0))),
509
+ ]
510
+ return candidates.find((file) => isFileOnDisk(baseDir, file)) ?? null
511
+ }
512
+
513
+ const matchingPrefixes = (map, name) => [...map].filter(([prefix]) => name.startsWith(prefix)).toSorted((a, b) => b[0].length - a[0].length)
514
+
515
+ // From loadComposerPackages, as a package's own composer.json usually omits its `version`.
696
516
  function packageVersions(packages) {
697
517
  const byDir = new Map()
698
518
  const byName = new Map()
699
- for (const { name, version, dir, repo } of packages) {
700
- byName.set(name, { version, repo })
701
- if (dir) byDir.set(dir, { version, repo })
519
+ for (const { name, version, dir, repo, integrity } of packages) {
520
+ const known = { version, repo, integrity }
521
+ byName.set(name, known)
522
+ if (dir) byDir.set(dir, known)
702
523
  }
703
524
  return { byDir, byName }
704
525
  }
705
526
 
706
- // Walk up from a bundled file to the nearest named composer.json, returning
707
- // { pkgDir, name, version, repo } (pkgDir "." for the root; version and repo from composer.lock or
708
- // installed.json by dir/name, else composer.json `version`, else `fallbackVersion`). Null if none.
709
527
  function findComposerPackage(baseDir, fileRelPath, installed, fallbackVersion) {
710
- let dir = dirname(fileRelPath)
711
- for (;;) {
528
+ for (let dir = dirname(fileRelPath); ; dir = dirname(dir)) {
712
529
  const cj = readJsonIfExists(join(baseDir, dir, 'composer.json'))
713
530
  if (cj?.name) {
714
531
  const known = installed.byDir.get(dir) ?? installed.byName.get(cj.name)
715
- return { pkgDir: dir, name: cj.name, version: known?.version ?? cj.version ?? fallbackVersion, repo: known?.repo }
532
+ return { pkgDir: dir, name: cj.name, version: known?.version ?? cj.version ?? fallbackVersion, repo: known?.repo, integrity: known?.integrity }
716
533
  }
717
- if (dir === '.' || dir === '/' || dir === '') return null
718
- const parent = dirname(dir)
719
- if (parent === dir) return null
720
- dir = parent
534
+ if (dirname(dir) === dir) return null
721
535
  }
722
536
  }
723
537
 
724
- // Group bundled PHP sources into per-package buckets keyed by the nearest
725
- // composer.json's directory (vendor deps get their own; workspace files and
726
- // orphans -> the root "." bucket with the placeholder identity). Returns a
727
- // Map<dir, { name, version, ecosystem?, repo?, files }>, a dependency's `repo` where composerRepo
728
- // gives one. `packages`: loadComposerPackages(baseDir).
538
+ // By the nearest composer.json's directory; workspace files and orphans in the root "." bucket, the placeholder's.
729
539
  export function bucketizePhpSources(baseDir, sources, fallbackName, fallbackVersion, packages = loadComposerPackages(baseDir)) {
730
540
  const installed = packageVersions(packages)
731
-
732
541
  const modules = new Map()
733
- const ensureBucket = (dir, name, version, ecosystem, repo) => {
734
- if (!modules.has(dir)) {
735
- modules.set(dir, ecosystem === undefined
736
- ? { name, version, files: Object.create(null) }
737
- : { name, version, ecosystem, ...(repo === undefined ? {} : { repo }), files: Object.create(null) })
738
- }
739
- return modules.get(dir)
740
- }
542
+ const ensureBucket = (dir, name, version, ecosystem, { repo, integrity } = {}) =>
543
+ upsert(modules, dir, () => moduleInfo({ name, version, ecosystem, ...(ecosystem !== undefined && { integrity, repo }), files: Object.create(null) }))
741
544
 
742
545
  for (const [path, content] of sources) {
743
546
  const pkg = findComposerPackage(baseDir, path, installed, fallbackVersion)
744
547
  if (pkg) {
745
- const rel = fileInBucket(pkg.pkgDir, path)
746
- // Below the root package = an installed Composer dependency, tagged
747
- // `composer`; the root "." bucket is workspace code and stays ecosystem-less.
548
+ // The root package is workspace code; one below it an installed dependency.
748
549
  const ecosystem = pkg.pkgDir === '.' ? undefined : 'composer'
749
- ensureBucket(pkg.pkgDir, pkg.name, pkg.version, ecosystem, pkg.repo).files[rel] = content
550
+ ensureBucket(pkg.pkgDir, pkg.name, pkg.version, ecosystem, pkg).files[fileInBucket(pkg.pkgDir, path)] = content
750
551
  } else {
751
552
  ensureBucket('.', fallbackName, fallbackVersion).files[path] = content
752
553
  }
@@ -754,11 +555,8 @@ export function bucketizePhpSources(baseDir, sources, fallbackName, fallbackVers
754
555
  return modules
755
556
  }
756
557
 
757
- // Laravel auto-registers service providers nothing references statically. Returns
758
- // discoverable provider files (from composer.json + the Composer `packages`'
759
- // `extra.laravel.providers`, autoload-resolved) plus bootstrap/providers.php as
760
- // extra collection roots. Best-effort: unresolvable classes skipped.
761
- // `packages`: loadComposerPackages(baseDir).
558
+ // Laravel registers service providers nothing references statically: composer.json's and the `packages`'
559
+ // `extra.laravel.providers`, and bootstrap/providers.php, are roots of their own.
762
560
  export function loadLaravelProviderFiles(baseDir, autoload, packages = loadComposerPackages(baseDir)) {
763
561
  const files = new Set()
764
562
  if (existsSync(join(baseDir, 'bootstrap', 'providers.php'))) files.add('bootstrap/providers.php')
@@ -776,9 +574,7 @@ export function loadLaravelProviderFiles(baseDir, autoload, packages = loadCompo
776
574
  return [...files]
777
575
  }
778
576
 
779
- // Names excluded from class-reference scanning: pseudo-types, scalar/special
780
- // types, and keywords that can sit before `$var`/`::` or after `new` and would
781
- // otherwise be mistaken for a class reference (`return $x`, `new class`, …).
577
+ // Names that can sit where a class reference does (`return $x`, `new class`, …) and are none.
782
578
  const RESERVED = new Set([
783
579
  'self', 'static', 'parent', 'this',
784
580
  'int', 'integer', 'float', 'double', 'string', 'bool', 'boolean', 'void',
@@ -789,15 +585,7 @@ const RESERVED = new Set([
789
585
  'endif', 'endswitch', 'endwhile', 'endfor',
790
586
  ])
791
587
 
792
- // Blank heredocs, comments AND string literals (unlike maskCommentsAndHeredocs,
793
- // which keeps strings) so class-reference scans don't trip over text inside them.
794
- function stripPhp(content) {
795
- return maskNonCode(content, false)
796
- }
797
-
798
- // Add the FQCN for a class reference `raw` given namespace `ns` and the `use`-alias
799
- // map, mirroring PHP name resolution: leading `\` = fully-qualified; a first
800
- // segment matching an alias expands through it; else relative to `ns`.
588
+ // As PHP resolves a name: a leading `\` fully qualified, a first segment an alias expands, else relative to `ns`.
801
589
  function addRef(set, raw, ns, aliasMap) {
802
590
  const n = raw.trim().replace(/^\?/u, '') // drop a nullable-type marker (`?Foo`)
803
591
  if (!n || !/^\\?[A-Za-z_][\w\\]*$/u.test(n)) return
@@ -805,21 +593,12 @@ function addRef(set, raw, ns, aliasMap) {
805
593
  set.add(n.replace(/^\\+/u, ''))
806
594
  return
807
595
  }
808
- const first = n.split('\\')[0]
809
- if (!n.includes('\\')) {
810
- if (RESERVED.has(n.toLowerCase())) return
811
- if (aliasMap.has(n)) set.add(aliasMap.get(n))
812
- else set.add(ns ? `${ns}\\${n}` : n)
813
- } else if (aliasMap.has(first)) {
814
- set.add(`${aliasMap.get(first)}\\${n.slice(first.length + 1)}`)
815
- } else {
816
- set.add(ns ? `${ns}\\${n}` : n)
817
- }
596
+ const [first, ...rest] = n.split('\\')
597
+ if (rest.length === 0 && RESERVED.has(n.toLowerCase())) return
598
+ if (aliasMap.has(first)) set.add([aliasMap.get(first), ...rest].join('\\'))
599
+ else set.add(ns ? `${ns}\\${n}` : n)
818
600
  }
819
601
 
820
- // Parse a `use` body (between `use` and `;`) into entries, handling comma lists
821
- // and group syntax (`Pre\{A, B as C}`). Returns `[{ name, short }]` (short = the
822
- // alias or last segment).
823
602
  function parseUseBody(body) {
824
603
  const grouped = body.match(/^([\w\\]+\\)\{([\s\S]*)\}$/u)
825
604
  const entries = grouped
@@ -835,49 +614,38 @@ function parseUseBody(body) {
835
614
  return out
836
615
  }
837
616
 
838
- // Position of the first class/interface/trait/enum declaration -- the end of the
839
- // import region (a `use` before it is an alias import; after it, an in-body trait
840
- // use that loads the trait). `::class`/member accesses excluded via the
841
- // lookbehind. Infinity when there's no class-like declaration.
842
- function firstDeclPos(stripped) {
843
- const m = stripped.match(/(?<![:\w$\\>])\b(?:class|interface|trait|enum)\b/iu)
844
- return m ? m.index : Infinity
845
- }
617
+ // The first class-like declaration ends the import region: a `use` before it is an alias import; after it, an
618
+ // in-body trait use, which loads the trait.
619
+ const firstDeclPos = (stripped) => stripped.match(/(?<![:\w$\\>])\b(?:class|interface|trait|enum)\b/iu)?.index ?? Infinity
846
620
 
847
- // Collect the FQCNs a PHP file actually depends on. A `use` import only aliases
848
- // and loads nothing, so it is NOT a dependency; only real reference sites pull a
849
- // file in (new/extends/implements/instanceof/catch/`Foo::bar`/attributes/type
850
- // hints/FQNs, plus in-body `use Trait;`).
621
+ // A `use` import only aliases and loads nothing, so is no dependency: only where a class is referenced is.
851
622
  export function phpClassDependencies(content) {
852
- const stripped = stripPhp(content)
623
+ // Strings blanked too, so class-reference scans don't trip over text in them.
624
+ const stripped = maskNonCode(content, false)
853
625
  const nsMatch = stripped.match(/\bnamespace\s+([\w\\]+)/u)
854
626
  const ns = nsMatch ? nsMatch[1].replace(/^\\+|\\+$/gu, '') : ''
855
627
  const set = new Set()
628
+ const aliasMap = new Map()
629
+ const add = (raw) => addRef(set, raw, ns, aliasMap)
630
+ const addAll = (re, separator) => {
631
+ for (const m of stripped.matchAll(re)) for (const nm of separator ? m[1].split(separator) : [m[1]]) add(nm)
632
+ }
856
633
 
857
- // `use` before the first declaration builds the alias map; a `use` after it is
858
- // an in-body trait use, counted as a reference.
859
634
  const declAt = firstDeclPos(stripped)
860
- const aliasMap = new Map()
861
- const traitRefs = []
862
635
  for (const m of stripped.matchAll(/\buse\s+(?!\()(function\s+|const\s+)?([\s\S]*?);/giu)) {
863
636
  if (m[1]) continue
864
637
  const entries = parseUseBody(m[2].trim())
865
638
  if (m.index < declAt) {
866
639
  for (const e of entries) aliasMap.set(e.short, e.name.replace(/^\\+/u, ''))
867
640
  } else {
868
- for (const e of entries) traitRefs.push(e.name)
641
+ for (const e of entries) add(e.name)
869
642
  }
870
643
  }
871
644
 
872
- const add = (raw) => addRef(set, raw, ns, aliasMap)
873
- for (const raw of traitRefs) add(raw)
874
-
875
- for (const m of stripped.matchAll(/(?<![\w$\\])new\s+(\\?[\w\\]+)/giu)) add(m[1])
876
- for (const m of stripped.matchAll(/(?<![\w$\\])instanceof\s+(\\?[\w\\]+)/giu)) add(m[1])
877
- for (const m of stripped.matchAll(/(?<![\w$\\])(\\?[\w\\]+)\s*::/giu)) add(m[1])
878
- for (const m of stripped.matchAll(/#\[\s*(\\?[\w\\]+)/giu)) add(m[1])
879
-
880
- // class/interface/trait/enum headers: pull names out of extends/implements.
645
+ addAll(/(?<![\w$\\])new\s+(\\?[\w\\]+)/giu)
646
+ addAll(/(?<![\w$\\])instanceof\s+(\\?[\w\\]+)/giu)
647
+ addAll(/(?<![\w$\\])(\\?[\w\\]+)\s*::/giu)
648
+ addAll(/#\[\s*(\\?[\w\\]+)/giu)
881
649
  for (const m of stripped.matchAll(/\b(?:class|interface|trait|enum)\b[^{;]*?\{/giu)) {
882
650
  const header = m[0]
883
651
  const ext = header.match(/\bextends\s+([\w\\\s,?]+?)(?:\bimplements\b|\{)/iu)
@@ -885,31 +653,16 @@ export function phpClassDependencies(content) {
885
653
  const impl = header.match(/\bimplements\s+([\w\\\s,?]+?)\{/iu)
886
654
  if (impl) for (const nm of impl[1].split(',')) add(nm)
887
655
  }
888
-
889
- // catch (A | B $e), or PHP 8's catch (A | B) with no variable: capture the type
890
- // list up to `$var` or `)`. One quantifier with nothing after it keeps matching
891
- // linear on adversarial input.
892
- for (const m of stripped.matchAll(/\bcatch\s*\(([^)$]*)/giu)) {
893
- for (const nm of m[1].split('|')) add(nm)
894
- }
895
-
896
- // parameter/property type hints: `Type $var`, incl. `?Type`, variadic, by-ref,
897
- // and union/intersection `A|B`/`A&B` (each member counts). Only one whitespace
898
- // quantifier is unbounded (inner `\s*` gated behind `[&.]`) to avoid
899
- // catastrophic backtracking against adversarial input.
900
- for (const m of stripped.matchAll(/(?<![\w$\\])([?\w\\|&]+)\s+(?:[&.]+\s*)?\$\w+/giu)) {
901
- for (const nm of m[1].split(/[|&]/u)) add(nm)
902
- }
903
- // return types: `): Type`, incl. nullable and union/intersection `): A|B`.
904
- for (const m of stripped.matchAll(/\)\s*:\s*([?\w\\|&]+)/giu)) {
905
- for (const nm of m[1].split(/[|&]/u)) add(nm)
906
- }
907
-
656
+ // `catch (A | B $e)`, or PHP 8's with no variable: one quantifier with nothing after it keeps matching linear
657
+ // on adversarial input.
658
+ addAll(/\bcatch\s*\(([^)$]*)/giu, '|')
659
+ // Type hints, `?Type`, variadic, by-ref and `A|B`/`A&B` too, then return types: only one whitespace quantifier
660
+ // is unbounded (the inner `\s*` behind `[&.]`), against catastrophic backtracking.
661
+ addAll(/(?<![\w$\\])([?\w\\|&]+)\s+(?:[&.]+\s*)?\$\w+/giu, /[|&]/u)
662
+ addAll(/\)\s*:\s*([?\w\\|&]+)/giu, /[|&]/u)
908
663
  return set
909
664
  }
910
665
 
911
- // Resolve each autoloaded class a file references to a baseDir-relative file that
912
- // exists and is in `sources`. Best-effort: unresolvable refs skipped.
913
666
  function autoloadEdges(content, autoload, baseDir, sources) {
914
667
  const edges = new Map()
915
668
  if (!autoload) return edges
@@ -920,37 +673,28 @@ function autoloadEdges(content, autoload, baseDir, sources) {
920
673
  return edges
921
674
  }
922
675
 
923
- // Build `{ sources, resolutions, missing }` from already-loaded PHP sources.
924
- // Explicit includes are strict (unresolvable -> `missing`); Composer-autoloaded
925
- // class refs (when `autoload` is given) are best-effort and never added to
926
- // `missing`. Fallback: a specifier matching a stored key verbatim is accepted.
676
+ // Explicit includes are strict (unresolvable -> `missing`); Composer-autoloaded class refs (with `autoload`)
677
+ // best-effort, never `missing`.
927
678
  export function buildPhpTree(sources, { baseDir, autoload = null } = {}) {
928
679
  const resolutions = new Map()
929
680
  const missing = []
930
681
  for (const [path, content] of sources) {
931
682
  const specMap = new Map()
932
683
  for (const spec of extractPhpImports(content)) {
933
- let resolved = resolvePhpImport(spec, path, { baseDir })
934
- if (resolved && !sources.has(resolved)) resolved = null
935
- if (!resolved && sources.has(spec)) resolved = spec
936
- if (resolved) {
937
- specMap.set(spec, resolved)
938
- } else {
684
+ // A specifier naming a stored key verbatim is taken where it resolves to none.
685
+ const resolved = [resolvePhpImport(spec, path, { baseDir }), spec].find((p) => p && sources.has(p))
686
+ if (resolved) specMap.set(spec, resolved)
687
+ else {
939
688
  console.warn(`[loader.php] Missing import: ${spec} from ${path}`)
940
689
  missing.push({ spec, from: path })
941
690
  }
942
691
  }
943
- for (const [fqcn, file] of autoloadEdges(content, autoload, baseDir, sources)) {
944
- specMap.set(fqcn, file)
945
- }
692
+ for (const [fqcn, file] of autoloadEdges(content, autoload, baseDir, sources)) specMap.set(fqcn, file)
946
693
  resolutions.set(path, specMap)
947
694
  }
948
695
  return { sources, resolutions, missing }
949
696
  }
950
697
 
951
- // Walk the filesystem from `entries` (plus Composer `files` autoload entries),
952
- // following resolved includes and autoloaded class refs, reading each file once.
953
- // Same-wave files are read in parallel; the next wave depends on the previous.
954
698
  export async function collectPhpFilesFromDisk(baseDir, entries, { autoload = null } = {}) {
955
699
  const sources = new Map()
956
700
  const realBase = realpathSync(baseDir)
@@ -963,9 +707,7 @@ export async function collectPhpFilesFromDisk(baseDir, entries, { autoload = nul
963
707
  if (!isUtf8(bytes)) throw new Error(`PHP source is not valid UTF-8: ${relPath}`)
964
708
  return [relPath, bytes.toString('utf8')]
965
709
  } catch (err) {
966
- // ENOENT (no file) / EISDIR (specifier resolved to a directory): not a
967
- // loadable file -- warn and skip rather than crash (buildPhpTree surfaces
968
- // the unresolved edge for real includes).
710
+ // No file, or a specifier resolved to a directory: buildPhpTree tells a real include's edge unresolved.
969
711
  if (err.code === 'ENOENT' || err.code === 'EISDIR') {
970
712
  console.warn(`[loader.php] Missing import: ${relPath}`)
971
713
  return null
@@ -974,56 +716,35 @@ export async function collectPhpFilesFromDisk(baseDir, entries, { autoload = nul
974
716
  }
975
717
  }
976
718
 
977
- const processWave = async (wave) => {
719
+ // Composer `files` autoload entries load unconditionally, so they're roots too.
720
+ for (let wave = [...entries, ...(autoload?.files ?? [])]; wave.length > 0;) {
978
721
  const toLoad = [...new Set(wave)].filter((p) => !sources.has(p))
979
- if (toLoad.length === 0) return
980
- // Bounded batches: a wave can be huge (a dynamic include's directory glob),
981
- // and an unbounded Promise.all would open every file at once and crash EMFILE.
982
722
  const reads = []
983
723
  for (let k = 0; k < toLoad.length; k += READ_CONCURRENCY) {
984
724
  // eslint-disable-next-line no-await-in-loop -- batches are intentionally sequential to cap open files
985
725
  reads.push(...(await Promise.all(toLoad.slice(k, k + READ_CONCURRENCY).map(readOne))))
986
726
  }
987
727
  const next = []
988
- for (const entry of reads) {
989
- if (!entry) continue
990
- const [relPath, content] = entry
728
+ for (const [relPath, content] of reads.filter(Boolean)) {
991
729
  sources.set(relPath, content)
992
- const includes = scanIncludes(content)
730
+ const masked = maskedPhp(content)
731
+ const includes = scanIncludes(masked)
993
732
  for (const spec of includeSpecs(includes, 'file')) {
994
733
  const resolved = resolvePhpImport(spec, relPath, { baseDir })
995
- if (resolved) {
996
- if (!sources.has(resolved)) next.push(resolved)
997
- } else {
998
- console.warn(`[loader.php] Missing import: ${spec} from ${relPath}`)
999
- }
734
+ if (resolved) next.push(resolved)
735
+ else console.warn(`[loader.php] Missing import: ${spec} from ${relPath}`)
1000
736
  }
1001
- // Dynamic includes with a static dir prefix: the exact file is known only
1002
- // at runtime, so bundle every `.php` file in that directory as a candidate.
1003
737
  for (const dirSpec of includeSpecs(includes, 'dir')) {
1004
738
  const dir = resolvePhpDir(dirSpec, relPath, baseDir)
1005
- if (!dir) continue
1006
- for (const file of listPhpFiles(baseDir, dir)) {
1007
- if (!sources.has(file)) next.push(file)
1008
- }
739
+ if (dir) for (const file of listPhpFiles(baseDir, dir)) next.push(file)
1009
740
  }
1010
- // `.php` path literals outside a require (route/config files passed to a
1011
- // framework). Best-effort: bundle only if they resolve to an existing file.
1012
- for (const { spec, anchor } of extractPhpPathRefs(content)) {
1013
- const resolved = anchor === 'root'
1014
- ? normalizeProjectRel(baseDir, spec)
1015
- : resolvePhpImport(spec, relPath, { baseDir })
1016
- if (resolved && isFileOnDisk(baseDir, resolved) && !sources.has(resolved)) next.push(resolved)
1017
- }
1018
- // Autoloaded class references (best-effort): enqueue whatever resolves.
1019
- for (const [, file] of autoloadEdges(content, autoload, baseDir, null)) {
1020
- if (!sources.has(file)) next.push(file)
741
+ for (const { spec, anchor } of pathRefs(masked)) {
742
+ const resolved = anchor === 'root' ? normalizeProjectRel(baseDir, spec) : resolvePhpImport(spec, relPath, { baseDir })
743
+ if (resolved && isFileOnDisk(baseDir, resolved)) next.push(resolved)
1021
744
  }
745
+ for (const file of autoloadEdges(content, autoload, baseDir, null).values()) next.push(file)
1022
746
  }
1023
- await processWave(next)
747
+ wave = next
1024
748
  }
1025
-
1026
- // Composer `files` autoload entries load unconditionally, so they're graph roots too.
1027
- await processWave([...entries, ...(autoload?.files ?? [])])
1028
749
  return sources
1029
750
  }