@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,26 +1,22 @@
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'
9
4
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
10
5
  import { isDeepStrictEqual } from 'node:util'
11
6
 
12
- import { assertRealPathWithinBase, isPlainObject, relativeEscapes, toPosix } from '@exodus/stasis-core/util'
7
+ import { isValidRepoField } from '@exodus/stasis-core/bundle'
8
+ import { checkoutCommit, parseGithubRepository } from '@exodus/stasis-core/bundle-util'
9
+ import { archiveIntegrity, assertRealPathWithinBase, fileInBucket, isPlainObject, moduleInfo, relativeEscapes, toPosix, upsert } from '@exodus/stasis-core/util'
13
10
  import { LockfileError, parseComposerLock } from '@preventive/lockfile/composer.js'
14
11
  import { isDir, isFile } from '../resolve-typescript.js'
15
- import { applyToDir } from './paths.js'
12
+ import { applyToDir, isDotRelative } from './paths.js'
16
13
  import { readUtf8OrNull } from './solidity-ownership.js'
17
14
  import { nameErrors } from './toml.js'
18
15
 
19
- // 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.
20
17
  const READ_CONCURRENCY = 64
21
18
 
22
- // End index (exclusive) of the heredoc/nowdoc opener at `start`, or `start` if
23
- // 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.
24
20
  function heredocEnd(code, start) {
25
21
  const n = code.length
26
22
  let j = start + 3
@@ -30,120 +26,91 @@ function heredocEnd(code, start) {
30
26
  while (j < n && /\w/u.test(code[j])) label += code[j++]
31
27
  if (label === '') return start
32
28
  if (quote && code[j] === quote) j++
33
- let p = code.indexOf('\n', j)
34
- if (p === -1) return n
35
- p += 1
36
- while (p <= n) {
37
- let q = p
29
+ for (let nl = code.indexOf('\n', j); nl !== -1; nl = code.indexOf('\n', nl + 1)) {
30
+ let q = nl + 1
38
31
  while (q < n && (code[q] === ' ' || code[q] === '\t')) q++
39
- if (code.startsWith(label, q)) {
40
- const after = code[q + label.length]
41
- if (after === undefined || !/\w/u.test(after)) {
42
- const nl = code.indexOf('\n', q)
43
- return nl === -1 ? n : nl
44
- }
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
45
35
  }
46
- const nl = code.indexOf('\n', p)
47
- if (nl === -1) return n
48
- p = nl + 1
49
36
  }
50
37
  return n
51
38
  }
52
39
 
53
- // Blank everything that isn't executable PHP (comments, heredocs/nowdocs, and
54
- // unless `keepStrings` string literals) to spaces, preserving newlines so byte
55
- // 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.
56
42
  function maskNonCode(code, keepStrings) {
57
43
  const n = code.length
58
- const blank = (s) => s.replace(/[^\n]/gu, ' ')
59
44
  let out = ''
60
45
  let i = 0
61
46
  while (i < n) {
62
47
  const c = code[i]
48
+ let end = i + 1
49
+ let masked = true
63
50
  if ((c === '/' && code[i + 1] === '/') || (c === '#' && code[i + 1] !== '[')) {
64
- let end = code.indexOf('\n', i)
51
+ end = code.indexOf('\n', i)
65
52
  if (end === -1) end = n
66
- out += blank(code.slice(i, end))
67
- i = end
68
53
  } else if (c === '/' && code[i + 1] === '*') {
69
54
  const close = code.indexOf('*/', i + 2)
70
- const end = close === -1 ? n : close + 2
71
- out += blank(code.slice(i, end))
72
- i = end
55
+ end = close === -1 ? n : close + 2
73
56
  } else if (c === '<' && code[i + 1] === '<' && code[i + 2] === '<') {
74
- const end = heredocEnd(code, i)
75
- 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
76
59
  } else if (c === "'" || c === '"') {
77
- let j = i + 1
78
- while (j < n) {
79
- if (code[j] === '\\') { j += 2; continue }
80
- if (code[j] === c) { j++; break }
81
- j++
60
+ while (end < n) {
61
+ if (code[end] === '\\') { end += 2; continue }
62
+ if (code[end++] === c) break
82
63
  }
83
- out += keepStrings ? code.slice(i, j) : blank(code.slice(i, j))
84
- i = j
85
- } else {
86
- out += c
87
- i++
88
- }
64
+ masked = !keepStrings
65
+ } else masked = false
66
+ out += masked ? code.slice(i, end).replace(/[^\n]/gu, ' ') : code.slice(i, end)
67
+ i = end
89
68
  }
90
69
  return out
91
70
  }
92
71
 
93
- // Blank comments/heredocs, keep string literals (include paths live in strings).
94
- function maskCommentsAndHeredocs(content) {
95
- 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) }
96
76
  }
97
77
 
98
- // Scan string literals -> { start, end, value, quote } with PHP single-quote
99
- // unescaping (only `\\` and the closing quote are escapes; other backslashes
100
- // literal -- good enough for path values).
78
+ // Only `\\` and the closing quote unescaped, as PHP's single quotes do: good enough for path values.
101
79
  function stringLiterals(code) {
102
80
  const out = []
103
81
  let i = 0
104
82
  while (i < code.length) {
105
83
  const q = code[i]
106
- if (q === "'" || q === '"') {
107
- let j = i + 1
108
- let value = ''
109
- while (j < code.length) {
110
- const c = code[j]
111
- if (c === '\\') {
112
- const next = code[j + 1]
113
- value += next === '\\' || next === q ? next : c + (next ?? '')
114
- j += next === undefined ? 1 : 2
115
- continue
116
- }
117
- if (c === q) { j++; break }
118
- value += c
119
- 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
120
94
  }
121
- out.push({ start: i, end: j, value, quote: q })
122
- i = j
123
- } else {
124
- i++
95
+ if (c === q) { j++; break }
96
+ value += c
97
+ j++
125
98
  }
99
+ out.push({ start: i, end: j, value, quote: q })
100
+ i = j
126
101
  }
127
102
  return out
128
103
  }
129
104
 
130
- // Whether `pos` is inside one of `strings` (stringLiterals), and the literal starting at `pos`.
131
105
  const inString = (strings, pos) => strings.some(({ start, end }) => pos > start && pos < end)
132
106
  const stringAt = (strings, pos) => strings.find(({ start }) => start === pos)
133
107
 
134
- // Include keyword. The lookbehind rejects method/scope-resolution calls
135
- // (`$x->require`, `Foo::include`); the trailing `\b` stops matching inside
136
- // `requireConfig`. String-literal matches are filtered out by the caller.
108
+ // The lookbehind rejects `$x->require` and `Foo::include`, the `\b` `requireConfig`.
137
109
  const PHP_INCLUDE_KEYWORD_RE = /(?<![\w$>:])(?:require_once|require|include_once|include)\b/gidu
138
-
139
- // Directory anchor (sticky): `__DIR__`/`dirname(__FILE__)` (file's own dir) or
140
- // `dirname(__DIR__[, N])` (N parent levels up).
141
110
  const PHP_DIR_ANCHOR_RE = /__DIR__\b|dirname\s*\(\s*(__FILE__|__DIR__)\s*(?:,\s*(\d+)\s*)?\)/y
142
- // Anchor starts, for scanning path literals anywhere (not just after `require`).
143
111
  const PHP_DIR_ANCHOR_FIND_RE = /(?<![\w$>])(?:__DIR__\b|dirname\s*\(\s*(?:__FILE__|__DIR__))/gu
144
112
 
145
- // Laravel path helpers resolving a string arg relative to the project root (or a
146
- // 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.
147
114
  const PHP_PATH_HELPERS = new Map([
148
115
  ['base_path', ''],
149
116
  ['app_path', 'app'],
@@ -154,11 +121,9 @@ const PHP_PATH_HELPERS = new Map([
154
121
  ['resource_path', 'resources'],
155
122
  ['storage_path', 'storage'],
156
123
  ])
157
- const PHP_PATH_HELPER_FIND_RE =
158
- /(?<![\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')
159
125
 
160
- // Interpolation markers inside a double-quoted string (`$var`, `${...}`,
161
- // `{$...}`). Single-quoted strings never interpolate, so a `$` there is literal.
126
+ // A double-quoted string's interpolation; a single-quoted one's `$` is literal.
162
127
  const PHP_INTERPOLATION_RE = /\$[A-Za-z_{]|\{\$/u
163
128
 
164
129
  function skipWs(code, pos) {
@@ -166,32 +131,20 @@ function skipWs(code, pos) {
166
131
  return pos
167
132
  }
168
133
 
169
- // If a directory anchor starts at `pos`, return { end, up } (up = parent levels
170
- // above the file's dir; 0 for `__DIR__`/`dirname(__FILE__)`); else null.
171
134
  function matchDirAnchor(code, pos) {
172
135
  PHP_DIR_ANCHOR_RE.lastIndex = pos
173
136
  const m = PHP_DIR_ANCHOR_RE.exec(code)
174
137
  if (!m) return null
175
- const up = m[1] === '__DIR__' ? (m[2] ? Number(m[2]) : 1) : 0
176
- 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 }
177
139
  }
178
140
 
179
- // A `./`/`../` specifier, as PHP tells one (a `.`-led NAME like `..cache/a.php` is a bare one).
180
- const isDotRelative = (spec) => spec === '.' || spec === '..' || spec.startsWith('./') || spec.startsWith('../')
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
266
+ export const resolvePhpImport = (specifier, fromFile, { baseDir } = {}) =>
267
+ resolvePhpSpec(specifier, fromFile, baseDir, (rel) => isFileOnDisk(baseDir, rel))
369
268
 
370
- const projRel = projectRel(baseDir, resolve(baseDir, specifier))
371
- if (projRel && isFileOnDisk(baseDir, projRel)) return projRel
372
- }
373
-
374
- return null
375
- }
376
-
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,20 +398,32 @@ function assertInstalledAsLocked(lockText, installedText, { installedFile, vendo
532
398
  return installed
533
399
  }
534
400
 
535
- // The Composer packages of the project at `baseDir`, `[{ name, version, dir, extra }]`, `dir` where
536
- // the package is installed, baseDir-relative (null for nowhere in baseDir, as a metapackage). Of
537
- // its composer.lock where there is one, read by @preventive/lockfile beside composer.json as
538
- // `composer install` reads them -- one it refuses stops the build -- each package where Composer
539
- // installs it (lockedDir), so no install is needed; else of vendor/composer/installed.json, as
540
- // it is. Where both are, installed.json must be the lockfile's install (assertInstalledAsLocked):
541
- // its packages, each where installed.json says.
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) {
404
+ if (source?.type !== 'git') return undefined
405
+ if (fromSource ? at === null || checkoutCommit(at) !== source.reference : dist.reference !== source.reference) return undefined
406
+ const github = parseGithubRepository(source.url)
407
+ return github !== null && isValidRepoField('commit', source.reference) ? { github, directory: '', commit: source.reference } : undefined
408
+ }
409
+
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.
542
419
  export function loadComposerPackages(baseDir) {
543
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)) })
544
422
  const lockText = readUtf8OrNull(join(baseDir, 'composer.lock'), 'composer.lock')
545
423
  if (lockText === null) {
546
424
  return readInstalledPackages(baseDir, vendorDir)
547
425
  .filter((p) => p?.name && p.version)
548
- .map((p) => ({ name: p.name, version: p.version, dir: installedDir(baseDir, vendorDir, p), extra: p.extra }))
426
+ .map((p) => packageAt(p, installedDir(baseDir, vendorDir, p), p['installation-source']))
549
427
  }
550
428
 
551
429
  const composerJson = readUtf8OrNull(join(baseDir, 'composer.json'), 'composer.json')
@@ -554,15 +432,13 @@ export function loadComposerPackages(baseDir) {
554
432
  const installedText = readUtf8OrNull(join(baseDir, installedFile), installedFile)
555
433
  const installed = installedText === null ? null : assertInstalledAsLocked(lockText, installedText, { installedFile, vendorDir })
556
434
  const dirs = installed === null ? null : new Map(installed.packages.map((p) => [p.name, installedDir(baseDir, vendorDir, p)]))
435
+ const from = new Map(installed?.packages.map((p) => [p.name, p['installation-source']]))
557
436
  return Object.values(lock.packages)
558
437
  .filter((p) => dirs === null || dirs.has(p.name))
559
- .map((p) => ({ name: p.name, version: p.version, dir: dirs === null ? lockedDir(baseDir, vendorDir, p) : dirs.get(p.name), extra: p.extra }))
438
+ .map((p) => packageAt(p, dirs === null ? lockedDir(baseDir, vendorDir, p) : dirs.get(p.name), from.get(p.name)))
560
439
  }
561
440
 
562
- // Build the autoload config for `baseDir`, merging the root composer.json
563
- // `autoload`(+dev) with the generated `vendor/composer/autoload_*` maps. All
564
- // paths normalised to POSIX baseDir-relative (escapers dropped). Returns
565
- // `{ psr4, psr0, classmap, files }`, or null when no Composer config is found.
441
+ // Null where there is no Composer config.
566
442
  export function loadComposerAutoload(baseDir) {
567
443
  const { composerJson, vendorDir } = readComposerJson(baseDir)
568
444
 
@@ -573,17 +449,10 @@ export function loadComposerAutoload(baseDir) {
573
449
  let found = false
574
450
 
575
451
  const mergeDirs = (map, prefix, dirs) => map.set(prefix, [...new Set([...(map.get(prefix) ?? []), ...dirs])])
576
- const addPrefixDirs = (map, prefix, paths) => {
577
- const list = Array.isArray(paths) ? paths : [paths]
578
- const dirs = []
579
- for (const p of list) {
580
- const rel = normalizeProjectRel(baseDir, String(p))
581
- if (rel !== null) dirs.push(rel)
582
- }
583
- mergeDirs(map, prefix, dirs)
584
- }
452
+ const addPrefixDirs = (map, prefix, paths) =>
453
+ mergeDirs(map, prefix, [paths].flat().map((p) => normalizeProjectRel(baseDir, String(p))).filter((rel) => rel !== null))
585
454
 
586
- // Root composer.json autoload (+ dev). PSR-4 keys keep their trailing '\'.
455
+ // PSR-4 keys keep their trailing '\'.
587
456
  for (const block of [composerJson?.autoload, composerJson?.['autoload-dev']]) {
588
457
  if (!block || typeof block !== 'object') continue
589
458
  found = true
@@ -595,11 +464,9 @@ export function loadComposerAutoload(baseDir) {
595
464
  }
596
465
  }
597
466
 
598
- // Generated maps. `$vendorDir` = <baseDir>/<vendorDir>, `$baseDir` = <baseDir>.
599
467
  const composerGenDir = join(baseDir, vendorDir, 'composer')
600
468
  const vars = { baseDir: resolve(baseDir), vendorDir: resolve(baseDir, vendorDir) }
601
469
  const toRel = (abs) => projectRel(baseDir, abs) || null
602
- // A generated map's entries; none when the file is absent.
603
470
  const generated = (name, multi) => {
604
471
  const file = join(composerGenDir, name)
605
472
  if (!existsSync(file)) return new Map()
@@ -624,104 +491,63 @@ export function loadComposerAutoload(baseDir) {
624
491
  return { psr4, psr0, classmap, files: [...files] }
625
492
  }
626
493
 
627
- // Resolve a FQCN to a baseDir-relative file via the autoload config, mirroring
628
- // Composer's lookup order: classmap, then longest PSR-4 prefix, then PSR-0. Only
629
- // 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.
630
496
  export function resolveClassFile(fqcn, autoload, baseDir) {
631
497
  if (!autoload || !fqcn) return null
632
498
  const name = fqcn.replace(/^\\+/u, '')
633
499
  if (!name) return null
634
-
635
- const exact = autoload.classmap.get(name)
636
- if (exact && isFileOnDisk(baseDir, exact)) return exact
637
-
638
- // PSR-4: try every matching prefix longest-first (Composer falls back from a
639
- // longer prefix whose file is absent to a shorter one, incl. the `""` prefix).
640
- for (const [prefix, dirs] of matchingPrefixes(autoload.psr4, name)) {
641
- const sub = name.slice(prefix.length).replace(/\\/gu, '/')
642
- for (const dir of dirs) {
643
- const file = dir ? `${dir}/${sub}.php` : `${sub}.php`
644
- if (isFileOnDisk(baseDir, file)) return file
645
- }
646
- }
647
-
648
- // PSR-0: namespace separators AND underscores in the class name map to
649
- // directory separators; the namespace prefix is kept under the mapped dir.
650
- for (const [, dirs] of matchingPrefixes(autoload.psr0, name)) {
651
- const lastNs = name.lastIndexOf('\\')
652
- const nsPart = lastNs === -1 ? '' : name.slice(0, lastNs).replace(/\\/gu, '/')
653
- const clsPart = (lastNs === -1 ? name : name.slice(lastNs + 1)).replace(/_/gu, '/')
654
- const sub = `${nsPart ? `${nsPart}/` : ''}${clsPart}.php`
655
- for (const dir of dirs) {
656
- const file = dir ? `${dir}/${sub}` : sub
657
- if (isFileOnDisk(baseDir, file)) return file
658
- }
659
- }
660
-
661
- return null
662
- }
663
-
664
- // [prefix, dirs] entries whose prefix is a prefix of `name`, longest first --
665
- // prefer the most specific mapping, fall back to shorter (and the `""` fallback).
666
- function matchingPrefixes(map, name) {
667
- return [...map].filter(([prefix]) => name.startsWith(prefix)).toSorted((a, b) => b[0].length - a[0].length)
668
- }
669
-
670
- // The versions of the Composer `packages` (loadComposerPackages: the authoritative source; a
671
- // 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`.
672
516
  function packageVersions(packages) {
673
517
  const byDir = new Map()
674
518
  const byName = new Map()
675
- for (const { name, version, dir } of packages) {
676
- byName.set(name, version)
677
- if (dir) byDir.set(dir, version)
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)
678
523
  }
679
524
  return { byDir, byName }
680
525
  }
681
526
 
682
- // Walk up from a bundled file to the nearest named composer.json, returning
683
- // { pkgDir, name, version } (pkgDir "." for the root; version from composer.lock or
684
- // installed.json by dir/name, else composer.json `version`, else `fallbackVersion`). Null if none.
685
527
  function findComposerPackage(baseDir, fileRelPath, installed, fallbackVersion) {
686
- let dir = dirname(fileRelPath)
687
- for (;;) {
528
+ for (let dir = dirname(fileRelPath); ; dir = dirname(dir)) {
688
529
  const cj = readJsonIfExists(join(baseDir, dir, 'composer.json'))
689
530
  if (cj?.name) {
690
- const version = installed.byDir.get(dir) ?? installed.byName.get(cj.name) ?? cj.version ?? fallbackVersion
691
- return { pkgDir: dir, name: cj.name, version }
531
+ const known = installed.byDir.get(dir) ?? installed.byName.get(cj.name)
532
+ return { pkgDir: dir, name: cj.name, version: known?.version ?? cj.version ?? fallbackVersion, repo: known?.repo, integrity: known?.integrity }
692
533
  }
693
- if (dir === '.' || dir === '/' || dir === '') return null
694
- const parent = dirname(dir)
695
- if (parent === dir) return null
696
- dir = parent
534
+ if (dirname(dir) === dir) return null
697
535
  }
698
536
  }
699
537
 
700
- // Group bundled PHP sources into per-package buckets keyed by the nearest
701
- // composer.json's directory (vendor deps get their own; workspace files and
702
- // orphans -> the root "." bucket with the placeholder identity). Returns a
703
- // Map<dir, { name, version, files }>. `packages`: loadComposerPackages(baseDir).
538
+ // By the nearest composer.json's directory; workspace files and orphans in the root "." bucket, the placeholder's.
704
539
  export function bucketizePhpSources(baseDir, sources, fallbackName, fallbackVersion, packages = loadComposerPackages(baseDir)) {
705
540
  const installed = packageVersions(packages)
706
-
707
541
  const modules = new Map()
708
- const ensureBucket = (dir, name, version, ecosystem) => {
709
- if (!modules.has(dir)) {
710
- modules.set(dir, ecosystem === undefined
711
- ? { name, version, files: Object.create(null) }
712
- : { name, version, ecosystem, files: Object.create(null) })
713
- }
714
- return modules.get(dir)
715
- }
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) }))
716
544
 
717
545
  for (const [path, content] of sources) {
718
546
  const pkg = findComposerPackage(baseDir, path, installed, fallbackVersion)
719
547
  if (pkg) {
720
- const rel = pkg.pkgDir === '.' ? path : path.slice(pkg.pkgDir.length + 1)
721
- // Below the root package = an installed Composer dependency, tagged
722
- // `composer`; the root "." bucket is workspace code and stays ecosystem-less.
548
+ // The root package is workspace code; one below it an installed dependency.
723
549
  const ecosystem = pkg.pkgDir === '.' ? undefined : 'composer'
724
- ensureBucket(pkg.pkgDir, pkg.name, pkg.version, ecosystem).files[rel] = content
550
+ ensureBucket(pkg.pkgDir, pkg.name, pkg.version, ecosystem, pkg).files[fileInBucket(pkg.pkgDir, path)] = content
725
551
  } else {
726
552
  ensureBucket('.', fallbackName, fallbackVersion).files[path] = content
727
553
  }
@@ -729,11 +555,8 @@ export function bucketizePhpSources(baseDir, sources, fallbackName, fallbackVers
729
555
  return modules
730
556
  }
731
557
 
732
- // Laravel auto-registers service providers nothing references statically. Returns
733
- // discoverable provider files (from composer.json + the Composer `packages`'
734
- // `extra.laravel.providers`, autoload-resolved) plus bootstrap/providers.php as
735
- // extra collection roots. Best-effort: unresolvable classes skipped.
736
- // `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.
737
560
  export function loadLaravelProviderFiles(baseDir, autoload, packages = loadComposerPackages(baseDir)) {
738
561
  const files = new Set()
739
562
  if (existsSync(join(baseDir, 'bootstrap', 'providers.php'))) files.add('bootstrap/providers.php')
@@ -751,9 +574,7 @@ export function loadLaravelProviderFiles(baseDir, autoload, packages = loadCompo
751
574
  return [...files]
752
575
  }
753
576
 
754
- // Names excluded from class-reference scanning: pseudo-types, scalar/special
755
- // types, and keywords that can sit before `$var`/`::` or after `new` and would
756
- // 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.
757
578
  const RESERVED = new Set([
758
579
  'self', 'static', 'parent', 'this',
759
580
  'int', 'integer', 'float', 'double', 'string', 'bool', 'boolean', 'void',
@@ -764,15 +585,7 @@ const RESERVED = new Set([
764
585
  'endif', 'endswitch', 'endwhile', 'endfor',
765
586
  ])
766
587
 
767
- // Blank heredocs, comments AND string literals (unlike maskCommentsAndHeredocs,
768
- // which keeps strings) so class-reference scans don't trip over text inside them.
769
- function stripPhp(content) {
770
- return maskNonCode(content, false)
771
- }
772
-
773
- // Add the FQCN for a class reference `raw` given namespace `ns` and the `use`-alias
774
- // map, mirroring PHP name resolution: leading `\` = fully-qualified; a first
775
- // 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`.
776
589
  function addRef(set, raw, ns, aliasMap) {
777
590
  const n = raw.trim().replace(/^\?/u, '') // drop a nullable-type marker (`?Foo`)
778
591
  if (!n || !/^\\?[A-Za-z_][\w\\]*$/u.test(n)) return
@@ -780,21 +593,12 @@ function addRef(set, raw, ns, aliasMap) {
780
593
  set.add(n.replace(/^\\+/u, ''))
781
594
  return
782
595
  }
783
- const first = n.split('\\')[0]
784
- if (!n.includes('\\')) {
785
- if (RESERVED.has(n.toLowerCase())) return
786
- if (aliasMap.has(n)) set.add(aliasMap.get(n))
787
- else set.add(ns ? `${ns}\\${n}` : n)
788
- } else if (aliasMap.has(first)) {
789
- set.add(`${aliasMap.get(first)}\\${n.slice(first.length + 1)}`)
790
- } else {
791
- set.add(ns ? `${ns}\\${n}` : n)
792
- }
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)
793
600
  }
794
601
 
795
- // Parse a `use` body (between `use` and `;`) into entries, handling comma lists
796
- // and group syntax (`Pre\{A, B as C}`). Returns `[{ name, short }]` (short = the
797
- // alias or last segment).
798
602
  function parseUseBody(body) {
799
603
  const grouped = body.match(/^([\w\\]+\\)\{([\s\S]*)\}$/u)
800
604
  const entries = grouped
@@ -810,49 +614,38 @@ function parseUseBody(body) {
810
614
  return out
811
615
  }
812
616
 
813
- // Position of the first class/interface/trait/enum declaration -- the end of the
814
- // import region (a `use` before it is an alias import; after it, an in-body trait
815
- // use that loads the trait). `::class`/member accesses excluded via the
816
- // lookbehind. Infinity when there's no class-like declaration.
817
- function firstDeclPos(stripped) {
818
- const m = stripped.match(/(?<![:\w$\\>])\b(?:class|interface|trait|enum)\b/iu)
819
- return m ? m.index : Infinity
820
- }
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
821
620
 
822
- // Collect the FQCNs a PHP file actually depends on. A `use` import only aliases
823
- // and loads nothing, so it is NOT a dependency; only real reference sites pull a
824
- // file in (new/extends/implements/instanceof/catch/`Foo::bar`/attributes/type
825
- // 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.
826
622
  export function phpClassDependencies(content) {
827
- 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)
828
625
  const nsMatch = stripped.match(/\bnamespace\s+([\w\\]+)/u)
829
626
  const ns = nsMatch ? nsMatch[1].replace(/^\\+|\\+$/gu, '') : ''
830
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
+ }
831
633
 
832
- // `use` before the first declaration builds the alias map; a `use` after it is
833
- // an in-body trait use, counted as a reference.
834
634
  const declAt = firstDeclPos(stripped)
835
- const aliasMap = new Map()
836
- const traitRefs = []
837
635
  for (const m of stripped.matchAll(/\buse\s+(?!\()(function\s+|const\s+)?([\s\S]*?);/giu)) {
838
636
  if (m[1]) continue
839
637
  const entries = parseUseBody(m[2].trim())
840
638
  if (m.index < declAt) {
841
639
  for (const e of entries) aliasMap.set(e.short, e.name.replace(/^\\+/u, ''))
842
640
  } else {
843
- for (const e of entries) traitRefs.push(e.name)
641
+ for (const e of entries) add(e.name)
844
642
  }
845
643
  }
846
644
 
847
- const add = (raw) => addRef(set, raw, ns, aliasMap)
848
- for (const raw of traitRefs) add(raw)
849
-
850
- for (const m of stripped.matchAll(/(?<![\w$\\])new\s+(\\?[\w\\]+)/giu)) add(m[1])
851
- for (const m of stripped.matchAll(/(?<![\w$\\])instanceof\s+(\\?[\w\\]+)/giu)) add(m[1])
852
- for (const m of stripped.matchAll(/(?<![\w$\\])(\\?[\w\\]+)\s*::/giu)) add(m[1])
853
- for (const m of stripped.matchAll(/#\[\s*(\\?[\w\\]+)/giu)) add(m[1])
854
-
855
- // 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)
856
649
  for (const m of stripped.matchAll(/\b(?:class|interface|trait|enum)\b[^{;]*?\{/giu)) {
857
650
  const header = m[0]
858
651
  const ext = header.match(/\bextends\s+([\w\\\s,?]+?)(?:\bimplements\b|\{)/iu)
@@ -860,31 +653,16 @@ export function phpClassDependencies(content) {
860
653
  const impl = header.match(/\bimplements\s+([\w\\\s,?]+?)\{/iu)
861
654
  if (impl) for (const nm of impl[1].split(',')) add(nm)
862
655
  }
863
-
864
- // catch (A | B $e), or PHP 8's catch (A | B) with no variable: capture the type
865
- // list up to `$var` or `)`. One quantifier with nothing after it keeps matching
866
- // linear on adversarial input.
867
- for (const m of stripped.matchAll(/\bcatch\s*\(([^)$]*)/giu)) {
868
- for (const nm of m[1].split('|')) add(nm)
869
- }
870
-
871
- // parameter/property type hints: `Type $var`, incl. `?Type`, variadic, by-ref,
872
- // and union/intersection `A|B`/`A&B` (each member counts). Only one whitespace
873
- // quantifier is unbounded (inner `\s*` gated behind `[&.]`) to avoid
874
- // catastrophic backtracking against adversarial input.
875
- for (const m of stripped.matchAll(/(?<![\w$\\])([?\w\\|&]+)\s+(?:[&.]+\s*)?\$\w+/giu)) {
876
- for (const nm of m[1].split(/[|&]/u)) add(nm)
877
- }
878
- // return types: `): Type`, incl. nullable and union/intersection `): A|B`.
879
- for (const m of stripped.matchAll(/\)\s*:\s*([?\w\\|&]+)/giu)) {
880
- for (const nm of m[1].split(/[|&]/u)) add(nm)
881
- }
882
-
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)
883
663
  return set
884
664
  }
885
665
 
886
- // Resolve each autoloaded class a file references to a baseDir-relative file that
887
- // exists and is in `sources`. Best-effort: unresolvable refs skipped.
888
666
  function autoloadEdges(content, autoload, baseDir, sources) {
889
667
  const edges = new Map()
890
668
  if (!autoload) return edges
@@ -895,37 +673,28 @@ function autoloadEdges(content, autoload, baseDir, sources) {
895
673
  return edges
896
674
  }
897
675
 
898
- // Build `{ sources, resolutions, missing }` from already-loaded PHP sources.
899
- // Explicit includes are strict (unresolvable -> `missing`); Composer-autoloaded
900
- // class refs (when `autoload` is given) are best-effort and never added to
901
- // `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`.
902
678
  export function buildPhpTree(sources, { baseDir, autoload = null } = {}) {
903
679
  const resolutions = new Map()
904
680
  const missing = []
905
681
  for (const [path, content] of sources) {
906
682
  const specMap = new Map()
907
683
  for (const spec of extractPhpImports(content)) {
908
- let resolved = resolvePhpImport(spec, path, { baseDir })
909
- if (resolved && !sources.has(resolved)) resolved = null
910
- if (!resolved && sources.has(spec)) resolved = spec
911
- if (resolved) {
912
- specMap.set(spec, resolved)
913
- } 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 {
914
688
  console.warn(`[loader.php] Missing import: ${spec} from ${path}`)
915
689
  missing.push({ spec, from: path })
916
690
  }
917
691
  }
918
- for (const [fqcn, file] of autoloadEdges(content, autoload, baseDir, sources)) {
919
- specMap.set(fqcn, file)
920
- }
692
+ for (const [fqcn, file] of autoloadEdges(content, autoload, baseDir, sources)) specMap.set(fqcn, file)
921
693
  resolutions.set(path, specMap)
922
694
  }
923
695
  return { sources, resolutions, missing }
924
696
  }
925
697
 
926
- // Walk the filesystem from `entries` (plus Composer `files` autoload entries),
927
- // following resolved includes and autoloaded class refs, reading each file once.
928
- // Same-wave files are read in parallel; the next wave depends on the previous.
929
698
  export async function collectPhpFilesFromDisk(baseDir, entries, { autoload = null } = {}) {
930
699
  const sources = new Map()
931
700
  const realBase = realpathSync(baseDir)
@@ -938,9 +707,7 @@ export async function collectPhpFilesFromDisk(baseDir, entries, { autoload = nul
938
707
  if (!isUtf8(bytes)) throw new Error(`PHP source is not valid UTF-8: ${relPath}`)
939
708
  return [relPath, bytes.toString('utf8')]
940
709
  } catch (err) {
941
- // ENOENT (no file) / EISDIR (specifier resolved to a directory): not a
942
- // loadable file -- warn and skip rather than crash (buildPhpTree surfaces
943
- // the unresolved edge for real includes).
710
+ // No file, or a specifier resolved to a directory: buildPhpTree tells a real include's edge unresolved.
944
711
  if (err.code === 'ENOENT' || err.code === 'EISDIR') {
945
712
  console.warn(`[loader.php] Missing import: ${relPath}`)
946
713
  return null
@@ -949,56 +716,35 @@ export async function collectPhpFilesFromDisk(baseDir, entries, { autoload = nul
949
716
  }
950
717
  }
951
718
 
952
- 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;) {
953
721
  const toLoad = [...new Set(wave)].filter((p) => !sources.has(p))
954
- if (toLoad.length === 0) return
955
- // Bounded batches: a wave can be huge (a dynamic include's directory glob),
956
- // and an unbounded Promise.all would open every file at once and crash EMFILE.
957
722
  const reads = []
958
723
  for (let k = 0; k < toLoad.length; k += READ_CONCURRENCY) {
959
724
  // eslint-disable-next-line no-await-in-loop -- batches are intentionally sequential to cap open files
960
725
  reads.push(...(await Promise.all(toLoad.slice(k, k + READ_CONCURRENCY).map(readOne))))
961
726
  }
962
727
  const next = []
963
- for (const entry of reads) {
964
- if (!entry) continue
965
- const [relPath, content] = entry
728
+ for (const [relPath, content] of reads.filter(Boolean)) {
966
729
  sources.set(relPath, content)
967
- const includes = scanIncludes(content)
730
+ const masked = maskedPhp(content)
731
+ const includes = scanIncludes(masked)
968
732
  for (const spec of includeSpecs(includes, 'file')) {
969
733
  const resolved = resolvePhpImport(spec, relPath, { baseDir })
970
- if (resolved) {
971
- if (!sources.has(resolved)) next.push(resolved)
972
- } else {
973
- console.warn(`[loader.php] Missing import: ${spec} from ${relPath}`)
974
- }
734
+ if (resolved) next.push(resolved)
735
+ else console.warn(`[loader.php] Missing import: ${spec} from ${relPath}`)
975
736
  }
976
- // Dynamic includes with a static dir prefix: the exact file is known only
977
- // at runtime, so bundle every `.php` file in that directory as a candidate.
978
737
  for (const dirSpec of includeSpecs(includes, 'dir')) {
979
738
  const dir = resolvePhpDir(dirSpec, relPath, baseDir)
980
- if (!dir) continue
981
- for (const file of listPhpFiles(baseDir, dir)) {
982
- if (!sources.has(file)) next.push(file)
983
- }
739
+ if (dir) for (const file of listPhpFiles(baseDir, dir)) next.push(file)
984
740
  }
985
- // `.php` path literals outside a require (route/config files passed to a
986
- // framework). Best-effort: bundle only if they resolve to an existing file.
987
- for (const { spec, anchor } of extractPhpPathRefs(content)) {
988
- const resolved = anchor === 'root'
989
- ? normalizeProjectRel(baseDir, spec)
990
- : resolvePhpImport(spec, relPath, { baseDir })
991
- if (resolved && isFileOnDisk(baseDir, resolved) && !sources.has(resolved)) next.push(resolved)
992
- }
993
- // Autoloaded class references (best-effort): enqueue whatever resolves.
994
- for (const [, file] of autoloadEdges(content, autoload, baseDir, null)) {
995
- 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)
996
744
  }
745
+ for (const file of autoloadEdges(content, autoload, baseDir, null).values()) next.push(file)
997
746
  }
998
- await processWave(next)
747
+ wave = next
999
748
  }
1000
-
1001
- // Composer `files` autoload entries load unconditionally, so they're graph roots too.
1002
- await processWave([...entries, ...(autoload?.files ?? [])])
1003
749
  return sources
1004
750
  }