@exodus/stasis-core 1.0.0-beta.0 → 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/fs.js CHANGED
@@ -1,176 +1,45 @@
1
- // `stasis run --fs=sync|async` (EXODUS_STASIS_FS, or "fs" in stasis.config.json): monkey-patch
2
- // the filesystem readers
3
- // fs.readFileSync, fs.readdirSync, fs.lstatSync, fs.statSync so that, alongside the
4
- // module graph the loader hooks already capture, a program's explicit file/directory
5
- // reads are recorded into the bundle (bundle=add|replace) and served back from it
6
- // (bundle=load). Alongside the readers, the existence/canonical-path PROBES existsSync /
7
- // accessSync / realpathSync are served (load mode) so a tool that checks a file before
8
- // reading it finds a bundle-only file -- see the existsSync/accessSync/realpathSync bullet.
9
- //
10
- // MODE:
11
- // - `=sync` patches only the sync readers above (the default; `--fs` bare == sync).
12
- // - `=async` additionally patches their async counterparts -- the callback forms
13
- // fs.readFile/readdir/lstat/stat and the promise forms fs.promises.* (the latter
14
- // IS node:fs/promises, the same object, so syncBuiltinESMExports() covers ESM
15
- // `import ... from 'node:fs/promises'` too). Each async wrapper shares the exact
16
- // capture/serve logic of its sync sibling; only the I/O plumbing differs. The async
17
- // probe forms (fs.access / fs.realpath and the fs.promises.* forms) are added here too.
18
- //
19
- // SCOPE, deliberately narrow:
20
- // - The four readers above, plus the existence/canonical-path probes existsSync /
21
- // accessSync / realpathSync (and, under =async, fs.access / fs.realpath and the
22
- // fs.promises forms). Other fs (fs.opendir, streams, fs.cp, watchers, the deprecated
23
- // callback fs.exists, ...) is NOT touched, in either mode. Notably fs.readlink is left
24
- // unserved: enhanced-resolve probes it per path-segment but treats a read error as
25
- // "not a symlink" and continues, so an absent recorded file still resolves correctly --
26
- // leaving it unserved costs nothing for the absent-config case (same ancestor-symlink
27
- // limitation as realpathSync's lexical fallback below).
28
- // - readdirSync: only the single-argument form `readdirSync(path)`. Any options
29
- // (encoding, withFileTypes, recursive) fall through untouched -- Dirent objects
30
- // and recursive listings aren't modelled.
31
- // - readFileSync: the optional second argument (an `encoding` string, or an
32
- // options object with `encoding`) is honoured; the raw bytes are what we
33
- // capture/serve and `encoding` is applied on the way out.
34
- // - lstatSync / statSync: serve-only, bundle=load, single-argument form. For a
35
- // recorded path they return a Stats-like object whose isFile()/isDirectory() come
36
- // from the bundle (the common existence check); every other member is the real
37
- // stat while the file is still on disk, and a benign synthetic default (0 / epoch
38
- // / file-or-dir mode) once it's gone -- so fs wrappers that read more than
39
- // isFile()/isDirectory() (graceful-fs reads stats.uid/gid) keep working under
40
- // bundle=load instead of re-throwing ENOENT. Not patched in capture mode (the file
41
- // is on disk there, so the real Stats is correct), except to report a skipped
42
- // source-map sidecar as absent (next bullet). statSync vs lstatSync differ only in
43
- // symlink following, which matters solely for that on-disk passthrough -- each falls
44
- // back to its own real implementation.
45
- // - existsSync / accessSync / realpathSync (+ their async/promise forms under =async):
46
- // existence/canonical-path PROBES, serve-only and bundle=load only. A path the bundle
47
- // records answers existent / accessible (read-only: F_OK/R_OK, while W_OK/X_OK defer) /
48
- // its-path even once it's gone from disk; an
49
- // unrecorded path (and all of capture mode, where the file is on disk) defers to the
50
- // real call. This is what lets a tool that gates file loading on a SEPARATE existence
51
- // check find a file whose bytes live only in the bundle, instead of forcing an on-disk
52
- // stub: @babel/core, for one, guards config loading with fs.existsSync(babel.config.js)
53
- // (and realpath-canonicalizes the path) BEFORE it require()s the file -- so without
54
- // serving the probe, a bundled-but-absent babel.config.js reads as missing and Babel
55
- // silently runs with no config (an empty on-disk babel.config.js "works" only because
56
- // its existence passes the probe; its bytes are then served from the bundle by the
57
- // module loader). Because these are serve-only (never captured), a file that is ONLY
58
- // existence-probed -- never read or imported -- isn't recorded, so its probe falls
59
- // through to disk on load; babel.config.js is fine because it is also require()d, hence
60
- // recorded. realpathSync returns the real (symlink-resolved) path while the file is on
61
- // disk, and falls back to the LEXICALLY-resolved request path once it's bundle-only (a
62
- // symlink in a surviving ancestor dir is not re-resolved -- moot for the absent-config
63
- // case, but a canonicalize-then-compare under a symlinked ancestor could diverge between
64
- // capture and load). Its `.native` variant is covered too.
65
- // - Source-map sidecars (`*.map`): build-time debug artifacts that never affect a
66
- // program's output, yet tools read them unconditionally -- regardless of any
67
- // "sourcemaps off" setting (e.g. @babel/core's normalizeFile reads a file's sibling
68
- // `.js.map` to chain an INPUT source map no matter the bundler's devtool, and skips
69
- // it when absent). Under --fs every in-root `*.map` is therefore treated as
70
- // NON-EXISTENT -- never captured, never served, ENOENT to the reader -- in BOTH
71
- // capture and load (returning ENOENT at capture too is what keeps a captured build
72
- // byte-identical to a hermetic replay). Opt in by adding `map` to the resources
73
- // allowlist; then it's captured/served like any other declared resource.
74
- // - Only paths inside the project root -- whose REAL path (symlinks resolved)
75
- // also stays inside the root -- are captured/served; anything else (a system
76
- // path, a symlink escaping the root, an fd, a non-file URL) falls through to
77
- // the real call and is NOT attested.
78
- //
79
- // Mechanism mirrors the @exodus/stasis tooling package's src/mock.js: reach the
80
- // mutable CJS `node:fs` object through createRequire, snapshot the real functions
81
- // at module-eval time (BEFORE install() patches anything, so stasis's own snapshots
82
- // and these stay real), then on install replace the readers and
83
- // syncBuiltinESMExports() so user code's later ESM `import { readFileSync } from
84
- // 'node:fs'` sees the patched binding too. (Unlike mock.js it assigns directly
85
- // rather than via node:test's MockTracker -- no test-time restore is needed.) State
86
- // is read lazily per call (it's created when the entry loads), and decode/lookup
87
- // reuse State's getFs* / addFs* methods.
1
+ // `stasis run --fs=sync|async`: monkey-patch the fs readers (readFileSync/readdirSync/lstat/stat
2
+ // + existence/realpath probes; under =async their callback + fs.promises counterparts) to capture a
3
+ // program's explicit reads into the bundle (bundle=add|replace) or serve them from it (bundle=load).
4
+ // SECURITY INVARIANT: only paths whose REAL path (symlinks resolved) stays inside the project root are
5
+ // captured/served; anything else falls through to the real fs and is never attested.
88
6
 
89
7
  import { createRequire, syncBuiltinESMExports } from 'node:module'
90
- import { isAbsolute, relative, resolve } from 'node:path'
8
+ import { resolve } from 'node:path'
91
9
  import { fileURLToPath, pathToFileURL } from 'node:url'
92
10
 
93
- // The genuine sync source reader (snapshotted before any --fs patch). Lives in
94
- // state-util.js so there's a single source of truth shared with the bundler plugins;
95
- // see that module for why it must not be a patched `node:fs` named import.
96
11
  import { realReadFileSync } from './state-util.js'
12
+ import { isDotEnvFile, isPathWithin, isStasisArtifactName } from './util.js'
97
13
 
98
14
  const require = createRequire(import.meta.url)
99
15
  const fs = require('node:fs')
100
16
 
101
- // Snapshot the real functions now, while they're still the genuine builtins. The
102
- // hooks below call THESE (never the patched `fs.*`), so there is no recursion,
103
- // capture always sees real bytes, and the patched lstatSync/statSync/realpathSync fall
104
- // back to the real impls here. realRealpathSync also backs realRootOf/realContained, whose
105
- // containment checks must stay on the genuine builtin even after realpathSync is patched.
106
- // (The sync source reader, realReadFileSync, is imported from state-util.js above -- the
107
- // single source of truth shared with the bundler plugins; only the dir/stat/realpath
108
- // readers are snapshotted here, since only the --fs hook needs them.)
109
- const realReaddirSync = fs.readdirSync
110
- const realLstatSync = fs.lstatSync
111
- const realStatSync = fs.statSync
112
- const realRealpathSync = fs.realpathSync
113
- const realRealpathSyncNative = fs.realpathSync.native
114
- const realExistsSync = fs.existsSync
115
- const realAccessSync = fs.accessSync
116
-
117
- // Async counterparts, snapshotted for `--fs=async`. Callback forms off `fs`, promise
118
- // forms off `fs.promises` (which IS node:fs/promises -- same object, so patching it +
119
- // syncBuiltinESMExports() also covers `import ... from 'node:fs/promises'`). The
120
- // bundleStats shim still falls back to the SYNC real stat (a Stats field read is
121
- // synchronous), so no async stat snapshot is needed.
122
- const realReadFile = fs.readFile
123
- const realReaddir = fs.readdir
124
- const realLstat = fs.lstat
125
- const realStat = fs.stat
126
- const realReadFileP = fs.promises.readFile
127
- const realReaddirP = fs.promises.readdir
128
- const realLstatP = fs.promises.lstat
129
- const realStatP = fs.promises.stat
130
-
131
- // Async access/realpath probe counterparts, snapshotted for `--fs=async`. The legacy callback
132
- // fs.exists is deliberately not REASSIGNED (it's deprecated, and wrapping it would clobber its
133
- // util.promisify.custom) -- but note it STILL answers from the bundle under --fs=async, because
134
- // Node implements fs.exists by delegating to the (now-patched) fs.access; under --fs=sync it
135
- // falls through to disk like every other async API. That's the desirable direction (consistent
136
- // with existsSync), so leaving it unwrapped is fine. There is no fs.promises.exists. realpath's
137
- // `.native` variant is snapshotted too.
138
- const realAccess = fs.access
139
- const realAccessP = fs.promises.access
140
- const realRealpath = fs.realpath
141
- const realRealpathNative = fs.realpath.native
142
- const realRealpathP = fs.promises.realpath
143
-
144
- // True iff an access() mode requests ONLY read-class bits (existence F_OK / readable R_OK) --
145
- // nothing implying mutation or execution. The bundle serves files read-only, so only such a
146
- // request is answered from it; a W_OK/X_OK request is deferred to the real fs (which gives the
147
- // truthful answer: ENOENT for a bundle-only file, real perms for an on-disk one). Phrased as an
148
- // allowlist -- "no bits outside READ_ACCESS" -- rather than a `& (W_OK|X_OK) === 0` denylist, so
149
- // an out-of-range/garbage mode (e.g. 8) also defers to the real fs and gets its faithful
150
- // ERR_OUT_OF_RANGE instead of slipping through. `| 0` coerces the default `undefined` to F_OK.
17
+ // Snapshot the real fns while still genuine builtins; the hooks call THESE, never patched `fs.*`, so
18
+ // there's no recursion and capture/containment always see real bytes/paths. fs.promises IS
19
+ // node:fs/promises (same object). The legacy callback fs.exists is deliberately NOT reassigned
20
+ // (wrapping would clobber its util.promisify.custom); it still answers via the patched fs.access.
21
+ const {
22
+ readdirSync: realReaddirSync, lstatSync: realLstatSync, statSync: realStatSync, realpathSync: realRealpathSync,
23
+ existsSync: realExistsSync, accessSync: realAccessSync,
24
+ readFile: realReadFile, readdir: realReaddir, lstat: realLstat, stat: realStat, access: realAccess, realpath: realRealpath,
25
+ } = fs
26
+ const { readFile: realReadFileP, readdir: realReaddirP, lstat: realLstatP, stat: realStatP, access: realAccessP, realpath: realRealpathP } = fs.promises
27
+ const realRealpathSyncNative = realRealpathSync.native
28
+ const realRealpathNative = realRealpath.native
29
+
30
+ // The bundle serves read-only, so only an F_OK/R_OK-only mode may be answered from it; allowlist form
31
+ // so a W_OK/X_OK or out-of-range mode defers to the real fs.
151
32
  const READ_ACCESS = fs.constants.F_OK | fs.constants.R_OK
152
33
  const isReadOnlyAccessMode = (mode) => ((mode | 0) & ~READ_ACCESS) === 0
153
34
 
154
- // Resolve a path argument to an absolute filesystem path, or null when it's
155
- // something we don't capture (an integer fd, or a non-file URL). Strings/Buffers
156
- // are resolved against cwd exactly like fs does; a trailing slash on a directory is
157
- // dropped by resolve(), keeping the file: URL we build in agreement with State's
158
- // pathToFileURL round-trip.
35
+ // Resolve a path argument to an absolute path, or null for what we don't capture (fd, non-file URL).
159
36
  function toAbsPath(path) {
160
37
  if (typeof path === 'string') return resolve(path)
161
38
  if (Buffer.isBuffer(path)) return resolve(path.toString())
162
39
  if (path instanceof URL) return path.protocol === 'file:' ? fileURLToPath(path) : null
163
- return null // integer fd or unknown
40
+ return null
164
41
  }
165
42
 
166
- // True when `abs` is the project root or lives beneath it. Out-of-root reads (system
167
- // files, parent escapes) are left entirely to the real implementation.
168
- function withinRoot(root, abs) {
169
- const rel = relative(root, abs)
170
- return !rel.startsWith('..') && !isAbsolute(rel)
171
- }
172
-
173
- // Memoized real path of the project root, for the symlink-containment check below.
174
43
  let realRootCache
175
44
  function realRootOf(root) {
176
45
  if (realRootCache?.root !== root) {
@@ -181,97 +50,54 @@ function realRootOf(root) {
181
50
  return realRootCache.real
182
51
  }
183
52
 
184
- // Capture-side containment: the path's REAL location (all symlinks resolved) must
185
- // stay inside the project root's real path. `withinRoot` is lexical only, so a
186
- // symlink inside the tree pointing OUT (`src/peek -> /etc`) would otherwise be read
187
- // and its bytes/listing attested as if in-root -- pulling external content into the
188
- // closed, signed bundle. An escaping (or vanished) path returns false: the hook
189
- // then leaves it to the real fs and records nothing. Only used while capturing; the
190
- // path exists (we just read it).
53
+ // Capture-side containment: the path's REAL location must stay inside root's real path, else an
54
+ // in-tree symlink pointing OUT would pull external content into the signed bundle.
191
55
  function realContained(root, abs) {
192
56
  let real
193
57
  try { real = realRealpathSync(abs) } catch { return false }
194
- const rel = relative(realRootOf(root), real)
195
- return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
58
+ return isPathWithin(realRootOf(root), real)
196
59
  }
197
60
 
198
- // Apply readFileSync's second argument to raw bytes: a string encoding, or an
199
- // options object's `encoding`. No encoding yields the Buffer; anything else is
200
- // handed to Buffer.toString, which decodes a known encoding and throws
201
- // ERR_UNKNOWN_ENCODING for an unknown one -- matching fs's contract, including
202
- // that an invalid encoding like 'buffer' throws rather than returning the Buffer.
61
+ // At the project root, drop stasis's own artifacts from the RECORDED listing so it doesn't depend on
62
+ // whether an earlier run left them behind; the program still receives the true on-disk `names`.
63
+ function dirCaptureNames(root, abs, names) {
64
+ if (!isPathWithin(abs, root)) return names
65
+ return names.filter((name) => !isStasisArtifactName(name))
66
+ }
67
+
68
+ // Apply readFileSync's encoding arg to raw bytes; Buffer.toString matches fs's ERR_UNKNOWN_ENCODING.
203
69
  function decode(buf, options) {
204
70
  const encoding = typeof options === 'string' ? options : options?.encoding
205
- if (encoding == null) return buf
206
- return buf.toString(encoding)
71
+ return encoding == null ? buf : buf.toString(encoding)
207
72
  }
208
73
 
209
- // realpathSync/realpath honour an `encoding` arg exactly like fs: 'buffer' yields a Buffer,
210
- // anything else (incl. the default 'utf8') a string. Used for the synthetic answer returned
211
- // when a bundle-served path is gone from disk -- the real realpath would ENOENT there.
74
+ // Honour realpath's `encoding` arg for the synthetic answer when a bundle-served path is gone from disk.
212
75
  function encodeRealpath(abs, options) {
213
76
  const encoding = typeof options === 'string' ? options : options?.encoding
214
77
  return encoding === 'buffer' ? Buffer.from(abs) : abs
215
78
  }
216
79
 
217
- // Source-map sidecars (`*.map`) are build-time debug artifacts that never affect a
218
- // program's emitted output, yet tools read them opportunistically and INDEPENDENTLY of
219
- // any "sourcemaps off" setting -- @babel/core's normalizeFile, for one, reads a
220
- // transformed file's sibling `.js.map` to chain an INPUT source map no matter the
221
- // bundler's devtool, and simply skips it (try/catch) when the file is absent. Under --fs
222
- // we therefore treat such a map as NON-EXISTENT: never captured (so a stray map read
223
- // can't abort a capture or bloat the lockfile/bundle) and never served, handing the
224
- // reader a faithful ENOENT in BOTH capture and load. Returning ENOENT at CAPTURE too --
225
- // not just load -- keeps a captured build byte-identical to a hermetic replay.
226
- //
227
- // NOT gated on bundle mode: --fs capture writes the lockfile (hashes, via addFile) as
228
- // well as the bundle, so the skip must be identical whether or not a bundle is written
229
- // -- lockfile attestation can't depend on bundle mode. (The hook only runs under --fs,
230
- // which always has a bundle mode, so no explicit mode check is needed.)
231
- //
232
- // Two opt-outs keep this from hiding a map a user genuinely wants:
233
- // - `map` in the resources allowlist -> captured + served as a normal resource
234
- // (classifyExtension tags `.map` 'resource' once `map` is allowed).
235
- // - at load, a map the bundle actually CARRIES is served regardless of the load run's
236
- // resources flag -- bundle membership wins, exactly like every other recorded
237
- // resource, so a map captured under `--resources=map` still loads even if the load
238
- // run forgets the flag (getFsStatFamily returns undefined for a map that was skipped, so the
239
- // common "never captured" case still falls through to the ENOENT below).
240
- // Uses getFsStatFamily, matching the serve paths: a map a bundler-plugin sidecar carries
241
- // counts as carried by the family, not just by main.
242
- function isSkippedSourceMap(state, abs) {
243
- if (!abs.toLowerCase().endsWith('.map')) return false
244
- if (state.config.resources?.has('map')) return false
245
- if (state.config.loadBundle && state.getFsStatFamily(pathToFileURL(abs).toString()) !== undefined) return false
246
- return true
80
+ // NON-EXISTENT under --fs (a faithful ENOENT from every reader, listings included, in both modes):
81
+ // source-map sidecars (`*.map`, so a captured build replays byte-identically; opt out via `map` in
82
+ // resources) and `.env`/`.env.*` (an automated capture can never bake a secret in; no opt-in). The
83
+ // ONE way either serves at load is bundle membership (an explicit `stasis add .env`).
84
+ function isSkippedFsPath(state, abs) {
85
+ const skipped = (abs.toLowerCase().endsWith('.map') && !state.config.resources?.has('map')) || isDotEnvFile(abs)
86
+ return skipped && !(state.config.loadBundle && state.getFsStatFamily(pathToFileURL(abs).toString()) !== undefined)
247
87
  }
248
88
 
249
- // A faithful Node-shaped ENOENT, so a skipped source map is indistinguishable from a
250
- // genuinely absent file to the caller (code/errno/syscall/path all set, exactly what a
251
- // real failed open/stat throws). Callers like @babel/core catch it and carry on.
89
+ // A faithful Node-shaped ENOENT, indistinguishable from a real absent file.
252
90
  function enoent(syscall, path) {
253
91
  const p = typeof path === 'string' ? path : Buffer.isBuffer(path) ? path.toString() : String(path)
254
- const err = new Error(`ENOENT: no such file or directory, ${syscall} '${p}'`)
255
- err.code = 'ENOENT'
256
- err.errno = -2
257
- err.syscall = syscall
258
- err.path = p
259
- return err
92
+ return Object.assign(new Error(`ENOENT: no such file or directory, ${syscall} '${p}'`), { code: 'ENOENT', errno: -2, syscall, path: p })
260
93
  }
261
94
 
262
- // File-type bits, so code that derives the kind from stats.mode (rather than the
263
- // is*() methods) still sees file-vs-directory for an absent bundle-served path.
95
+ // File-type bits, so code reading stats.mode (not the is*() methods) still sees file-vs-dir.
264
96
  const S_IFREG = 0o100000
265
97
  const S_IFDIR = 0o040000
266
98
 
267
- // Benign fs.Stats-shaped record for a recorded path whose bytes are served from the
268
- // bundle but is GONE from disk. isFile/isDirectory come from the bundle; the rest are
269
- // neutral defaults (zeros, epoch Dates, file/dir mode bits) -- never a throw. This is
270
- // what lets fs wrappers that read more than isFile()/isDirectory() off the returned
271
- // Stats keep working under bundle=load: graceful-fs's statFixSync, for instance,
272
- // reads stats.uid/gid, which would otherwise re-trigger the very ENOENT the bundle
273
- // exists to paper over. The other is*() are false -- the shim models only files and
274
- // directories.
99
+ // Neutral fs.Stats-shaped record for a bundle-served path gone from disk; never throws, so wrappers
100
+ // reading uid/gid etc. keep working.
275
101
  function syntheticStat(isDir) {
276
102
  const epoch = new Date(0)
277
103
  return {
@@ -284,32 +110,16 @@ function syntheticStat(isDir) {
284
110
  }
285
111
  }
286
112
 
287
- // A Stats-like object for a bundle-served path (bundle=load). isFile()/isDirectory()
288
- // always answer from the bundle's record (the point of the shim -- available even
289
- // when the file is absent from disk). Every other member comes from the REAL stat
290
- // while the file is still on disk (faithful metadata); once it's gone -- the
291
- // bundle-load case -- realStatFn throws and we fall back to syntheticStat's benign
292
- // defaults instead of forwarding the ENOENT. Built as a Proxy so this covers the
293
- // full Stats surface (methods AND numeric/Date fields) without enumerating it.
294
- //
295
- // `then` is short-circuited to undefined: a real fs.Stats is never thenable, but the
296
- // lazy resolution would otherwise forward the `then` probe that `await`/Promise
297
- // resolution performs to realStatFn -- which THROWS for an absent file, making a
298
- // bundle-served Stats an accidental rejecting thenable (`await lstatSync(x)` would
299
- // reject with ENOENT for exactly the absent-from-disk case the shim exists to serve).
300
- // Returning undefined keeps it non-thenable in both the present and absent cases.
301
- //
302
- // Read-only: there is no `set` trap, so a write to a field (a wrapper normalising
303
- // e.g. stats.uid) lands on the override target, not on `data`, and isn't reflected
304
- // back on read. No real consumer needs mutate-then-read here -- graceful-fs only
305
- // writes uid/gid when they're < 0, which the synthetic 0 (and modern Node) never hit.
113
+ // A Stats-like Proxy for a bundle-served path: isFile()/isDirectory() answer from the bundle, other
114
+ // members from the REAL stat while on disk, else syntheticStat. `then` is short-circuited so a
115
+ // bundle-served Stats is never an accidental (rejecting) thenable under `await`.
306
116
  function bundleStats(realStatFn, statPath, isDir) {
307
- let data // real fs.Stats, or the synthetic fallback -- resolved once, on demand
117
+ let data
308
118
  const overrides = { isFile: () => !isDir, isDirectory: () => isDir }
309
119
  return new Proxy(overrides, {
310
120
  get(target, prop) {
311
121
  if (prop === 'isFile' || prop === 'isDirectory') return target[prop]
312
- if (prop === 'then') return undefined // never an (accidentally rejecting) thenable
122
+ if (prop === 'then') return undefined
313
123
  if (data === undefined) {
314
124
  try { data = realStatFn(statPath) } catch { data = syntheticStat(isDir) }
315
125
  }
@@ -322,205 +132,129 @@ function bundleStats(realStatFn, statPath, isDir) {
322
132
  let installed = false
323
133
 
324
134
  export function installFsHooks({ async: patchAsync, getState, markAborted, isLoadingModule }) {
325
- if (installed) return // idempotent: install() is the sole caller, but guard anyway
135
+ if (installed) return
326
136
  installed = true
327
137
 
328
- fs.readFileSync = function readFileSync(path, options) {
138
+ // Classify a path for every hook: null passes through to the real fs; else { mode, abs, url, state }
139
+ // with mode 'absent' (a skipped path: ENOENT), 'serve' (bundle=load; an uncaptured path still falls
140
+ // through to disk) or 'capture' (bundle=add|replace, outside a loader read).
141
+ const classify = (path) => {
329
142
  const state = getState()
330
- if (state) {
331
- const abs = toAbsPath(path)
332
- if (abs !== null && withinRoot(state.root, abs)) {
333
- // Source-map sidecars are absent in both modes (see isSkippedSourceMap) -- before
334
- // any serve/capture so a `.js.map` is neither read from the bundle nor recorded.
335
- if (isSkippedSourceMap(state, abs)) throw enoent('open', path)
336
- const url = pathToFileURL(abs).toString()
337
- if (state.config.loadBundle) {
338
- // Serve the captured bytes (consulting sidecar bundles too -- a bundler-plugin
339
- // sidecar may carry it). A path no family bundle recorded (or one recorded as a
340
- // directory) returns undefined and falls back to disk.
341
- const buf = state.getFsFileFamily(url)
342
- if (buf !== undefined) return decode(buf, options)
343
- } else if (state.config.writeBundle && !isLoadingModule()) {
344
- // (Skip while Node's loader is reading a module's source -- that's captured
345
- // as code by the load hook, not a program fs read.) Read once via the real
346
- // reader (faithful errors on the user's original path), record, and hand
347
- // the user the same bytes. A capture conflict (the file read twice with
348
- // diverging bytes) taints the run so nothing inconsistent is written; the
349
- // user's read still succeeds. A path whose real location escapes the root
350
- // (in-tree symlink) is read but NOT recorded -- its content isn't in-bundle
351
- // and must not be attested.
352
- const buf = realReadFileSync(path)
353
- // Skip a read a bundler-plugin sidecar already attests (the module graph webpack
354
- // reads through inputFileSystem) -- recording it here would duplicate the graph
355
- // into this (main) bundle. Reads no sidecar owns (the plugin's manual non-JS
356
- // file reads, etc.) ARE recorded here.
357
- if (realContained(state.root, abs) && !state.attestedBySidecar(url)) {
358
- try { state.addFsFile(url, buf) } catch (err) { markAborted(err) }
359
- }
360
- return decode(buf, options)
361
- }
362
- }
143
+ if (!state) return null
144
+ const abs = toAbsPath(path)
145
+ if (abs === null || !isPathWithin(state.root, abs)) return null
146
+ if (isSkippedFsPath(state, abs)) return { mode: 'absent', abs }
147
+ const url = pathToFileURL(abs).toString()
148
+ if (state.config.loadBundle) return { mode: 'serve', state, url, abs }
149
+ if (state.config.writeBundle && !isLoadingModule()) return { mode: 'capture', state, url, abs }
150
+ return null
151
+ }
152
+ // A path the bundle knows (content, listing, stat record or implied dir), for the serve-only probes.
153
+ const served = (t) => t?.mode === 'serve' && t.state.getFsStatFamily(t.url) !== undefined
154
+
155
+ // Capture-side records; a rejected capture taints the run (markAborted) rather than failing the read.
156
+ const record = (fn) => { try { fn() } catch (err) { markAborted(err) } }
157
+ // A path whose real location escapes root (in-tree symlink) is read but NOT recorded, and neither is
158
+ // a read a bundler-plugin sidecar already attests.
159
+ const captureFile = ({ state, abs, url }, buf) => {
160
+ if (realContained(state.root, abs) && !state.attestedBySidecar(url)) record(() => state.addFsFile(url, buf))
161
+ }
162
+ const captureDir = ({ state, abs, url }, names) => {
163
+ if (realContained(state.root, abs)) record(() => state.addFsDir(url, dirCaptureNames(state.root, abs, names)))
164
+ }
165
+ // A stat records the path's KIND as a payload-free record so a stat-ONLY path's type getters answer
166
+ // at load. Only file and dir are modelled.
167
+ const captureStat = ({ state, abs, url }, stats) => {
168
+ const isDir = stats.isDirectory()
169
+ if (!isDir && !stats.isFile()) return
170
+ if (realContained(state.root, abs) && !state.attestedBySidecar(url)) record(() => state.addFsStat(url, isDir ? 'directory' : 'file'))
171
+ }
172
+
173
+ fs.readFileSync = function readFileSync(path, options) {
174
+ const t = classify(path)
175
+ if (t?.mode === 'absent') throw enoent('open', path)
176
+ if (t?.mode === 'serve') {
177
+ const buf = t.state.getFsFileFamily(t.url)
178
+ if (buf !== undefined) return decode(buf, options)
179
+ } else if (t?.mode === 'capture') {
180
+ const buf = realReadFileSync(path)
181
+ captureFile(t, buf)
182
+ return decode(buf, options)
363
183
  }
364
184
  return realReadFileSync(path, options)
365
185
  }
366
186
 
367
187
  fs.readdirSync = function readdirSync(path, options) {
368
- const state = getState()
369
- // Single-argument form only: any options (encoding/withFileTypes/recursive)
370
- // are out of scope and pass straight through.
371
- if (state && options == null) {
372
- const abs = toAbsPath(path)
373
- if (abs !== null && withinRoot(state.root, abs)) {
374
- const url = pathToFileURL(abs).toString()
375
- if (state.config.loadBundle) {
376
- const names = state.getFsDirFamily(url)
377
- if (names !== undefined) return names // sorted at capture time
378
- } else if (state.config.writeBundle && !isLoadingModule()) {
379
- // (Node's loader doesn't readdir to load a module, but skip during a load
380
- // window anyway, symmetric with readFileSync.)
381
- const names = realReaddirSync(path) // string[] (single-arg)
382
- // As in readFileSync: skip recording a directory whose real path escapes
383
- // the root (an in-tree symlink to outside), so an external listing is
384
- // never baked into the bundle/lockfile.
385
- if (realContained(state.root, abs)) {
386
- try { state.addFsDir(url, names) } catch (err) { markAborted(err) }
387
- }
388
- return names
389
- }
390
- }
188
+ const t = classify(path)
189
+ if (t?.mode === 'absent') throw enoent('scandir', path)
190
+ // Served/captured in the single-argument form only; any options pass straight through.
191
+ if (options == null && t?.mode === 'serve') {
192
+ const names = t.state.getFsDirFamily(t.url)
193
+ if (names !== undefined) return names // sorted at capture time
194
+ } else if (options == null && t?.mode === 'capture') {
195
+ const names = realReaddirSync(path)
196
+ captureDir(t, names)
197
+ return names
391
198
  }
392
199
  return realReaddirSync(path, options)
393
200
  }
394
201
 
395
- fs.lstatSync = function lstatSync(path, options) {
396
- const state = getState()
397
- // Serve-only, single-argument form. Capture mode is left to the real lstatSync
398
- // (the file is on disk, so its Stats is correct and complete) -- the lone exception
399
- // being a skipped source-map sidecar, reported absent in both modes.
400
- if (state && options == null) {
401
- const abs = toAbsPath(path)
402
- if (abs !== null && withinRoot(state.root, abs)) {
403
- if (isSkippedSourceMap(state, abs)) throw enoent('lstat', path)
404
- if (state.config.loadBundle) {
405
- const kind = state.getFsStatFamily(pathToFileURL(abs).toString())
406
- if (kind !== undefined) return bundleStats(realLstatSync, path, kind === 'directory')
407
- }
408
- }
409
- }
410
- return realLstatSync(path, options)
411
- }
412
-
413
- // statSync mirrors lstatSync exactly; the only difference is symlink following,
414
- // which is moot for a bundle-served path (there is no link to follow once the
415
- // bytes come from the bundle) but matters for the passthrough/present-on-disk
416
- // case, so it falls back to the real statSync rather than lstatSync.
417
- fs.statSync = function statSync(path, options) {
418
- const state = getState()
419
- if (state && options == null) {
420
- const abs = toAbsPath(path)
421
- if (abs !== null && withinRoot(state.root, abs)) {
422
- if (isSkippedSourceMap(state, abs)) throw enoent('stat', path)
423
- if (state.config.loadBundle) {
424
- const kind = state.getFsStatFamily(pathToFileURL(abs).toString())
425
- if (kind !== undefined) return bundleStats(realStatSync, path, kind === 'directory')
426
- }
202
+ // Single-arg form only; capture still hands the caller the REAL Stats/errors. statSync follows
203
+ // symlinks, so it must use the real statSync: an in-root symlink records the TARGET's kind there.
204
+ const servedStatSync = (syscall, realFn) => ({
205
+ [`${syscall}Sync`](path, options) {
206
+ const t = options == null ? classify(path) : null
207
+ if (t?.mode === 'absent') throw enoent(syscall, path)
208
+ if (t?.mode === 'serve') {
209
+ const kind = t.state.getFsStatFamily(t.url)
210
+ if (kind !== undefined) return bundleStats(realFn, path, kind === 'directory')
211
+ } else if (t?.mode === 'capture') {
212
+ const stats = realFn(path)
213
+ captureStat(t, stats)
214
+ return stats
427
215
  }
428
- }
429
- return realStatSync(path, options)
430
- }
216
+ return realFn(path, options)
217
+ },
218
+ })[`${syscall}Sync`]
219
+ fs.lstatSync = servedStatSync('lstat', realLstatSync)
220
+ fs.statSync = servedStatSync('stat', realStatSync)
431
221
 
432
- // existsSync / accessSync / realpathSync: existence + canonical-path PROBES, distinct
433
- // from the byte readers above. A build tool may check a file's existence (and realpath)
434
- // on a channel that never reads its bytes -- @babel/core guards config loading with
435
- // fs.existsSync(babel.config.js) and canonicalizes the path with realpath BEFORE it
436
- // require()s the file. Under bundle=load the bytes come from the bundle (via the module
437
- // loader, or readFileSync above), but without serving these probes too the file still has
438
- // to exist on disk or the tool concludes it is absent and silently skips it. Serve-only,
439
- // like lstat/stat: a recorded path answers from getFsStatFamily (so a file a bundler-plugin
440
- // sidecar carries answers here too, matching the byte/stat readers -- a check-then-read tool
441
- // sees it); everything else -- and all of capture mode, where the file is on disk -- falls
442
- // through to the real call. A skipped source-map sidecar is reported absent in both modes,
443
- // matching readFileSync/statSync.
222
+ // existsSync/accessSync/realpathSync: existence + canonical-path PROBES, serve-only (bundle=load) --
223
+ // a tool may probe before reading bytes (@babel/core does); capture mode and unrecorded paths defer.
444
224
  fs.existsSync = function existsSync(path) {
445
- const state = getState()
446
- if (state) {
447
- const abs = toAbsPath(path)
448
- if (abs !== null && withinRoot(state.root, abs)) {
449
- if (isSkippedSourceMap(state, abs)) return false
450
- if (state.config.loadBundle && state.getFsStatFamily(pathToFileURL(abs).toString()) !== undefined) return true
451
- }
452
- }
453
- return realExistsSync(path)
225
+ const t = classify(path)
226
+ if (t?.mode === 'absent') return false
227
+ return served(t) || realExistsSync(path)
454
228
  }
455
229
 
456
230
  fs.accessSync = function accessSync(path, mode) {
457
- const state = getState()
458
- if (state) {
459
- const abs = toAbsPath(path)
460
- if (abs !== null && withinRoot(state.root, abs)) {
461
- if (isSkippedSourceMap(state, abs)) throw enoent('access', path)
462
- // The bundle serves files READ-ONLY: a carried path satisfies an existence/read probe
463
- // (F_OK / R_OK -- what build tools check), but a write/exec probe (W_OK / X_OK) is not
464
- // ours to grant, so it falls through to the real fs (which reports a bundle-only,
465
- // absent-on-disk file as not writable). Unrecorded paths and capture mode also defer.
466
- if (state.config.loadBundle && isReadOnlyAccessMode(mode) &&
467
- state.getFsStatFamily(pathToFileURL(abs).toString()) !== undefined) {
468
- return undefined
469
- }
470
- }
471
- }
231
+ const t = classify(path)
232
+ if (t?.mode === 'absent') throw enoent('access', path)
233
+ if (isReadOnlyAccessMode(mode) && served(t)) return undefined
472
234
  return realAccessSync(path, mode)
473
235
  }
474
236
 
475
- // realpathSync carries a `.native` variant (enhanced-resolve and some tools call it);
476
- // both share this serve logic. Try the real realpath first so a path still on disk gets
477
- // true symlink resolution; fall back to the lexically-resolved abs once it's gone
478
- // (bundle-served) -- ancestor symlinks aren't re-resolved in that fallback.
237
+ // Try the real realpath first (true symlink resolution while on disk), fall back to the lexical abs
238
+ // once gone (ancestor symlinks not re-resolved then).
479
239
  const servedRealpathSync = (realFn) => function realpathSync(path, options) {
480
- const state = getState()
481
- if (state) {
482
- const abs = toAbsPath(path)
483
- if (abs !== null && withinRoot(state.root, abs)) {
484
- if (isSkippedSourceMap(state, abs)) throw enoent('realpath', path)
485
- if (state.config.loadBundle && state.getFsStatFamily(pathToFileURL(abs).toString()) !== undefined) {
486
- try { return realFn(path, options) } catch { return encodeRealpath(abs, options) }
487
- }
488
- }
240
+ const t = classify(path)
241
+ if (t?.mode === 'absent') throw enoent('realpath', path)
242
+ if (served(t)) {
243
+ try { return realFn(path, options) } catch { return encodeRealpath(t.abs, options) }
489
244
  }
490
245
  return realFn(path, options)
491
246
  }
492
247
  fs.realpathSync = servedRealpathSync(realRealpathSync)
493
248
  fs.realpathSync.native = servedRealpathSync(realRealpathSyncNative)
494
249
 
495
- // --fs=async: the async counterparts. Each shares its sync sibling's capture/serve
496
- // logic via fsTarget(); only the I/O plumbing (callback / promise) differs. A served
497
- // callback is deferred (queueMicrotask) so a bundle hit never fires it synchronously,
498
- // preserving fs's "the callback is always async" contract. fs.promises.* IS
499
- // node:fs/promises (same object), so syncBuiltinESMExports() below propagates these
500
- // to ESM `import ... from 'node:fs/promises'` as well.
250
+ // --fs=async counterparts; a served callback is deferred (queueMicrotask) to preserve fs's
251
+ // always-async contract.
501
252
  if (patchAsync) {
502
- // Classify a path exactly as the sync readers do: serve from the bundle
503
- // (loadBundle), capture into it (writeBundle, outside a module-load window), or
504
- // pass through (null) for out-of-root / fd / non-file-URL / no-state.
505
- const fsTarget = (path) => {
506
- const state = getState()
507
- if (!state) return null
508
- const abs = toAbsPath(path)
509
- if (abs === null || !withinRoot(state.root, abs)) return null
510
- // Source-map sidecars are absent in both modes (see isSkippedSourceMap); 'absent'
511
- // makes the read/stat wrappers below hand back ENOENT instead of serving/capturing.
512
- if (isSkippedSourceMap(state, abs)) return { mode: 'absent', abs }
513
- const url = pathToFileURL(abs).toString()
514
- if (state.config.loadBundle) return { mode: 'serve', state, url, abs }
515
- if (state.config.writeBundle && !isLoadingModule()) return { mode: 'capture', state, url, abs }
516
- return null
517
- }
518
-
519
- // Decode bytes for a callback reader, routing a decode error (e.g. an invalid
520
- // encoding like 'buffer') to the callback -- exactly as fs.readFile does. Without
521
- // this the throw escapes the deferred/real-reader callback as an UNCAUGHT exception
522
- // and crashes the process (the sync path is fine: there the throw is the caller's
523
- // to catch). The promise readers don't need it -- a throw there rejects the promise.
253
+ // Split a trailing callback from its optional options argument.
254
+ const cbArgs = (options, callback) => (typeof options === 'function' ? [undefined, options] : [options, callback])
255
+ const later = (cb, ...args) => queueMicrotask(() => cb(...args))
256
+ // Route a decode error to the callback (as fs.readFile does); a throw from a deferred callback
257
+ // would escape as an uncaught exception and crash the process.
524
258
  const decodeToCb = (cb, buf, options) => {
525
259
  let out
526
260
  try { out = decode(buf, options) } catch (err) { cb(err); return }
@@ -528,185 +262,145 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
528
262
  }
529
263
 
530
264
  fs.readFile = function readFile(path, options, callback) {
531
- const cb = typeof options === 'function' ? options : callback
532
- const opts = typeof options === 'function' ? undefined : options
533
- const t = typeof cb === 'function' ? fsTarget(path) : null
534
- if (t?.mode === 'absent') { queueMicrotask(() => cb(enoent('open', path))); return }
265
+ const [opts, cb] = cbArgs(options, callback)
266
+ const t = typeof cb === 'function' ? classify(path) : null
267
+ if (t?.mode === 'absent') return later(cb, enoent('open', path))
535
268
  if (t?.mode === 'serve') {
536
269
  const buf = t.state.getFsFileFamily(t.url)
537
- if (buf !== undefined) { queueMicrotask(() => decodeToCb(cb, buf, opts)); return }
270
+ if (buf !== undefined) return later(decodeToCb, cb, buf, opts)
538
271
  } else if (t?.mode === 'capture') {
539
- realReadFile(path, (err, buf) => {
272
+ return realReadFile(path, (err, buf) => {
540
273
  if (err) return cb(err)
541
- // Skip what a sidecar already attests (see readFileSync); record only the rest.
542
- if (realContained(t.state.root, t.abs) && !t.state.attestedBySidecar(t.url)) { try { t.state.addFsFile(t.url, buf) } catch (e) { markAborted(e) } }
274
+ captureFile(t, buf)
543
275
  decodeToCb(cb, buf, opts)
544
276
  })
545
- return
546
277
  }
547
278
  return realReadFile(path, options, callback)
548
279
  }
549
280
 
550
281
  fs.promises.readFile = async function readFile(path, options) {
551
- const t = fsTarget(path)
282
+ const t = classify(path)
552
283
  if (t?.mode === 'absent') throw enoent('open', path)
553
284
  if (t?.mode === 'serve') {
554
285
  const buf = t.state.getFsFileFamily(t.url)
555
286
  if (buf !== undefined) return decode(buf, options)
556
287
  } else if (t?.mode === 'capture') {
557
288
  const buf = await realReadFileP(path)
558
- // Skip what a sidecar already attests (see readFileSync); record only the rest.
559
- if (realContained(t.state.root, t.abs) && !t.state.attestedBySidecar(t.url)) { try { t.state.addFsFile(t.url, buf) } catch (e) { markAborted(e) } }
289
+ captureFile(t, buf)
560
290
  return decode(buf, options)
561
291
  }
562
292
  return realReadFileP(path, options)
563
293
  }
564
294
 
565
- // Single-argument form only (options === the callback / undefined), like readdirSync.
566
295
  fs.readdir = function readdir(path, options, callback) {
567
- const cb = typeof options === 'function' ? options : callback
568
- // "single-argument" form: fn(path, cb) OR fn(path, null/undefined, cb). graceful-fs
569
- // normalises readdir(path, cb) to readdir(path, null, cb), so a null options must
570
- // count as "no options" -- otherwise its reads never hit the bundle (the exact
571
- // gap that made --fs=async fail for enhanced-resolve's async file system).
572
- const t = ((options == null || typeof options === 'function') && typeof cb === 'function') ? fsTarget(path) : null
573
- if (t?.mode === 'serve') {
296
+ const [opts, cb] = cbArgs(options, callback)
297
+ const t = typeof cb === 'function' ? classify(path) : null
298
+ if (t?.mode === 'absent') return later(cb, enoent('scandir', path))
299
+ // Served/captured in the single-arg form only, where a null options must count as "no options"
300
+ // (graceful-fs normalises to that), else its reads never hit the bundle.
301
+ if (opts == null && t?.mode === 'serve') {
574
302
  const names = t.state.getFsDirFamily(t.url)
575
- if (names !== undefined) { queueMicrotask(() => cb(null, names)); return }
576
- } else if (t?.mode === 'capture') {
577
- realReaddir(path, (err, names) => {
303
+ if (names !== undefined) return later(cb, null, names)
304
+ } else if (opts == null && t?.mode === 'capture') {
305
+ return realReaddir(path, (err, names) => {
578
306
  if (err) return cb(err)
579
- if (realContained(t.state.root, t.abs)) { try { t.state.addFsDir(t.url, names) } catch (e) { markAborted(e) } }
307
+ captureDir(t, names)
580
308
  cb(null, names)
581
309
  })
582
- return
583
310
  }
584
311
  return realReaddir(path, options, callback)
585
312
  }
586
313
 
587
314
  fs.promises.readdir = async function readdir(path, options) {
588
- const t = options == null ? fsTarget(path) : null
589
- if (t?.mode === 'serve') {
315
+ const t = classify(path)
316
+ if (t?.mode === 'absent') throw enoent('scandir', path)
317
+ if (options == null && t?.mode === 'serve') {
590
318
  const names = t.state.getFsDirFamily(t.url)
591
319
  if (names !== undefined) return names
592
- } else if (t?.mode === 'capture') {
320
+ } else if (options == null && t?.mode === 'capture') {
593
321
  const names = await realReaddirP(path)
594
- if (realContained(t.state.root, t.abs)) { try { t.state.addFsDir(t.url, names) } catch (e) { markAborted(e) } }
322
+ captureDir(t, names)
595
323
  return names
596
324
  }
597
325
  return realReaddirP(path, options)
598
326
  }
599
327
 
600
- // lstat/stat are serve-only (like their sync siblings); capture is left to the real
601
- // call. bundleStats's field fallback is synchronous, so it uses the sync real stat.
602
- fs.lstat = function lstat(path, options, callback) {
603
- const cb = typeof options === 'function' ? options : callback
604
- // "single-argument" form: fn(path, cb) OR fn(path, null/undefined, cb). graceful-fs
605
- // normalises readdir(path, cb) to readdir(path, null, cb), so a null options must
606
- // count as "no options" -- otherwise its reads never hit the bundle (the exact
607
- // gap that made --fs=async fail for enhanced-resolve's async file system).
608
- const t = ((options == null || typeof options === 'function') && typeof cb === 'function') ? fsTarget(path) : null
609
- if (t?.mode === 'absent') { queueMicrotask(() => cb(enoent('lstat', path))); return }
610
- if (t?.mode === 'serve') {
611
- const kind = t.state.getFsStatFamily(t.url)
612
- if (kind !== undefined) { queueMicrotask(() => cb(null, bundleStats(realLstatSync, path, kind === 'directory'))); return }
613
- }
614
- return realLstat(path, options, callback)
615
- }
616
-
617
- fs.stat = function stat(path, options, callback) {
618
- const cb = typeof options === 'function' ? options : callback
619
- // "single-argument" form: fn(path, cb) OR fn(path, null/undefined, cb). graceful-fs
620
- // normalises readdir(path, cb) to readdir(path, null, cb), so a null options must
621
- // count as "no options" -- otherwise its reads never hit the bundle (the exact
622
- // gap that made --fs=async fail for enhanced-resolve's async file system).
623
- const t = ((options == null || typeof options === 'function') && typeof cb === 'function') ? fsTarget(path) : null
624
- if (t?.mode === 'absent') { queueMicrotask(() => cb(enoent('stat', path))); return }
625
- if (t?.mode === 'serve') {
626
- const kind = t.state.getFsStatFamily(t.url)
627
- if (kind !== undefined) { queueMicrotask(() => cb(null, bundleStats(realStatSync, path, kind === 'directory'))); return }
628
- }
629
- return realStat(path, options, callback)
630
- }
631
-
632
- fs.promises.lstat = async function lstat(path, options) {
633
- const t = options == null ? fsTarget(path) : null
634
- if (t?.mode === 'absent') throw enoent('lstat', path)
635
- if (t?.mode === 'serve') {
636
- const kind = t.state.getFsStatFamily(t.url)
637
- if (kind !== undefined) return bundleStats(realLstatSync, path, kind === 'directory')
638
- }
639
- return realLstatP(path, options)
640
- }
641
-
642
- fs.promises.stat = async function stat(path, options) {
643
- const t = options == null ? fsTarget(path) : null
644
- if (t?.mode === 'absent') throw enoent('stat', path)
645
- if (t?.mode === 'serve') {
646
- const kind = t.state.getFsStatFamily(t.url)
647
- if (kind !== undefined) return bundleStats(realStatSync, path, kind === 'directory')
648
- }
649
- return realStatP(path, options)
650
- }
328
+ // lstat/stat mirror their sync siblings; bundleStats's field fallback stays sync.
329
+ const servedStat = (syscall, realFn, realSyncFn) => ({
330
+ [syscall](path, options, callback) {
331
+ const [opts, cb] = cbArgs(options, callback)
332
+ const t = opts == null && typeof cb === 'function' ? classify(path) : null
333
+ if (t?.mode === 'absent') return later(cb, enoent(syscall, path))
334
+ if (t?.mode === 'serve') {
335
+ const kind = t.state.getFsStatFamily(t.url)
336
+ if (kind !== undefined) return later(cb, null, bundleStats(realSyncFn, path, kind === 'directory'))
337
+ } else if (t?.mode === 'capture') {
338
+ return realFn(path, (err, stats) => {
339
+ if (err) return cb(err)
340
+ captureStat(t, stats)
341
+ cb(null, stats)
342
+ })
343
+ }
344
+ return realFn(path, options, callback)
345
+ },
346
+ })[syscall]
347
+ fs.lstat = servedStat('lstat', realLstat, realLstatSync)
348
+ fs.stat = servedStat('stat', realStat, realStatSync)
349
+
350
+ const servedStatP = (syscall, realFn, realSyncFn) => ({
351
+ async [syscall](path, options) {
352
+ const t = options == null ? classify(path) : null
353
+ if (t?.mode === 'absent') throw enoent(syscall, path)
354
+ if (t?.mode === 'serve') {
355
+ const kind = t.state.getFsStatFamily(t.url)
356
+ if (kind !== undefined) return bundleStats(realSyncFn, path, kind === 'directory')
357
+ } else if (t?.mode === 'capture') {
358
+ const stats = await realFn(path)
359
+ captureStat(t, stats)
360
+ return stats
361
+ }
362
+ return realFn(path, options)
363
+ },
364
+ })[syscall]
365
+ fs.promises.lstat = servedStatP('lstat', realLstatP, realLstatSync)
366
+ fs.promises.stat = servedStatP('stat', realStatP, realStatSync)
651
367
 
652
- // Access + realpath probes, async forms (serve-only, mirroring the sync siblings and
653
- // reusing fsTarget: 'serve' answers from the bundle when the path is recorded, 'absent'
654
- // is a skipped source map, and capture / unrecorded paths fall through to the real call).
655
368
  fs.access = function access(path, mode, callback) {
656
- const cb = typeof mode === 'function' ? mode : callback
657
- // Read-only serve: a W_OK/X_OK probe is deferred to the real fs (see accessSync).
658
- const accessMode = typeof mode === 'function' ? undefined : mode
659
- const t = typeof cb === 'function' ? fsTarget(path) : null
660
- if (t?.mode === 'absent') { queueMicrotask(() => cb(enoent('access', path))); return }
661
- if (t?.mode === 'serve' && isReadOnlyAccessMode(accessMode) && t.state.getFsStatFamily(t.url) !== undefined) {
662
- queueMicrotask(() => cb(null)); return
663
- }
369
+ const [accessMode, cb] = cbArgs(mode, callback)
370
+ const t = typeof cb === 'function' ? classify(path) : null
371
+ if (t?.mode === 'absent') return later(cb, enoent('access', path))
372
+ if (isReadOnlyAccessMode(accessMode) && served(t)) return later(cb, null)
664
373
  return realAccess(path, mode, callback)
665
374
  }
666
375
 
667
376
  fs.promises.access = async function access(path, mode) {
668
- const t = fsTarget(path)
377
+ const t = classify(path)
669
378
  if (t?.mode === 'absent') throw enoent('access', path)
670
- // Read-only serve: a W_OK/X_OK probe is deferred to the real fs (see accessSync).
671
- if (t?.mode === 'serve' && isReadOnlyAccessMode(mode) && t.state.getFsStatFamily(t.url) !== undefined) return undefined
379
+ if (isReadOnlyAccessMode(mode) && served(t)) return undefined
672
380
  return realAccessP(path, mode)
673
381
  }
674
382
 
675
383
  const servedRealpath = (realFn) => function realpath(path, options, callback) {
676
- const cb = typeof options === 'function' ? options : callback
677
- const opts = typeof options === 'function' ? undefined : options
678
- const t = typeof cb === 'function' ? fsTarget(path) : null
679
- if (t?.mode === 'absent') { queueMicrotask(() => cb(enoent('realpath', path))); return }
680
- if (t?.mode === 'serve' && t.state.getFsStatFamily(t.url) !== undefined) {
681
- // Real first (symlink resolution while present); lexically-resolved abs once gone.
682
- realFn(path, opts, (err, resolved) => (err ? cb(null, encodeRealpath(t.abs, opts)) : cb(null, resolved)))
683
- return
684
- }
384
+ const [opts, cb] = cbArgs(options, callback)
385
+ const t = typeof cb === 'function' ? classify(path) : null
386
+ if (t?.mode === 'absent') return later(cb, enoent('realpath', path))
387
+ if (served(t)) return realFn(path, opts, (err, resolved) => cb(null, err ? encodeRealpath(t.abs, opts) : resolved))
685
388
  return realFn(path, options, callback)
686
389
  }
687
390
  fs.realpath = servedRealpath(realRealpath)
688
391
  fs.realpath.native = servedRealpath(realRealpathNative)
689
392
 
690
393
  fs.promises.realpath = async function realpath(path, options) {
691
- const t = fsTarget(path)
394
+ const t = classify(path)
692
395
  if (t?.mode === 'absent') throw enoent('realpath', path)
693
- if (t?.mode === 'serve' && t.state.getFsStatFamily(t.url) !== undefined) {
396
+ if (served(t)) {
694
397
  try { return await realRealpathP(path, options) } catch { return encodeRealpath(t.abs, options) }
695
398
  }
696
399
  return realRealpathP(path, options)
697
400
  }
698
401
  }
699
402
 
700
- // Refresh the node:fs (and node:fs/promises) ESM wrappers so user-code destructured/namespace
701
- // ESM imports resolve to the patched functions. This repoints a LIVE `import { existsSync }
702
- // from 'node:fs'` binding regardless of whether the module evaluated before or after this.
703
- // INVARIANT: stasis's own run-graph modules must stay on the genuine builtin, so the ones in
704
- // the run graph (state.js, state-util.js, util.js) snapshot fs at module-eval via
705
- // `const { ... } = fs` and are immune. The bundler plugins (webpack.js / metro.js) DO use live
706
- // `import { existsSync }`, but they never reach it in load mode (apply()/#run route away from
707
- // the capture path), and capture-mode probes are byte-for-byte transparent; the CLI
708
- // subcommands/loaders/launcher (prune, scan, bundle, extract, the language loaders, the bins)
709
- // run in processes where installFsHooks never fires. A NEW stasis module that needs real fs
710
- // under --fs must snapshot (`const { x } = fs`), not live-import.
403
+ // Refresh the node:fs (+ node:fs/promises) ESM wrappers so user-code live imports see the patched fns.
404
+ // INVARIANT: a stasis module needing the real fs must snapshot it (`const { ... } = fs`), never live-import.
711
405
  syncBuiltinESMExports()
712
406
  }