@exodus/stasis-core 1.0.0-beta.1 → 1.0.0-beta.10

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.
package/src/util.js CHANGED
@@ -1,70 +1,51 @@
1
- import * as fs from 'node:fs'
2
- import { basename, isAbsolute, join, posix, relative } from 'node:path'
3
-
4
- // Snapshot realpathSync at module-eval, BEFORE `stasis run --fs` patches fs.realpathSync.
5
- // The patch + syncBuiltinESMExports() repoint a LIVE `import { realpathSync }` binding to the
6
- // bundle-serving wrapper, which (by design, for user code) does NOT throw ENOENT for a
7
- // recorded-but-absent path -- which would silently defeat assertRealPathWithinBase's reliance
8
- // on that throw (see its comment). Stasis's own reads must stay on the genuine builtin, so we
9
- // snapshot here exactly like state.js / state-util.js / fs.js do for the other patched readers.
10
- const { realpathSync } = fs
11
-
12
- const sep = '/'
13
-
14
- // The full, finite universe of `format` strings stasis knows. Lockfile and bundle
15
- // parsers reject any value outside this set so a tampered or forward-incompatible
16
- // artifact fails closed at the schema boundary, not at a later string compare.
17
- // Categories:
18
- // Executable by Node's loader — module, commonjs, json, *-typescript
19
- // Source languages (analysis-only, not runnable by Node) — solidity, php, bash, rust
20
- // Resources (asset payloads) — resource (raw UTF-8), resource:base64 (binary)
21
- // Filesystem captures (`stasis run --fs`) — directory (a JSON-serialized,
22
- // sorted `fs.readdirSync` listing; a resource-like raw-UTF-8 payload)
23
- // Adding a new format is a deliberate schema change: list it here AND extend
24
- // hooks.js's executable allowlist if Node should serve it from a bundle.
25
- export const KNOWN_FORMATS = new Set([
26
- 'module',
27
- 'commonjs',
28
- 'json',
29
- 'module-typescript',
30
- 'commonjs-typescript',
31
- 'solidity',
32
- 'php',
33
- 'bash',
34
- 'rust',
35
- 'resource',
36
- 'resource:base64',
37
- 'directory',
1
+ import { isUtf8 } from 'node:buffer'
2
+ import { basename, isAbsolute, join, relative, sep } from 'node:path'
3
+ import { parseArgs } from 'node:util'
4
+
5
+ import { NODE_FORMATS } from './artifact-util.js'
6
+ import { diskHost } from './host.js'
7
+
8
+ // The Node-side half of the util split: byte/name classification for the capture walks, fs/execute-bit
9
+ // observation and CLI parsing. The pure artifact data model lives in artifact-util.js, re-exported
10
+ // here so `@exodus/stasis-core/util` keeps serving the full set.
11
+ export * from './artifact-util.js'
12
+
13
+ // JS_UNRESOLVED_EXTS (.js/.ts type/syntax-dependent, .jsx/.tsx transformed) classify as null, not a format.
14
+ const NODE_EXT_FORMATS = new Map([
15
+ ['mjs', 'module'], ['cjs', 'commonjs'], ['json', 'json'],
16
+ ['mts', 'module-typescript'], ['cts', 'commonjs-typescript'],
38
17
  ])
18
+ const JS_UNRESOLVED_EXTS = new Set(['js', 'ts', 'jsx', 'tsx'])
19
+ export const CODE_EXTENSIONS = new Set([...NODE_EXT_FORMATS.keys(), ...JS_UNRESOLVED_EXTS])
39
20
 
40
- // File extensions whose bytes are JS-shaped code -- Node's loader and the
41
- // lockfile/bundle format machinery can attest them (module/commonjs/json/
42
- // *-typescript) and `bundle=load` can round-trip them as modules. This is the
43
- // SINGLE source of truth for "is this a code file", shared so the two capture
44
- // paths can't disagree: bundler plugins classify module-graph imports against it
45
- // (classifyExtension), parseResourcesOption refuses to admit any of these into a
46
- // `resources` allowlist (a code file is never an asset payload), and State both
47
- // classifies `--fs` reads and guards `resource:true` against it. Dot-less +
48
- // lowercase, matching pathExt. Drift here was the root of a lockfile/bundle
49
- // desync: `.jsx`/`.tsx` were code to the plugins but missing from the fs-capture's
50
- // own set, so an fs-read tagged a `.jsx` 'resource' while the import tagged it code.
51
- export const CODE_EXTENSIONS = new Set(['js', 'mjs', 'cjs', 'ts', 'jsx', 'tsx', 'json', 'mts', 'cts'])
52
-
53
- // Lowercased, dot-less extension of a path, or '' if none.
54
21
  export function pathExt(filePath) {
55
22
  const m = /\.([^./\\]+)$/.exec(filePath)
56
23
  return m ? m[1].toLowerCase() : ''
57
24
  }
58
25
 
59
- // Validates + normalizes a `resources` allowlist (plugin option, --resources flag,
60
- // EXODUS_STASIS_RESOURCES, or stasis.config.json) into a Set of lowercase entries. Each
61
- // entry is either a bare extension (`png`, `.png`) or an extensionless filename
62
- // (`LICENSE`, `Makefile`, `license-mit`); classifyExtension matches a file by its
63
- // extension, falling back to its basename when it has none. A dotted entry like
64
- // `data.bin` is rejected -- a file that HAS an extension is keyed by it, so the entry
65
- // would never match; declare the extension (`bin`) instead. Code extensions are rejected
66
- // too (always tracked). Throwing here surfaces misconfigurations immediately rather than
67
- // as silent capture drift. `resources` may be an array (option / config) or undefined.
26
+ // A native path as the '/'-joined form every artifact key uses. Off Windows `\` is no separator but
27
+ // part of a name, and a name holding one is refused rather than taken for another path.
28
+ export function toPosix(path) {
29
+ if (sep === '\\') return path.replaceAll('\\', '/')
30
+ if (path.includes('\\')) throw new Error(`stasis: a path holding '\\' is not supported: ${path}`)
31
+ return path
32
+ }
33
+
34
+ // Whether a path.relative() result climbs out of its base: absolute, or beginning with a `..`
35
+ // SEGMENT -- a bare startsWith('..') would also reject a legitimate `..cache` name.
36
+ export const relativeEscapes = (rel) => rel === '..' || rel.startsWith('../') || rel.startsWith(`..${sep}`) || isAbsolute(rel)
37
+
38
+ // True when `path` is `base` or lies beneath it. Lexical: resolve real paths first where symlinks matter.
39
+ export const isPathWithin = (base, path) => !relativeEscapes(relative(base, path))
40
+
41
+ // Both rules are needed: pathExt('.env.local') is 'local', and the extension rule alone misses `.env.*`.
42
+ export function isDotEnvFile(name) {
43
+ const base = basename(name).toLowerCase()
44
+ return base === '.env' || base.startsWith('.env.') || pathExt(base) === 'env'
45
+ }
46
+
47
+ // Entries are a bare extension (`png`) or extensionless filename (`LICENSE`); a dotted entry
48
+ // (`data.bin`) is rejected because a file with an extension is keyed by it and would never match.
68
49
  export function parseResourcesOption(label, resources) {
69
50
  if (resources === undefined) return new Set()
70
51
  if (!Array.isArray(resources)) {
@@ -87,124 +68,281 @@ export function parseResourcesOption(label, resources) {
87
68
  return out
88
69
  }
89
70
 
90
- // Classifies a file against the code set + a parsed resources allowlist. Returns 'code'
91
- // (track with its loader format), 'resource' (track with a 'resource'/'resource:base64'
92
- // format -- the encoding is chosen from content), or 'unknown' (caller must reject). A
93
- // file is keyed by its extension, or -- when it has none (LICENSE, Makefile, a dotless
94
- // name) -- by its basename, so a resources entry can be an extension or an extensionless
95
- // filename. The 'unknown' path forces every non-JS asset to be declared explicitly -- no
96
- // silent attestation widening. The SINGLE classifier for both capture paths: bundler
97
- // plugins run it on module-graph imports, State runs it on `--fs` reads, so the two
98
- // can't drift.
71
+ export const isBrotliQuality = (n) => Number.isInteger(n) && n >= 0 && n <= 11
72
+
73
+ // `${n}` must round-trip to the input, so non-canonical forms ('5.0', '05', ' 5 ') throw.
74
+ export function parseBrotliQuality(name, value) {
75
+ const n = Number(value)
76
+ if (`${n}` !== value || !isBrotliQuality(n)) {
77
+ throw new RangeError(`${name} must be an integer 0..11 (got '${value}')`)
78
+ }
79
+ return n
80
+ }
81
+
82
+ // Shifts the leading option tokens off `argv`, stopping at the first positional so `run`'s forwarded
83
+ // child argv survives. `valueFlags` lists options whose separate-token value (`-o dir`) isn't the positional.
84
+ export function parseLeadingOptions(argv, options, { valueFlags = [], onError } = {}) {
85
+ const takesValue = new Set(valueFlags)
86
+ const flags = []
87
+ while (argv.length > 0 && (argv[0].startsWith('-') || takesValue.has(flags.at(-1)))) {
88
+ flags.push(argv.shift())
89
+ }
90
+ try {
91
+ return parseArgs({ args: flags, options }).values
92
+ } catch (cause) {
93
+ onError(`Error: ${cause.message}`) // usage(), which exits
94
+ return undefined
95
+ }
96
+ }
97
+
98
+ // The JS-graph bundlers' policy view over classifyFormat: only JS-family code (null or a NODE_FORMAT)
99
+ // counts as 'code'; native/source formats don't. Otherwise 'resource' if allowlisted, else 'unknown'.
99
100
  export function classifyExtension(filePath, resources) {
100
- const ext = pathExt(filePath)
101
- if (CODE_EXTENSIONS.has(ext)) return 'code'
102
- if (resources.has(ext || basename(filePath).toLowerCase())) return 'resource'
101
+ const format = classifyFormat(filePath)
102
+ if (format === null || NODE_FORMATS.has(format)) return 'code'
103
+ if (resources.has(pathExt(filePath) || basename(filePath).toLowerCase())) return 'resource'
103
104
  return 'unknown'
104
105
  }
105
106
 
106
- // Set-equality for parsed resources allowlists (lowercase extension/filename sets).
107
- // Coordinates a plugin's `resources` option against an active preload's, and the env
108
- // var against an explicit option in Config.
109
- export function extSetsEqual(a, b) {
110
- if (a.size !== b.size) return false
111
- for (const ext of a) if (!b.has(ext)) return false
112
- return true
113
- }
114
-
115
- // Flat project-relative key for the file `rel` inside module dir `dir`, inverse of
116
- // the bucketing State/Bundle apply. The `rel === ''` branch is reached only by a
117
- // `directory` capture whose path IS a module root (e.g. `fs.readdirSync` of a
118
- // package dir, or of the project root): the listing is keyed at the bucket itself,
119
- // so the flat key is the dir (or '' for the workspace root) — never `${dir}/`,
120
- // which a trailing-slash join would wrongly produce and break the round-trip. For
121
- // every ordinary file `rel` is a real basename, so this matches the historical
122
- // `dir === '.' ? rel : `${dir}/${rel}`` exactly.
123
- export function moduleFileKey(dir, rel) {
124
- if (rel === '') return dir === '.' ? '' : dir
125
- return dir === '.' ? rel : `${dir}/${rel}`
126
- }
127
-
128
- // Resolve `baseDir/relPath` through symlinks and confirm the real target stays
129
- // within `realBase` (the caller-resolved real path of baseDir). Throws on a
130
- // symlink that escapes the bundle root: a crafted in-tree symlink
131
- // (`link.sh -> /etc/passwd`, or a symlinked directory) must not pull an
132
- // external file into a self-contained, attestable bundle. The textual path
133
- // guards elsewhere don't catch this because they never resolve symlinks.
134
- // realpathSync surfaces ENOENT for a missing path, which the loaders' disk
135
- // walks already handle as "missing".
136
- export function assertRealPathWithinBase(realBase, baseDir, relPath) {
137
- const real = realpathSync(join(baseDir, relPath))
138
- const rel = relative(realBase, real).split(/[\\/]/u).join('/')
139
- if (rel.startsWith('..') || isAbsolute(rel)) {
140
- throw new Error(`Refusing to follow symlink escaping bundle root: ${relPath} -> ${real}`)
141
- }
107
+ // Compiled/prebuilt artifacts, non-deterministic across installs, so the native capture skips them
108
+ // entirely. Matched on a file OR directory name (an Apple `*.framework`/`*.xcodeproj` bundle dir).
109
+ const NATIVE_ARTIFACT_EXTS = new Set([
110
+ 'a', 'so', 'o', 'obj', 'dylib', 'lib', 'dll', 'exe', 'pdb',
111
+ 'aar', 'jar', 'class', 'dex',
112
+ 'node',
113
+ 'framework', 'xcframework', 'dsym',
114
+ 'xcodeproj', 'xcworkspace',
115
+ 'zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', '7z',
116
+ ])
117
+ export function isNativeArtifact(name) {
118
+ return NATIVE_ARTIFACT_EXTS.has(pathExt(name))
142
119
  }
143
120
 
144
- export function assert(condition, msg) {
145
- if (!condition) throw new Error(msg)
121
+ // An extensionless non-UTF-8 file is a compiled tool (Hermes' `hermesc`), never source -- skipped.
122
+ function isExtensionlessBinary(name, content) {
123
+ return pathExt(name) === '' && Buffer.isBuffer(content) && !isUtf8(content)
146
124
  }
147
125
 
148
- export function sortPaths(a, b) {
149
- const [al, bl] = [a.split(sep), b.split(sep)]
150
- while (al.length > 0 && al[0] === bl[0]) {
151
- al.shift()
152
- bl.shift()
153
- }
154
- if (al.length === 0 && bl.length === 0) return 0
126
+ // A binary plist is a real build input, but its bytes can't ride the text-only 'xml' format
127
+ // classifyFormat gives a `.plist`. Callers treat it as NOT code, so it needs `.plist` in `resources`.
128
+ export function isBinaryPlist(name, content) {
129
+ return pathExt(name) === 'plist' && Buffer.isBuffer(content) && !isUtf8(content)
130
+ }
155
131
 
156
- // First process each file in dir, then subdirs
157
- if (al.length < 2) return bl.length < 2 && al > bl ? 1 : -1
158
- if (bl.length < 2) return 1
132
+ // Discovered by name: RN scatters podspecs in subdirs `react-native config` misses.
133
+ export function isPodspec(name) {
134
+ return name.endsWith('.podspec') || name.endsWith('.podspec.json')
135
+ }
159
136
 
160
- // * comes first
161
- if (al[0] === '*') return -1
162
- if (bl[0] === '*') return 1
137
+ // Non-JS code formats by extension. Every value must be in KNOWN_FORMATS.
138
+ const CODE_EXT_FORMATS = new Map([
139
+ ['sol', 'solidity'],
140
+ ['php', 'php'],
141
+ ['sh', 'shell'], ['bash', 'shell'],
142
+ ['rs', 'rust'],
143
+ ['patch', 'patch'],
144
+ ['java', 'java'],
145
+ ['kt', 'kotlin'], ['kts', 'kotlin'],
146
+ ['gradle', 'gradle'],
147
+ ['m', 'objc'],
148
+ ['mm', 'objcpp'],
149
+ ['swift', 'swift'],
150
+ ['c', 'c'],
151
+ ['cc', 'cpp'], ['cxx', 'cpp'], ['cpp', 'cpp'], ['c++', 'cpp'],
152
+ ['h', 'c-header'],
153
+ ['hh', 'cpp-header'], ['hxx', 'cpp-header'], ['hpp', 'cpp-header'], ['h++', 'cpp-header'],
154
+ ['rb', 'ruby'],
155
+ ['py', 'python'], ['pyi', 'python'], ['pyw', 'python'],
156
+ ['cmake', 'cmake'],
157
+ ['podspec', 'podspec'],
158
+ ['template', 'template'],
159
+ ['xml', 'xml'], ['plist', 'xml'], ['xcprivacy', 'xml'], ['xcscheme', 'xml'],
160
+ ['storyboard', 'xml'], ['entitlements', 'xml'], ['xcworkspacedata', 'xml'],
161
+ ['env', 'env'],
162
+ ['pbxproj', 'pbxproj'],
163
+ ])
163
164
 
164
- // node_modules comes last
165
- if (al[0] === 'node_modules') return 1
166
- if (bl[0] === 'node_modules') return -1
165
+ // Code formats by exact (lowercased) basename, for names whose extension is too generic to key
166
+ // (Podfile.lock's `.lock`, CMakeLists.txt's `.txt`).
167
+ const CODE_NAME_FORMATS = new Map([
168
+ ['podfile', 'podfile'],
169
+ ['podfile.lock', 'podfile-lock'],
170
+ ['cmakelists.txt', 'cmake'],
171
+ ['gradlew', 'shell'],
172
+ ['appfile', 'fastlane'],
173
+ ['fastfile', 'fastlane'],
174
+ ['apple-app-site-association', 'json'],
175
+ ])
167
176
 
168
- // Prefer example/ over example-something/
169
- const [an, bn] = [al, bl].map((list) => list.join(String.fromCodePoint(0)))
170
- if (an < bn) return -1
171
- if (an > bn) return 1
172
- throw new Error('Unreachable')
177
+ const SHELL_SHEBANG = /^#![^\n]*\b(?:bash|sh)\b/u
178
+ function isShellShebang(content) {
179
+ if (!Buffer.isBuffer(content) || !isUtf8(content)) return false
180
+ const head = content.subarray(0, 256).toString('utf8')
181
+ const nl = head.indexOf('\n')
182
+ return SHELL_SHEBANG.test(nl === -1 ? head : head.slice(0, nl))
173
183
  }
174
184
 
175
- export const isPlainObject = (x) => x && [null, Object.prototype].includes(Object.getPrototypeOf(x))
176
-
177
- export const fromEntries = (entries) => Object.setPrototypeOf(Object.fromEntries(entries), null)
185
+ // Files a native package ships that are NOT build inputs (docs/legal, editor/lint/CI config, logs,
186
+ // sidecars), excluded from the Metro native capture. `flow` covers the `*.js.flow` sidecars.
187
+ const NATIVE_EXCLUDE_EXTS = new Set(['md', 'log', 'map', 'flow', 'swiftdoc'])
188
+ const NATIVE_EXCLUDE_NAMES = new Set([
189
+ 'license', 'licence', 'third-party-licenses',
190
+ '.prettierrc', '.prettierignore', '.prettierrc.js', '.gitattributes', '.flowconfig', '.eslintignore',
191
+ '.releaserc', '.clang-format', '.buckconfig', '.watchmanconfig', '.editorconfig', 'circle.yml', '.swiftlint.yml',
192
+ 'documentation.yml', // documentation.js config
193
+ 'yarn.lock',
194
+ '.project', // Eclipse IDE metadata
195
+ 'gradle-wrapper.properties', // the APP's wrapper drives the build, not a module's own
196
+ ])
197
+ export function isExcludedNativeFile(name, { win32 = process.platform === 'win32' } = {}) {
198
+ if (NATIVE_EXCLUDE_NAMES.has(basename(name).toLowerCase())) return true
199
+ const ext = pathExt(name)
200
+ return NATIVE_EXCLUDE_EXTS.has(ext) || (!win32 && ext === 'bat')
201
+ }
178
202
 
179
- export const fileSetToObject = (set) => [...set].toSorted((a, b) => sortPaths(a, b))
203
+ export function isExcludedNativeDir(name, { win32 = process.platform === 'win32' } = {}) {
204
+ return !win32 && name === 'windows'
205
+ }
180
206
 
181
- export const fileMapToObject = (map) => fromEntries(
182
- [...map]
183
- .toSorted((a, b) => sortPaths(a[0], b[0]))
184
- .map(([k, v]) => [k, v instanceof Map ? fileMapToObject(v) : v])
207
+ // An Apple prebuilt-slice dir (`ios-arm64`, `tvos-arm64_x86_64-simulator`): compiled output, not source,
208
+ // at ANY depth. The PLATFORM segment is deliberately loose -- the required ARCH segment is the precision.
209
+ const APPLE_ARCH = String.raw`(?:arm64e|arm64_32|arm64|armv7k|armv7s|armv7|x86_64|i386)`
210
+ const APPLE_SLICE_DIR = new RegExp(
211
+ String.raw`^[a-z0-9]+-${APPLE_ARCH}(?:_${APPLE_ARCH})*(?:-(?:simulator|maccatalyst))?$`,
212
+ 'u'
185
213
  )
214
+ export function isAppleSliceDir(name) {
215
+ return APPLE_SLICE_DIR.test(name)
216
+ }
186
217
 
187
- export const objectToMaps = (obj) => new Map(
188
- Object.entries(obj).map(([k, v]) => [k, isPlainObject(v) ? objectToMaps(v) : v])
189
- )
218
+ // Types only, never a runtime module: the resolvers must refuse to land on one and fall through to the
219
+ // real `.js`. Keyed by compound suffix -- pathExt only sees the trailing `ts`.
220
+ const TYPE_DECLARATION_SUFFIXES = ['.d.ts', '.d.mts', '.d.cts']
221
+ export function isTypeDeclaration(name) {
222
+ const base = basename(name).toLowerCase()
223
+ return TYPE_DECLARATION_SUFFIXES.some((suffix) => base.endsWith(suffix))
224
+ }
225
+
226
+ export function stripTypeDeclaration(name) {
227
+ const lower = name.toLowerCase()
228
+ const suffix = TYPE_DECLARATION_SUFFIXES.find((s) => lower.endsWith(s))
229
+ return suffix === undefined ? name : name.slice(0, -suffix.length)
230
+ }
231
+
232
+ // stasis's own outputs (`stasis.lock.json`, a `*stasis*.br`): absent on a first run but present on a
233
+ // later one, so a listing (`--fs` readdir) or a sweep (`add .`) that records one diverges between runs
234
+ // and the later capture conflicts.
235
+ export function isStasisArtifactName(name) {
236
+ const base = basename(name).toLowerCase()
237
+ return base === 'stasis.lock.json' || (base.includes('stasis') && base.endsWith('.br'))
238
+ }
239
+
240
+ // Dirs no walk descends into: VCS/CI/IDE metadata, sample apps, test scaffolding -- none of it is the
241
+ // code being shipped -- plus the Apple prebuilt slice dirs. `name` is a BARE dir name (a dirent name
242
+ // or path segment), matched at any depth, so every walk agrees on what "not source" means.
243
+ const AUTO_EXCLUDED_DIRS = new Set([
244
+ '.git', '.github', '.settings', // VCS / CI / IDE metadata
245
+ 'example', 'examples', // sample apps -- they import the package, they aren't it
246
+ '__tests__', '__mocks__', 'jest', // test scaffolding
247
+ ])
248
+ export function isAutoExcludedDir(name) {
249
+ const base = name.toLowerCase()
250
+ return AUTO_EXCLUDED_DIRS.has(base) || isAppleSliceDir(base)
251
+ }
252
+
253
+ // Dirs the NATIVE walks (Metro plugin + the static --metro bundler) skip, on top of the shared set:
254
+ // nested packages (attested separately) and regenerated build output -- none is a build input.
255
+ const NATIVE_BUILD_OUTPUT_DIRS = new Set(['node_modules', 'build', '.gradle', '.cxx', 'Pods', 'DerivedData'])
256
+ export function isSkippedNativeWalkDir(name) {
257
+ return NATIVE_BUILD_OUTPUT_DIRS.has(name) || isAutoExcludedDir(name) || isNativeArtifact(name)
258
+ }
259
+
260
+ // Files a sweep drops: type declarations (types only, erased at runtime), the `.env` family (secrets),
261
+ // stasis's own outputs (they'd attest themselves), and everything the native capture excludes as
262
+ // non-build-input noise (docs/legal, editor/lint/CI config, `*.map`/`*.js.flow` sidecars, logs).
263
+ // A path can only reach this via a glob -- an EXPLICITLY named one is added as asked (`add .env` still
264
+ // captures), which is also the only way to attest a file this set covers.
265
+ export function isAutoExcludedFile(name) {
266
+ return isTypeDeclaration(name) || isDotEnvFile(name) || isStasisArtifactName(name) || isExcludedNativeFile(name)
267
+ }
268
+
269
+ // The single name->format classifier every capture path is a policy view of. Returns a concrete format
270
+ // when the name determines one; null for a JS-family file (.js/.ts/.jsx/.tsx); undefined if unrecognized.
271
+ export function classifyFormat(name, { content } = {}) {
272
+ const base = basename(name).toLowerCase()
273
+ // Before the extension rules, so a `*.podspec.json` isn't shadowed.
274
+ if (base === 'package.json' || base.endsWith('.podspec.json')) return 'json'
275
+ // Compound suffix: pathExt only sees the trailing `in`.
276
+ if (base.endsWith('.cmake.in')) return 'cmake'
277
+ const byName = CODE_NAME_FORMATS.get(base)
278
+ if (byName !== undefined) return byName
279
+ const ext = pathExt(name)
280
+ if (JS_UNRESOLVED_EXTS.has(ext)) return null
281
+ const byExt = NODE_EXT_FORMATS.get(ext) ?? CODE_EXT_FORMATS.get(ext)
282
+ if (byExt !== undefined) return byExt
283
+ if (ext === '' && isShellShebang(content)) return 'shell'
284
+ return undefined
285
+ }
286
+
287
+ // The Metro native capture's policy view. Returns { action, format }: 'code' (a native build input),
288
+ // 'skip' (excluded noise, or a JS-family file matched BY EXTENSION -- Metro owns those), else 'resource'.
289
+ export function classifyNativeCapture(name, { win32 = process.platform === 'win32', content } = {}) {
290
+ // `.env` files carry secrets: an automated capture must never sweep them in.
291
+ if (isExcludedNativeFile(name, { win32 }) || isDotEnvFile(name)) return { action: 'skip' }
292
+ const base = basename(name).toLowerCase()
293
+ // Name-matched code is always a native build input, even when its tag is a Node format the JS
294
+ // graph would otherwise own.
295
+ if (base === 'package.json' || base.endsWith('.podspec.json')) return { action: 'code', format: 'json' }
296
+ const byName = CODE_NAME_FORMATS.get(base)
297
+ if (byName !== undefined) return { action: 'code', format: byName }
298
+ if (CODE_EXTENSIONS.has(pathExt(name))) return { action: 'skip' }
299
+ const format = classifyFormat(name, { content })
300
+ return format === undefined ? { action: 'resource' } : { action: 'code', format }
301
+ }
302
+
303
+ // The byte-level half of the native classification, refining what classifyNativeCapture derived from the
304
+ // NAME. Both rules only ever demote. A 'resource' carries no format: storage derives base64 from bytes.
305
+ export function refineNativeCapture(classified, name, content, resources = new Set()) {
306
+ if (isExtensionlessBinary(name, content)) return { action: 'skip' }
307
+ if (isBinaryPlist(name, content)) return { action: resources.has('plist') ? 'resource' : 'skip' }
308
+ return classified
309
+ }
310
+
311
+ // Files `pod install` reads while loading podspecs (Ruby helpers, package.json) -- NOT the native
312
+ // source those podspecs compile.
313
+ export function isNativeManifest(name) {
314
+ return isPodspec(name) || pathExt(name) === 'rb' || name === 'package.json'
315
+ }
316
+
317
+ // RN core build scripts the native walk would defer to Metro as `.js`, but Metro never sees them (RN's
318
+ // podspecs invoke them at pod-install). Project-relative, so react-native's `exports` can't hide them.
319
+ export const RN_CORE_INCLUDE_FILES = ['sdks/hermes-engine/utils/replace_hermes_version.js']
320
+
321
+ export const extSetsEqual = (a, b) => a.size === b.size && [...a].every((ext) => b.has(ext))
322
+
323
+ export const EXECUTE_BITS = 0o111
190
324
 
191
- // True when a POSIX, project-relative path escapes the root once normalized:
192
- // a leading `..`, an absolute path, or a mid-path `..` that pops above the
193
- // root (`a/../../x`). Plain `startsWith('..')` only catches the leading case,
194
- // so it's not enough for paths that later get resolved against the root.
195
- export function posixPathEscapes(path) {
196
- const normalized = posix.normalize(path)
197
- return normalized === '..' || normalized.startsWith('../') || posix.isAbsolute(normalized)
198
- }
199
-
200
- export function splitNodeModulesPath(path) {
201
- const marker = 'node_modules/'
202
- const idx = path.lastIndexOf(marker)
203
- if (idx === -1) return null
204
- const after = idx + marker.length
205
- const parts = path.slice(after).split('/')
206
- const pkgLen = parts[0].startsWith('@') ? 2 : 1
207
- if (parts.length <= pkgLen || parts.slice(0, pkgLen).some((p) => !p)) return null
208
- const name = parts.slice(0, pkgLen).join('/')
209
- return { dir: path.slice(0, after) + name, rel: parts.slice(pkgLen).join('/'), name }
325
+ export const isExecutableMode = (stats) => stats.isFile() && (stats.mode & EXECUTE_BITS) !== 0
326
+
327
+ // Tri-state: `undefined` means the mode could NOT be observed (gone mid-run, EACCES, ELOOP, a synthetic
328
+ // bundle entry). Callers must not read that as "not executable" -- failing to look is not evidence.
329
+ export function observeExecutable(abs, host = diskHost) {
330
+ const stats = host.stat(abs)
331
+ return stats === null ? undefined : isExecutableMode(stats)
332
+ }
333
+
334
+ // Boolean view for callers with nothing to refute (recording a fresh set from scratch).
335
+ export const isExecutableFile = (abs, host) => observeExecutable(abs, host) === true
336
+
337
+ // Windows reports no POSIX execute bits, so a capture there records none and must NOT read "no bit" as
338
+ // "the bit was removed" and strip what a POSIX capture attested.
339
+ export const canObserveExecuteBits = ({ win32 = process.platform === 'win32' } = {}) => !win32
340
+
341
+ // Throws on a symlink escaping the bundle root: a crafted `link.sh -> /etc/passwd` must not pull an
342
+ // external file into an attestable bundle. realpath surfaces ENOENT, which loaders treat as "missing".
343
+ export function assertRealPathWithinBase(realBase, baseDir, relPath, host = diskHost) {
344
+ const real = host.realpath(join(baseDir, relPath))
345
+ if (!isPathWithin(realBase, real)) {
346
+ throw new Error(`Refusing to follow symlink escaping bundle root: ${relPath} -> ${real}`)
347
+ }
210
348
  }