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

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,111 +1,21 @@
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
8
  import { isAbsolute, relative, 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, 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.)
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.
109
19
  const realReaddirSync = fs.readdirSync
110
20
  const realLstatSync = fs.lstatSync
111
21
  const realStatSync = fs.statSync
@@ -114,11 +24,7 @@ const realRealpathSyncNative = fs.realpathSync.native
114
24
  const realExistsSync = fs.existsSync
115
25
  const realAccessSync = fs.accessSync
116
26
 
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.
27
+ // Async counterparts, snapshotted for `--fs=async`. fs.promises IS node:fs/promises (same object).
122
28
  const realReadFile = fs.readFile
123
29
  const realReaddir = fs.readdir
124
30
  const realLstat = fs.lstat
@@ -128,49 +34,33 @@ const realReaddirP = fs.promises.readdir
128
34
  const realLstatP = fs.promises.lstat
129
35
  const realStatP = fs.promises.stat
130
36
 
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.
37
+ // The legacy callback fs.exists is deliberately NOT reassigned (wrapping would clobber its
38
+ // util.promisify.custom); it still answers via the patched fs.access.
138
39
  const realAccess = fs.access
139
40
  const realAccessP = fs.promises.access
140
41
  const realRealpath = fs.realpath
141
42
  const realRealpathNative = fs.realpath.native
142
43
  const realRealpathP = fs.promises.realpath
143
44
 
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.
45
+ // The bundle serves read-only, so only an F_OK/R_OK-only mode may be answered from it; allowlist form
46
+ // so a W_OK/X_OK or out-of-range mode defers to the real fs.
151
47
  const READ_ACCESS = fs.constants.F_OK | fs.constants.R_OK
152
48
  const isReadOnlyAccessMode = (mode) => ((mode | 0) & ~READ_ACCESS) === 0
153
49
 
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.
50
+ // Resolve a path argument to an absolute path, or null for what we don't capture (fd, non-file URL).
159
51
  function toAbsPath(path) {
160
52
  if (typeof path === 'string') return resolve(path)
161
53
  if (Buffer.isBuffer(path)) return resolve(path.toString())
162
54
  if (path instanceof URL) return path.protocol === 'file:' ? fileURLToPath(path) : null
163
- return null // integer fd or unknown
55
+ return null
164
56
  }
165
57
 
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.
58
+ // True when `abs` is the project root or lives beneath it -- lexical only (see realContained).
168
59
  function withinRoot(root, abs) {
169
60
  const rel = relative(root, abs)
170
61
  return !rel.startsWith('..') && !isAbsolute(rel)
171
62
  }
172
63
 
173
- // Memoized real path of the project root, for the symlink-containment check below.
174
64
  let realRootCache
175
65
  function realRootOf(root) {
176
66
  if (realRootCache?.root !== root) {
@@ -181,13 +71,8 @@ function realRootOf(root) {
181
71
  return realRootCache.real
182
72
  }
183
73
 
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).
74
+ // Capture-side containment: the path's REAL location must stay inside root's real path, else an
75
+ // in-tree symlink pointing OUT would pull external content into the signed bundle.
191
76
  function realContained(root, abs) {
192
77
  let real
193
78
  try { real = realRealpathSync(abs) } catch { return false }
@@ -195,50 +80,28 @@ function realContained(root, abs) {
195
80
  return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
196
81
  }
197
82
 
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.
83
+ // At the project root, drop stasis's own artifacts from the RECORDED listing so it doesn't depend on
84
+ // whether an earlier run left them behind; the program still receives the true on-disk `names`.
85
+ function dirCaptureNames(root, abs, names) {
86
+ if (relative(root, abs) !== '') return names
87
+ return names.filter((name) => !isStasisArtifactName(name))
88
+ }
89
+
90
+ // Apply readFileSync's encoding arg to raw bytes; Buffer.toString matches fs's ERR_UNKNOWN_ENCODING.
203
91
  function decode(buf, options) {
204
92
  const encoding = typeof options === 'string' ? options : options?.encoding
205
93
  if (encoding == null) return buf
206
94
  return buf.toString(encoding)
207
95
  }
208
96
 
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.
97
+ // Honour realpath's `encoding` arg for the synthetic answer when a bundle-served path is gone from disk.
212
98
  function encodeRealpath(abs, options) {
213
99
  const encoding = typeof options === 'string' ? options : options?.encoding
214
100
  return encoding === 'buffer' ? Buffer.from(abs) : abs
215
101
  }
216
102
 
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.
103
+ // Source-map sidecars (`*.map`) are NON-EXISTENT under --fs (faithful ENOENT in both modes, so a
104
+ // captured build replays byte-identically). Opt out via `map` in resources, or bundle membership.
242
105
  function isSkippedSourceMap(state, abs) {
243
106
  if (!abs.toLowerCase().endsWith('.map')) return false
244
107
  if (state.config.resources?.has('map')) return false
@@ -246,9 +109,19 @@ function isSkippedSourceMap(state, abs) {
246
109
  return true
247
110
  }
248
111
 
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.
112
+ // `.env`/`.env.*` are NON-EXISTENT under --fs so an automated capture can never bake a secret in. No
113
+ // resources opt-in: the ONE way one serves at load is membership (an explicit `stasis add .env`).
114
+ function isSkippedEnvFile(state, abs) {
115
+ if (!isDotEnvFile(abs)) return false
116
+ if (state.config.loadBundle && state.getFsStatFamily(pathToFileURL(abs).toString()) !== undefined) return false
117
+ return true
118
+ }
119
+
120
+ function isSkippedFsPath(state, abs) {
121
+ return isSkippedSourceMap(state, abs) || isSkippedEnvFile(state, abs)
122
+ }
123
+
124
+ // A faithful Node-shaped ENOENT, indistinguishable from a real absent file.
252
125
  function enoent(syscall, path) {
253
126
  const p = typeof path === 'string' ? path : Buffer.isBuffer(path) ? path.toString() : String(path)
254
127
  const err = new Error(`ENOENT: no such file or directory, ${syscall} '${p}'`)
@@ -259,19 +132,12 @@ function enoent(syscall, path) {
259
132
  return err
260
133
  }
261
134
 
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.
135
+ // File-type bits, so code reading stats.mode (not the is*() methods) still sees file-vs-dir.
264
136
  const S_IFREG = 0o100000
265
137
  const S_IFDIR = 0o040000
266
138
 
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.
139
+ // Neutral fs.Stats-shaped record for a bundle-served path gone from disk; never throws, so wrappers
140
+ // reading uid/gid etc. keep working.
275
141
  function syntheticStat(isDir) {
276
142
  const epoch = new Date(0)
277
143
  return {
@@ -284,32 +150,16 @@ function syntheticStat(isDir) {
284
150
  }
285
151
  }
286
152
 
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.
153
+ // A Stats-like Proxy for a bundle-served path: isFile()/isDirectory() answer from the bundle, other
154
+ // members from the REAL stat while on disk, else syntheticStat. `then` is short-circuited so a
155
+ // bundle-served Stats is never an accidental (rejecting) thenable under `await`.
306
156
  function bundleStats(realStatFn, statPath, isDir) {
307
- let data // real fs.Stats, or the synthetic fallback -- resolved once, on demand
157
+ let data
308
158
  const overrides = { isFile: () => !isDir, isDirectory: () => isDir }
309
159
  return new Proxy(overrides, {
310
160
  get(target, prop) {
311
161
  if (prop === 'isFile' || prop === 'isDirectory') return target[prop]
312
- if (prop === 'then') return undefined // never an (accidentally rejecting) thenable
162
+ if (prop === 'then') return undefined
313
163
  if (data === undefined) {
314
164
  try { data = realStatFn(statPath) } catch { data = syntheticStat(isDir) }
315
165
  }
@@ -322,7 +172,7 @@ function bundleStats(realStatFn, statPath, isDir) {
322
172
  let installed = false
323
173
 
324
174
  export function installFsHooks({ async: patchAsync, getState, markAborted, isLoadingModule }) {
325
- if (installed) return // idempotent: install() is the sole caller, but guard anyway
175
+ if (installed) return
326
176
  installed = true
327
177
 
328
178
  fs.readFileSync = function readFileSync(path, options) {
@@ -330,30 +180,15 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
330
180
  if (state) {
331
181
  const abs = toAbsPath(path)
332
182
  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)
183
+ if (isSkippedFsPath(state, abs)) throw enoent('open', path)
336
184
  const url = pathToFileURL(abs).toString()
337
185
  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
186
  const buf = state.getFsFileFamily(url)
342
187
  if (buf !== undefined) return decode(buf, options)
343
188
  } 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
189
  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.
190
+ // A path whose real location escapes root (in-tree symlink) is read but NOT recorded, and
191
+ // neither is a read a bundler-plugin sidecar already attests.
357
192
  if (realContained(state.root, abs) && !state.attestedBySidecar(url)) {
358
193
  try { state.addFsFile(url, buf) } catch (err) { markAborted(err) }
359
194
  }
@@ -366,8 +201,7 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
366
201
 
367
202
  fs.readdirSync = function readdirSync(path, options) {
368
203
  const state = getState()
369
- // Single-argument form only: any options (encoding/withFileTypes/recursive)
370
- // are out of scope and pass straight through.
204
+ // Single-argument form only; any options pass straight through.
371
205
  if (state && options == null) {
372
206
  const abs = toAbsPath(path)
373
207
  if (abs !== null && withinRoot(state.root, abs)) {
@@ -376,14 +210,10 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
376
210
  const names = state.getFsDirFamily(url)
377
211
  if (names !== undefined) return names // sorted at capture time
378
212
  } 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.
213
+ const names = realReaddirSync(path)
214
+ // As in readFileSync: a dir whose real path escapes root is not recorded.
385
215
  if (realContained(state.root, abs)) {
386
- try { state.addFsDir(url, names) } catch (err) { markAborted(err) }
216
+ try { state.addFsDir(url, dirCaptureNames(state.root, abs, names)) } catch (err) { markAborted(err) }
387
217
  }
388
218
  return names
389
219
  }
@@ -392,61 +222,65 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
392
222
  return realReaddirSync(path, options)
393
223
  }
394
224
 
225
+ // Shared capture-side stat recording: record the path's KIND as a payload-free stat record so a
226
+ // stat-ONLY path's type getters answer at load. Only file and dir are modelled.
227
+ const captureStat = (state, abs, stats) => {
228
+ const isDir = stats.isDirectory()
229
+ if (!isDir && !stats.isFile()) return
230
+ const url = pathToFileURL(abs).toString()
231
+ if (!realContained(state.root, abs) || state.attestedBySidecar(url)) return
232
+ try { state.addFsStat(url, isDir ? 'directory' : 'file') } catch (err) { markAborted(err) }
233
+ }
234
+
395
235
  fs.lstatSync = function lstatSync(path, options) {
396
236
  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.
237
+ // Single-arg form only; capture still hands the caller the REAL Stats/errors.
400
238
  if (state && options == null) {
401
239
  const abs = toAbsPath(path)
402
240
  if (abs !== null && withinRoot(state.root, abs)) {
403
- if (isSkippedSourceMap(state, abs)) throw enoent('lstat', path)
241
+ if (isSkippedFsPath(state, abs)) throw enoent('lstat', path)
404
242
  if (state.config.loadBundle) {
405
243
  const kind = state.getFsStatFamily(pathToFileURL(abs).toString())
406
244
  if (kind !== undefined) return bundleStats(realLstatSync, path, kind === 'directory')
245
+ } else if (state.config.writeBundle && !isLoadingModule()) {
246
+ const stats = realLstatSync(path)
247
+ captureStat(state, abs, stats)
248
+ return stats
407
249
  }
408
250
  }
409
251
  }
410
252
  return realLstatSync(path, options)
411
253
  }
412
254
 
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.
255
+ // Mirrors lstatSync but follows symlinks, so it must use the real statSync: an in-root symlink
256
+ // records the TARGET's kind here, nothing under lstatSync.
417
257
  fs.statSync = function statSync(path, options) {
418
258
  const state = getState()
419
259
  if (state && options == null) {
420
260
  const abs = toAbsPath(path)
421
261
  if (abs !== null && withinRoot(state.root, abs)) {
422
- if (isSkippedSourceMap(state, abs)) throw enoent('stat', path)
262
+ if (isSkippedFsPath(state, abs)) throw enoent('stat', path)
423
263
  if (state.config.loadBundle) {
424
264
  const kind = state.getFsStatFamily(pathToFileURL(abs).toString())
425
265
  if (kind !== undefined) return bundleStats(realStatSync, path, kind === 'directory')
266
+ } else if (state.config.writeBundle && !isLoadingModule()) {
267
+ const stats = realStatSync(path)
268
+ captureStat(state, abs, stats)
269
+ return stats
426
270
  }
427
271
  }
428
272
  }
429
273
  return realStatSync(path, options)
430
274
  }
431
275
 
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.
276
+ // existsSync/accessSync/realpathSync: existence + canonical-path PROBES, serve-only (bundle=load) --
277
+ // a tool may probe before reading bytes (@babel/core does); capture mode and unrecorded paths defer.
444
278
  fs.existsSync = function existsSync(path) {
445
279
  const state = getState()
446
280
  if (state) {
447
281
  const abs = toAbsPath(path)
448
282
  if (abs !== null && withinRoot(state.root, abs)) {
449
- if (isSkippedSourceMap(state, abs)) return false
283
+ if (isSkippedFsPath(state, abs)) return false
450
284
  if (state.config.loadBundle && state.getFsStatFamily(pathToFileURL(abs).toString()) !== undefined) return true
451
285
  }
452
286
  }
@@ -458,11 +292,7 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
458
292
  if (state) {
459
293
  const abs = toAbsPath(path)
460
294
  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.
295
+ if (isSkippedFsPath(state, abs)) throw enoent('access', path)
466
296
  if (state.config.loadBundle && isReadOnlyAccessMode(mode) &&
467
297
  state.getFsStatFamily(pathToFileURL(abs).toString()) !== undefined) {
468
298
  return undefined
@@ -472,16 +302,14 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
472
302
  return realAccessSync(path, mode)
473
303
  }
474
304
 
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.
305
+ // Try the real realpath first (true symlink resolution while on disk), fall back to the lexical abs
306
+ // once gone (ancestor symlinks not re-resolved then).
479
307
  const servedRealpathSync = (realFn) => function realpathSync(path, options) {
480
308
  const state = getState()
481
309
  if (state) {
482
310
  const abs = toAbsPath(path)
483
311
  if (abs !== null && withinRoot(state.root, abs)) {
484
- if (isSkippedSourceMap(state, abs)) throw enoent('realpath', path)
312
+ if (isSkippedFsPath(state, abs)) throw enoent('realpath', path)
485
313
  if (state.config.loadBundle && state.getFsStatFamily(pathToFileURL(abs).toString()) !== undefined) {
486
314
  try { return realFn(path, options) } catch { return encodeRealpath(abs, options) }
487
315
  }
@@ -492,35 +320,24 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
492
320
  fs.realpathSync = servedRealpathSync(realRealpathSync)
493
321
  fs.realpathSync.native = servedRealpathSync(realRealpathSyncNative)
494
322
 
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.
323
+ // --fs=async counterparts; a served callback is deferred (queueMicrotask) to preserve fs's
324
+ // always-async contract.
501
325
  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.
326
+ // Classify a path as the sync readers do: 'serve', 'capture', 'absent', or null (pass through).
505
327
  const fsTarget = (path) => {
506
328
  const state = getState()
507
329
  if (!state) return null
508
330
  const abs = toAbsPath(path)
509
331
  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 }
332
+ if (isSkippedFsPath(state, abs)) return { mode: 'absent', abs }
513
333
  const url = pathToFileURL(abs).toString()
514
334
  if (state.config.loadBundle) return { mode: 'serve', state, url, abs }
515
335
  if (state.config.writeBundle && !isLoadingModule()) return { mode: 'capture', state, url, abs }
516
336
  return null
517
337
  }
518
338
 
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.
339
+ // Route a decode error to the callback (as fs.readFile does); a throw from a deferred callback
340
+ // would escape as an uncaught exception and crash the process.
524
341
  const decodeToCb = (cb, buf, options) => {
525
342
  let out
526
343
  try { out = decode(buf, options) } catch (err) { cb(err); return }
@@ -538,7 +355,6 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
538
355
  } else if (t?.mode === 'capture') {
539
356
  realReadFile(path, (err, buf) => {
540
357
  if (err) return cb(err)
541
- // Skip what a sidecar already attests (see readFileSync); record only the rest.
542
358
  if (realContained(t.state.root, t.abs) && !t.state.attestedBySidecar(t.url)) { try { t.state.addFsFile(t.url, buf) } catch (e) { markAborted(e) } }
543
359
  decodeToCb(cb, buf, opts)
544
360
  })
@@ -555,20 +371,16 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
555
371
  if (buf !== undefined) return decode(buf, options)
556
372
  } else if (t?.mode === 'capture') {
557
373
  const buf = await realReadFileP(path)
558
- // Skip what a sidecar already attests (see readFileSync); record only the rest.
559
374
  if (realContained(t.state.root, t.abs) && !t.state.attestedBySidecar(t.url)) { try { t.state.addFsFile(t.url, buf) } catch (e) { markAborted(e) } }
560
375
  return decode(buf, options)
561
376
  }
562
377
  return realReadFileP(path, options)
563
378
  }
564
379
 
565
- // Single-argument form only (options === the callback / undefined), like readdirSync.
566
380
  fs.readdir = function readdir(path, options, callback) {
567
381
  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).
382
+ // Single-arg form only, and a null options must count as "no options" (graceful-fs normalises to
383
+ // that), else its reads never hit the bundle.
572
384
  const t = ((options == null || typeof options === 'function') && typeof cb === 'function') ? fsTarget(path) : null
573
385
  if (t?.mode === 'serve') {
574
386
  const names = t.state.getFsDirFamily(t.url)
@@ -576,7 +388,7 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
576
388
  } else if (t?.mode === 'capture') {
577
389
  realReaddir(path, (err, names) => {
578
390
  if (err) return cb(err)
579
- if (realContained(t.state.root, t.abs)) { try { t.state.addFsDir(t.url, names) } catch (e) { markAborted(e) } }
391
+ if (realContained(t.state.root, t.abs)) { try { t.state.addFsDir(t.url, dirCaptureNames(t.state.root, t.abs, names)) } catch (e) { markAborted(e) } }
580
392
  cb(null, names)
581
393
  })
582
394
  return
@@ -591,40 +403,45 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
591
403
  if (names !== undefined) return names
592
404
  } else if (t?.mode === 'capture') {
593
405
  const names = await realReaddirP(path)
594
- if (realContained(t.state.root, t.abs)) { try { t.state.addFsDir(t.url, names) } catch (e) { markAborted(e) } }
406
+ if (realContained(t.state.root, t.abs)) { try { t.state.addFsDir(t.url, dirCaptureNames(t.state.root, t.abs, names)) } catch (e) { markAborted(e) } }
595
407
  return names
596
408
  }
597
409
  return realReaddirP(path, options)
598
410
  }
599
411
 
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.
412
+ // lstat/stat mirror their sync siblings; bundleStats's field fallback stays sync.
602
413
  fs.lstat = function lstat(path, options, callback) {
603
414
  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
415
  const t = ((options == null || typeof options === 'function') && typeof cb === 'function') ? fsTarget(path) : null
609
416
  if (t?.mode === 'absent') { queueMicrotask(() => cb(enoent('lstat', path))); return }
610
417
  if (t?.mode === 'serve') {
611
418
  const kind = t.state.getFsStatFamily(t.url)
612
419
  if (kind !== undefined) { queueMicrotask(() => cb(null, bundleStats(realLstatSync, path, kind === 'directory'))); return }
420
+ } else if (t?.mode === 'capture') {
421
+ realLstat(path, (err, stats) => {
422
+ if (err) return cb(err)
423
+ captureStat(t.state, t.abs, stats)
424
+ cb(null, stats)
425
+ })
426
+ return
613
427
  }
614
428
  return realLstat(path, options, callback)
615
429
  }
616
430
 
617
431
  fs.stat = function stat(path, options, callback) {
618
432
  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
433
  const t = ((options == null || typeof options === 'function') && typeof cb === 'function') ? fsTarget(path) : null
624
434
  if (t?.mode === 'absent') { queueMicrotask(() => cb(enoent('stat', path))); return }
625
435
  if (t?.mode === 'serve') {
626
436
  const kind = t.state.getFsStatFamily(t.url)
627
437
  if (kind !== undefined) { queueMicrotask(() => cb(null, bundleStats(realStatSync, path, kind === 'directory'))); return }
438
+ } else if (t?.mode === 'capture') {
439
+ realStat(path, (err, stats) => {
440
+ if (err) return cb(err)
441
+ captureStat(t.state, t.abs, stats)
442
+ cb(null, stats)
443
+ })
444
+ return
628
445
  }
629
446
  return realStat(path, options, callback)
630
447
  }
@@ -635,6 +452,10 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
635
452
  if (t?.mode === 'serve') {
636
453
  const kind = t.state.getFsStatFamily(t.url)
637
454
  if (kind !== undefined) return bundleStats(realLstatSync, path, kind === 'directory')
455
+ } else if (t?.mode === 'capture') {
456
+ const stats = await realLstatP(path)
457
+ captureStat(t.state, t.abs, stats)
458
+ return stats
638
459
  }
639
460
  return realLstatP(path, options)
640
461
  }
@@ -645,16 +466,16 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
645
466
  if (t?.mode === 'serve') {
646
467
  const kind = t.state.getFsStatFamily(t.url)
647
468
  if (kind !== undefined) return bundleStats(realStatSync, path, kind === 'directory')
469
+ } else if (t?.mode === 'capture') {
470
+ const stats = await realStatP(path)
471
+ captureStat(t.state, t.abs, stats)
472
+ return stats
648
473
  }
649
474
  return realStatP(path, options)
650
475
  }
651
476
 
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
477
  fs.access = function access(path, mode, callback) {
656
478
  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
479
  const accessMode = typeof mode === 'function' ? undefined : mode
659
480
  const t = typeof cb === 'function' ? fsTarget(path) : null
660
481
  if (t?.mode === 'absent') { queueMicrotask(() => cb(enoent('access', path))); return }
@@ -667,7 +488,6 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
667
488
  fs.promises.access = async function access(path, mode) {
668
489
  const t = fsTarget(path)
669
490
  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
491
  if (t?.mode === 'serve' && isReadOnlyAccessMode(mode) && t.state.getFsStatFamily(t.url) !== undefined) return undefined
672
492
  return realAccessP(path, mode)
673
493
  }
@@ -678,7 +498,6 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
678
498
  const t = typeof cb === 'function' ? fsTarget(path) : null
679
499
  if (t?.mode === 'absent') { queueMicrotask(() => cb(enoent('realpath', path))); return }
680
500
  if (t?.mode === 'serve' && t.state.getFsStatFamily(t.url) !== undefined) {
681
- // Real first (symlink resolution while present); lexically-resolved abs once gone.
682
501
  realFn(path, opts, (err, resolved) => (err ? cb(null, encodeRealpath(t.abs, opts)) : cb(null, resolved)))
683
502
  return
684
503
  }
@@ -697,16 +516,7 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
697
516
  }
698
517
  }
699
518
 
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.
519
+ // Refresh the node:fs (+ node:fs/promises) ESM wrappers so user-code live imports see the patched fns.
520
+ // INVARIANT: a stasis module needing the real fs must snapshot it (`const { ... } = fs`), never live-import.
711
521
  syncBuiltinESMExports()
712
522
  }