@secure-exec/core 0.1.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +7 -0
  3. package/dist/bridge/active-handles.d.ts +21 -0
  4. package/dist/bridge/active-handles.js +60 -0
  5. package/dist/bridge/child-process.d.ts +90 -0
  6. package/dist/bridge/child-process.js +606 -0
  7. package/dist/bridge/fs.d.ts +281 -0
  8. package/dist/bridge/fs.js +2151 -0
  9. package/dist/bridge/index.d.ts +10 -0
  10. package/dist/bridge/index.js +41 -0
  11. package/dist/bridge/module.d.ts +75 -0
  12. package/dist/bridge/module.js +308 -0
  13. package/dist/bridge/network.d.ts +249 -0
  14. package/dist/bridge/network.js +1416 -0
  15. package/dist/bridge/os.d.ts +13 -0
  16. package/dist/bridge/os.js +256 -0
  17. package/dist/bridge/polyfills.d.ts +2 -0
  18. package/dist/bridge/polyfills.js +11 -0
  19. package/dist/bridge/process.d.ts +86 -0
  20. package/dist/bridge/process.js +938 -0
  21. package/dist/bridge-setup.d.ts +6 -0
  22. package/dist/bridge-setup.js +9 -0
  23. package/dist/bridge.js +11538 -0
  24. package/dist/esm-compiler.d.ts +14 -0
  25. package/dist/esm-compiler.js +68 -0
  26. package/dist/fs-helpers.d.ts +23 -0
  27. package/dist/fs-helpers.js +41 -0
  28. package/dist/generated/isolate-runtime.d.ts +19 -0
  29. package/dist/generated/isolate-runtime.js +21 -0
  30. package/dist/generated/polyfills.d.ts +82 -0
  31. package/dist/generated/polyfills.js +82 -0
  32. package/dist/index.d.ts +30 -0
  33. package/dist/index.js +25 -0
  34. package/dist/isolate-runtime/apply-custom-global-policy.js +54 -0
  35. package/dist/isolate-runtime/apply-timing-mitigation-freeze.js +44 -0
  36. package/dist/isolate-runtime/apply-timing-mitigation-off.js +14 -0
  37. package/dist/isolate-runtime/bridge-attach.js +29 -0
  38. package/dist/isolate-runtime/bridge-initial-globals.js +246 -0
  39. package/dist/isolate-runtime/eval-script-result.js +8 -0
  40. package/dist/isolate-runtime/global-exposure-helpers.js +36 -0
  41. package/dist/isolate-runtime/init-commonjs-module-globals.js +28 -0
  42. package/dist/isolate-runtime/override-process-cwd.js +8 -0
  43. package/dist/isolate-runtime/override-process-env.js +8 -0
  44. package/dist/isolate-runtime/require-setup.js +650 -0
  45. package/dist/isolate-runtime/set-commonjs-file-globals.js +36 -0
  46. package/dist/isolate-runtime/set-stdin-data.js +10 -0
  47. package/dist/isolate-runtime/setup-dynamic-import.js +64 -0
  48. package/dist/isolate-runtime/setup-fs-facade.js +48 -0
  49. package/dist/module-resolver.d.ts +25 -0
  50. package/dist/module-resolver.js +264 -0
  51. package/dist/package-bundler.d.ts +36 -0
  52. package/dist/package-bundler.js +497 -0
  53. package/dist/python-runtime.d.ts +16 -0
  54. package/dist/python-runtime.js +45 -0
  55. package/dist/runtime-driver.d.ts +62 -0
  56. package/dist/runtime-driver.js +1 -0
  57. package/dist/runtime.d.ts +31 -0
  58. package/dist/runtime.js +69 -0
  59. package/dist/shared/api-types.d.ts +71 -0
  60. package/dist/shared/api-types.js +1 -0
  61. package/dist/shared/bridge-contract.d.ts +302 -0
  62. package/dist/shared/bridge-contract.js +82 -0
  63. package/dist/shared/console-formatter.d.ts +22 -0
  64. package/dist/shared/console-formatter.js +157 -0
  65. package/dist/shared/constants.d.ts +3 -0
  66. package/dist/shared/constants.js +3 -0
  67. package/dist/shared/errors.d.ts +16 -0
  68. package/dist/shared/errors.js +21 -0
  69. package/dist/shared/esm-utils.d.ts +28 -0
  70. package/dist/shared/esm-utils.js +97 -0
  71. package/dist/shared/global-exposure.d.ts +38 -0
  72. package/dist/shared/global-exposure.js +406 -0
  73. package/dist/shared/in-memory-fs.d.ts +42 -0
  74. package/dist/shared/in-memory-fs.js +341 -0
  75. package/dist/shared/permissions.d.ts +38 -0
  76. package/dist/shared/permissions.js +283 -0
  77. package/dist/shared/require-setup.d.ts +6 -0
  78. package/dist/shared/require-setup.js +9 -0
  79. package/dist/types.d.ts +206 -0
  80. package/dist/types.js +1 -0
  81. package/package.json +107 -0
@@ -0,0 +1,2151 @@
1
+ // fs polyfill module for isolated-vm
2
+ // This module runs inside the isolate and provides Node.js fs API compatibility
3
+ // It communicates with the host via the _fs Reference object
4
+ import { Buffer } from "buffer";
5
+ // File descriptor table
6
+ const fdTable = new Map();
7
+ let nextFd = 3;
8
+ const O_RDONLY = 0;
9
+ const O_WRONLY = 1;
10
+ const O_RDWR = 2;
11
+ const O_ACCMODE = 3;
12
+ const O_CREAT = 64;
13
+ const O_EXCL = 128;
14
+ const O_TRUNC = 512;
15
+ const O_APPEND = 1024;
16
+ // Stats class
17
+ class Stats {
18
+ dev;
19
+ ino;
20
+ mode;
21
+ nlink;
22
+ uid;
23
+ gid;
24
+ rdev;
25
+ size;
26
+ blksize;
27
+ blocks;
28
+ atimeMs;
29
+ mtimeMs;
30
+ ctimeMs;
31
+ birthtimeMs;
32
+ atime;
33
+ mtime;
34
+ ctime;
35
+ birthtime;
36
+ constructor(init) {
37
+ this.dev = init.dev ?? 0;
38
+ this.ino = init.ino ?? 0;
39
+ this.mode = init.mode;
40
+ this.nlink = init.nlink ?? 1;
41
+ this.uid = init.uid ?? 0;
42
+ this.gid = init.gid ?? 0;
43
+ this.rdev = init.rdev ?? 0;
44
+ this.size = init.size;
45
+ this.blksize = init.blksize ?? 4096;
46
+ this.blocks = init.blocks ?? Math.ceil(init.size / 512);
47
+ this.atimeMs = init.atimeMs ?? Date.now();
48
+ this.mtimeMs = init.mtimeMs ?? Date.now();
49
+ this.ctimeMs = init.ctimeMs ?? Date.now();
50
+ this.birthtimeMs = init.birthtimeMs ?? Date.now();
51
+ this.atime = new Date(this.atimeMs);
52
+ this.mtime = new Date(this.mtimeMs);
53
+ this.ctime = new Date(this.ctimeMs);
54
+ this.birthtime = new Date(this.birthtimeMs);
55
+ }
56
+ isFile() {
57
+ return (this.mode & 61440) === 32768;
58
+ }
59
+ isDirectory() {
60
+ return (this.mode & 61440) === 16384;
61
+ }
62
+ isSymbolicLink() {
63
+ return (this.mode & 61440) === 40960;
64
+ }
65
+ isBlockDevice() {
66
+ return false;
67
+ }
68
+ isCharacterDevice() {
69
+ return false;
70
+ }
71
+ isFIFO() {
72
+ return false;
73
+ }
74
+ isSocket() {
75
+ return false;
76
+ }
77
+ }
78
+ // Dirent class for readdir with withFileTypes
79
+ class Dirent {
80
+ name;
81
+ parentPath;
82
+ path; // Deprecated alias for parentPath
83
+ _isDir;
84
+ constructor(name, isDir, parentPath = "") {
85
+ this.name = name;
86
+ this._isDir = isDir;
87
+ this.parentPath = parentPath;
88
+ this.path = parentPath;
89
+ }
90
+ isFile() {
91
+ return !this._isDir;
92
+ }
93
+ isDirectory() {
94
+ return this._isDir;
95
+ }
96
+ isSymbolicLink() {
97
+ return false;
98
+ }
99
+ isBlockDevice() {
100
+ return false;
101
+ }
102
+ isCharacterDevice() {
103
+ return false;
104
+ }
105
+ isFIFO() {
106
+ return false;
107
+ }
108
+ isSocket() {
109
+ return false;
110
+ }
111
+ }
112
+ // Dir class for opendir — async-iterable directory handle
113
+ class Dir {
114
+ path;
115
+ _entries = null;
116
+ _index = 0;
117
+ _closed = false;
118
+ constructor(dirPath) {
119
+ this.path = dirPath;
120
+ }
121
+ _load() {
122
+ if (this._entries === null) {
123
+ this._entries = fs.readdirSync(this.path, { withFileTypes: true });
124
+ }
125
+ return this._entries;
126
+ }
127
+ readSync() {
128
+ if (this._closed)
129
+ throw new Error("Directory handle was closed");
130
+ const entries = this._load();
131
+ if (this._index >= entries.length)
132
+ return null;
133
+ return entries[this._index++];
134
+ }
135
+ async read() {
136
+ return this.readSync();
137
+ }
138
+ closeSync() {
139
+ this._closed = true;
140
+ }
141
+ async close() {
142
+ this.closeSync();
143
+ }
144
+ async *[Symbol.asyncIterator]() {
145
+ const entries = this._load();
146
+ for (const entry of entries) {
147
+ if (this._closed)
148
+ return;
149
+ yield entry;
150
+ }
151
+ this._closed = true;
152
+ }
153
+ }
154
+ // ReadStream class for createReadStream
155
+ // Provides a proper readable stream implementation that works with stream.pipeline
156
+ class ReadStream {
157
+ _options;
158
+ // ReadStream-specific properties
159
+ bytesRead = 0;
160
+ path;
161
+ pending = true;
162
+ // Readable stream properties
163
+ readable = true;
164
+ readableAborted = false;
165
+ readableDidRead = false;
166
+ readableEncoding = null;
167
+ readableEnded = false;
168
+ readableFlowing = null;
169
+ readableHighWaterMark = 65536;
170
+ readableLength = 0;
171
+ readableObjectMode = false;
172
+ destroyed = false;
173
+ closed = false;
174
+ errored = null;
175
+ // Internal state
176
+ _content = null;
177
+ _listeners = new Map();
178
+ _started = false;
179
+ constructor(filePath, _options) {
180
+ this._options = _options;
181
+ this.path = filePath;
182
+ if (_options?.encoding) {
183
+ this.readableEncoding = _options.encoding;
184
+ }
185
+ if (_options?.highWaterMark) {
186
+ this.readableHighWaterMark = _options.highWaterMark;
187
+ }
188
+ }
189
+ _loadContent() {
190
+ if (this._content === null) {
191
+ const pathStr = typeof this.path === 'string' ? this.path : this.path.toString();
192
+ // readFileSync already normalizes the path
193
+ this._content = fs.readFileSync(pathStr);
194
+ this.pending = false;
195
+ }
196
+ return this._content;
197
+ }
198
+ // Start reading - called when 'data' listener is added or resume() is called
199
+ _startReading() {
200
+ if (this._started || this.destroyed)
201
+ return;
202
+ this._started = true;
203
+ this.readableFlowing = true;
204
+ Promise.resolve().then(() => {
205
+ try {
206
+ const content = this._loadContent();
207
+ this.readableDidRead = true;
208
+ // Determine start/end positions
209
+ const start = this._options?.start ?? 0;
210
+ const end = this._options?.end ?? content.length;
211
+ const chunk = content.slice(start, end);
212
+ this.bytesRead = chunk.length;
213
+ // Emit data event
214
+ this.emit('data', chunk);
215
+ // Emit end and close
216
+ Promise.resolve().then(() => {
217
+ this.readable = false;
218
+ this.readableEnded = true;
219
+ this.emit('end');
220
+ Promise.resolve().then(() => {
221
+ this.closed = true;
222
+ this.emit('close');
223
+ });
224
+ });
225
+ }
226
+ catch (err) {
227
+ this.errored = err;
228
+ this.emit('error', err);
229
+ this.destroy(err);
230
+ }
231
+ });
232
+ }
233
+ // Event handling
234
+ on(event, listener) {
235
+ if (!this._listeners.has(event)) {
236
+ this._listeners.set(event, []);
237
+ }
238
+ this._listeners.get(event).push(listener);
239
+ // Start reading when 'data' listener is added (flowing mode)
240
+ if (event === 'data' && !this._started) {
241
+ this._startReading();
242
+ }
243
+ return this;
244
+ }
245
+ once(event, listener) {
246
+ const wrapper = (...args) => {
247
+ this.off(event, wrapper);
248
+ listener(...args);
249
+ };
250
+ wrapper._originalListener = listener;
251
+ return this.on(event, wrapper);
252
+ }
253
+ off(event, listener) {
254
+ const listeners = this._listeners.get(event);
255
+ if (listeners) {
256
+ const idx = listeners.findIndex(fn => fn === listener || fn._originalListener === listener);
257
+ if (idx !== -1)
258
+ listeners.splice(idx, 1);
259
+ }
260
+ return this;
261
+ }
262
+ removeListener(event, listener) {
263
+ return this.off(event, listener);
264
+ }
265
+ removeAllListeners(event) {
266
+ if (event) {
267
+ this._listeners.delete(event);
268
+ }
269
+ else {
270
+ this._listeners.clear();
271
+ }
272
+ return this;
273
+ }
274
+ emit(event, ...args) {
275
+ const listeners = this._listeners.get(event);
276
+ if (listeners && listeners.length > 0) {
277
+ listeners.slice().forEach(fn => fn(...args));
278
+ return true;
279
+ }
280
+ return false;
281
+ }
282
+ // Readable methods
283
+ read(_size) {
284
+ if (this.readableEnded || this.destroyed)
285
+ return null;
286
+ try {
287
+ const content = this._loadContent();
288
+ const start = this._options?.start ?? 0;
289
+ const end = this._options?.end ?? content.length;
290
+ const chunk = content.slice(start, end);
291
+ this.bytesRead = chunk.length;
292
+ this.readableDidRead = true;
293
+ this.readable = false;
294
+ this.readableEnded = true;
295
+ // Schedule end event
296
+ Promise.resolve().then(() => {
297
+ this.emit('end');
298
+ Promise.resolve().then(() => {
299
+ this.closed = true;
300
+ this.emit('close');
301
+ });
302
+ });
303
+ return this.readableEncoding ? chunk.toString(this.readableEncoding) : chunk;
304
+ }
305
+ catch (err) {
306
+ this.errored = err;
307
+ this.emit('error', err);
308
+ return null;
309
+ }
310
+ }
311
+ pipe(destination, _options) {
312
+ const content = this._loadContent();
313
+ const start = this._options?.start ?? 0;
314
+ const end = this._options?.end ?? content.length;
315
+ const chunk = content.slice(start, end);
316
+ this.bytesRead = chunk.length;
317
+ this.readableDidRead = true;
318
+ if (typeof destination.write === 'function') {
319
+ destination.write(chunk);
320
+ }
321
+ if (typeof destination.end === 'function') {
322
+ Promise.resolve().then(() => destination.end());
323
+ }
324
+ this.readable = false;
325
+ this.readableEnded = true;
326
+ this.closed = true;
327
+ Promise.resolve().then(() => {
328
+ this.emit('end');
329
+ this.emit('close');
330
+ });
331
+ return destination;
332
+ }
333
+ unpipe(_destination) {
334
+ return this;
335
+ }
336
+ pause() {
337
+ this.readableFlowing = false;
338
+ return this;
339
+ }
340
+ resume() {
341
+ this.readableFlowing = true;
342
+ if (!this._started) {
343
+ this._startReading();
344
+ }
345
+ return this;
346
+ }
347
+ setEncoding(encoding) {
348
+ this.readableEncoding = encoding;
349
+ return this;
350
+ }
351
+ destroy(error) {
352
+ if (this.destroyed)
353
+ return this;
354
+ this.destroyed = true;
355
+ this.readable = false;
356
+ if (error) {
357
+ this.errored = error;
358
+ this.emit('error', error);
359
+ }
360
+ this.emit('close');
361
+ this.closed = true;
362
+ return this;
363
+ }
364
+ close(callback) {
365
+ if (this.closed) {
366
+ if (callback)
367
+ Promise.resolve().then(() => callback(null));
368
+ return;
369
+ }
370
+ this.closed = true;
371
+ this.readable = false;
372
+ this.destroyed = true;
373
+ Promise.resolve().then(() => {
374
+ this.emit('close');
375
+ if (callback)
376
+ callback(null);
377
+ });
378
+ }
379
+ // Symbol.asyncIterator for async iteration
380
+ async *[Symbol.asyncIterator]() {
381
+ const content = this._loadContent();
382
+ const start = this._options?.start ?? 0;
383
+ const end = this._options?.end ?? content.length;
384
+ const chunk = content.slice(start, end);
385
+ yield this.readableEncoding ? chunk.toString(this.readableEncoding) : chunk;
386
+ }
387
+ }
388
+ // WriteStream class for createWriteStream
389
+ // This provides a type-safe implementation that satisfies nodeFs.WriteStream
390
+ // We use 'as' assertion at the return site since the full interface is complex
391
+ class WriteStream {
392
+ // WriteStream-specific properties
393
+ bytesWritten = 0;
394
+ path;
395
+ pending = false;
396
+ // Writable stream properties
397
+ writable = true;
398
+ writableAborted = false;
399
+ writableEnded = false;
400
+ writableFinished = false;
401
+ writableHighWaterMark = 16384;
402
+ writableLength = 0;
403
+ writableObjectMode = false;
404
+ writableCorked = 0;
405
+ destroyed = false;
406
+ closed = false;
407
+ errored = null;
408
+ writableNeedDrain = false;
409
+ // Internal state
410
+ _chunks = [];
411
+ _listeners = new Map();
412
+ constructor(filePath, _options) {
413
+ this.path = filePath;
414
+ }
415
+ // WriteStream-specific methods
416
+ close(callback) {
417
+ if (this.closed) {
418
+ if (callback)
419
+ Promise.resolve().then(() => callback(null));
420
+ return;
421
+ }
422
+ this.closed = true;
423
+ this.writable = false;
424
+ Promise.resolve().then(() => {
425
+ this.emit("close");
426
+ if (callback)
427
+ callback(null);
428
+ });
429
+ }
430
+ // Writable methods
431
+ write(chunk, encodingOrCallback, callback) {
432
+ if (this.writableEnded || this.destroyed) {
433
+ const err = new Error("write after end");
434
+ if (typeof encodingOrCallback === "function") {
435
+ Promise.resolve().then(() => encodingOrCallback(err));
436
+ }
437
+ else if (callback) {
438
+ Promise.resolve().then(() => callback(err));
439
+ }
440
+ return false;
441
+ }
442
+ let data;
443
+ if (typeof chunk === "string") {
444
+ data = Buffer.from(chunk, typeof encodingOrCallback === "string" ? encodingOrCallback : "utf8");
445
+ }
446
+ else if (Buffer.isBuffer(chunk)) {
447
+ data = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
448
+ }
449
+ else if (chunk instanceof Uint8Array) {
450
+ data = chunk;
451
+ }
452
+ else {
453
+ data = Buffer.from(String(chunk));
454
+ }
455
+ this._chunks.push(data);
456
+ this.bytesWritten += data.length;
457
+ this.writableLength += data.length;
458
+ const cb = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
459
+ if (cb)
460
+ Promise.resolve().then(() => cb(null));
461
+ return true;
462
+ }
463
+ end(chunkOrCb, encodingOrCallback, callback) {
464
+ if (this.writableEnded)
465
+ return this;
466
+ let cb;
467
+ if (typeof chunkOrCb === "function") {
468
+ cb = chunkOrCb;
469
+ }
470
+ else if (typeof encodingOrCallback === "function") {
471
+ cb = encodingOrCallback;
472
+ if (chunkOrCb !== undefined && chunkOrCb !== null) {
473
+ this.write(chunkOrCb);
474
+ }
475
+ }
476
+ else {
477
+ cb = callback;
478
+ if (chunkOrCb !== undefined && chunkOrCb !== null) {
479
+ this.write(chunkOrCb, encodingOrCallback);
480
+ }
481
+ }
482
+ this.writableEnded = true;
483
+ // Concatenate and write all chunks
484
+ const totalLength = this._chunks.reduce((sum, c) => sum + c.length, 0);
485
+ const result = new Uint8Array(totalLength);
486
+ let offset = 0;
487
+ for (const c of this._chunks) {
488
+ result.set(c, offset);
489
+ offset += c.length;
490
+ }
491
+ // Write to filesystem
492
+ const pathStr = typeof this.path === "string" ? this.path : this.path.toString();
493
+ fs.writeFileSync(pathStr, result);
494
+ this.writable = false;
495
+ this.writableFinished = true;
496
+ this.writableLength = 0;
497
+ Promise.resolve().then(() => {
498
+ this.emit("finish");
499
+ this.emit("close");
500
+ this.closed = true;
501
+ if (cb)
502
+ cb();
503
+ });
504
+ return this;
505
+ }
506
+ setDefaultEncoding(_encoding) {
507
+ return this;
508
+ }
509
+ cork() {
510
+ this.writableCorked++;
511
+ }
512
+ uncork() {
513
+ if (this.writableCorked > 0)
514
+ this.writableCorked--;
515
+ }
516
+ destroy(error) {
517
+ if (this.destroyed)
518
+ return this;
519
+ this.destroyed = true;
520
+ this.writable = false;
521
+ if (error) {
522
+ this.errored = error;
523
+ Promise.resolve().then(() => {
524
+ this.emit("error", error);
525
+ this.emit("close");
526
+ this.closed = true;
527
+ });
528
+ }
529
+ else {
530
+ Promise.resolve().then(() => {
531
+ this.emit("close");
532
+ this.closed = true;
533
+ });
534
+ }
535
+ return this;
536
+ }
537
+ // Internal methods (required by Writable interface but not typically called directly)
538
+ _write(_chunk, _encoding, callback) {
539
+ callback();
540
+ }
541
+ _destroy(_error, callback) {
542
+ callback();
543
+ }
544
+ _final(callback) {
545
+ callback();
546
+ }
547
+ // EventEmitter methods
548
+ addListener(event, listener) {
549
+ return this.on(event, listener);
550
+ }
551
+ on(event, listener) {
552
+ const listeners = this._listeners.get(event) || [];
553
+ listeners.push(listener);
554
+ this._listeners.set(event, listeners);
555
+ return this;
556
+ }
557
+ once(event, listener) {
558
+ const wrapper = (...args) => {
559
+ this.removeListener(event, wrapper);
560
+ listener(...args);
561
+ };
562
+ return this.on(event, wrapper);
563
+ }
564
+ prependListener(event, listener) {
565
+ const listeners = this._listeners.get(event) || [];
566
+ listeners.unshift(listener);
567
+ this._listeners.set(event, listeners);
568
+ return this;
569
+ }
570
+ prependOnceListener(event, listener) {
571
+ const wrapper = (...args) => {
572
+ this.removeListener(event, wrapper);
573
+ listener(...args);
574
+ };
575
+ return this.prependListener(event, wrapper);
576
+ }
577
+ removeListener(event, listener) {
578
+ const listeners = this._listeners.get(event);
579
+ if (listeners) {
580
+ const idx = listeners.indexOf(listener);
581
+ if (idx !== -1)
582
+ listeners.splice(idx, 1);
583
+ }
584
+ return this;
585
+ }
586
+ off(event, listener) {
587
+ return this.removeListener(event, listener);
588
+ }
589
+ removeAllListeners(event) {
590
+ if (event !== undefined) {
591
+ this._listeners.delete(event);
592
+ }
593
+ else {
594
+ this._listeners.clear();
595
+ }
596
+ return this;
597
+ }
598
+ emit(event, ...args) {
599
+ const listeners = this._listeners.get(event);
600
+ if (listeners && listeners.length > 0) {
601
+ listeners.slice().forEach(l => l(...args));
602
+ return true;
603
+ }
604
+ return false;
605
+ }
606
+ listeners(event) {
607
+ return [...(this._listeners.get(event) || [])];
608
+ }
609
+ rawListeners(event) {
610
+ return this.listeners(event);
611
+ }
612
+ listenerCount(event) {
613
+ return (this._listeners.get(event) || []).length;
614
+ }
615
+ eventNames() {
616
+ return [...this._listeners.keys()];
617
+ }
618
+ getMaxListeners() {
619
+ return 10;
620
+ }
621
+ setMaxListeners(_n) {
622
+ return this;
623
+ }
624
+ // Pipe methods (minimal implementation)
625
+ pipe(destination, _options) {
626
+ return destination;
627
+ }
628
+ unpipe(_destination) {
629
+ return this;
630
+ }
631
+ // Additional required methods
632
+ compose(_stream, _options) {
633
+ throw new Error("compose not implemented in sandbox");
634
+ }
635
+ [Symbol.asyncDispose]() {
636
+ return Promise.resolve();
637
+ }
638
+ }
639
+ // Parse flags string to number
640
+ function parseFlags(flags) {
641
+ if (typeof flags === "number")
642
+ return flags;
643
+ const flagMap = {
644
+ r: O_RDONLY,
645
+ "r+": O_RDWR,
646
+ w: O_WRONLY | O_CREAT | O_TRUNC,
647
+ "w+": O_RDWR | O_CREAT | O_TRUNC,
648
+ a: O_WRONLY | O_APPEND | O_CREAT,
649
+ "a+": O_RDWR | O_APPEND | O_CREAT,
650
+ wx: O_WRONLY | O_CREAT | O_TRUNC | O_EXCL,
651
+ xw: O_WRONLY | O_CREAT | O_TRUNC | O_EXCL,
652
+ "wx+": O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
653
+ "xw+": O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
654
+ ax: O_WRONLY | O_APPEND | O_CREAT | O_EXCL,
655
+ xa: O_WRONLY | O_APPEND | O_CREAT | O_EXCL,
656
+ "ax+": O_RDWR | O_APPEND | O_CREAT | O_EXCL,
657
+ "xa+": O_RDWR | O_APPEND | O_CREAT | O_EXCL,
658
+ };
659
+ if (flags in flagMap)
660
+ return flagMap[flags];
661
+ throw new Error("Unknown file flag: " + flags);
662
+ }
663
+ // Check if flags allow reading
664
+ function canRead(flags) {
665
+ const mode = flags & O_ACCMODE;
666
+ return mode === 0 || mode === 2;
667
+ }
668
+ // Check if flags allow writing
669
+ function canWrite(flags) {
670
+ const mode = flags & O_ACCMODE;
671
+ return mode === 1 || mode === 2;
672
+ }
673
+ // Helper to create fs errors
674
+ function createFsError(code, message, syscall, path) {
675
+ const err = new Error(message);
676
+ err.code = code;
677
+ err.errno = code === "ENOENT" ? -2 : code === "EACCES" ? -13 : code === "EBADF" ? -9 : -1;
678
+ err.syscall = syscall;
679
+ if (path)
680
+ err.path = path;
681
+ return err;
682
+ }
683
+ /** Wrap a bridge call with ENOENT/EACCES error re-creation. */
684
+ function bridgeCall(fn, syscall, path) {
685
+ try {
686
+ return fn();
687
+ }
688
+ catch (err) {
689
+ const msg = err.message || String(err);
690
+ if (msg.includes("ENOENT") || msg.includes("no such file or directory") || msg.includes("not found")) {
691
+ throw createFsError("ENOENT", `ENOENT: no such file or directory, ${syscall} '${path}'`, syscall, path);
692
+ }
693
+ if (msg.includes("EACCES") || msg.includes("permission denied")) {
694
+ throw createFsError("EACCES", `EACCES: permission denied, ${syscall} '${path}'`, syscall, path);
695
+ }
696
+ if (msg.includes("EEXIST") || msg.includes("file already exists")) {
697
+ throw createFsError("EEXIST", `EEXIST: file already exists, ${syscall} '${path}'`, syscall, path);
698
+ }
699
+ if (msg.includes("EINVAL") || msg.includes("invalid argument")) {
700
+ throw createFsError("EINVAL", `EINVAL: invalid argument, ${syscall} '${path}'`, syscall, path);
701
+ }
702
+ throw err;
703
+ }
704
+ }
705
+ // Glob pattern matching helper — converts glob to regex and walks VFS recursively
706
+ function _globToRegex(pattern) {
707
+ // Determine base directory vs glob portion
708
+ let regexStr = "";
709
+ let i = 0;
710
+ while (i < pattern.length) {
711
+ const ch = pattern[i];
712
+ if (ch === "*" && pattern[i + 1] === "*") {
713
+ // ** matches any depth of directories
714
+ if (pattern[i + 2] === "/") {
715
+ regexStr += "(?:.+/)?";
716
+ i += 3;
717
+ }
718
+ else {
719
+ regexStr += ".*";
720
+ i += 2;
721
+ }
722
+ }
723
+ else if (ch === "*") {
724
+ regexStr += "[^/]*";
725
+ i++;
726
+ }
727
+ else if (ch === "?") {
728
+ regexStr += "[^/]";
729
+ i++;
730
+ }
731
+ else if (ch === "{") {
732
+ const close = pattern.indexOf("}", i);
733
+ if (close !== -1) {
734
+ const alternatives = pattern.slice(i + 1, close).split(",");
735
+ regexStr += "(?:" + alternatives.map(a => a.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, "[^/]*")).join("|") + ")";
736
+ i = close + 1;
737
+ }
738
+ else {
739
+ regexStr += "\\{";
740
+ i++;
741
+ }
742
+ }
743
+ else if (ch === "[") {
744
+ const close = pattern.indexOf("]", i);
745
+ if (close !== -1) {
746
+ regexStr += pattern.slice(i, close + 1);
747
+ i = close + 1;
748
+ }
749
+ else {
750
+ regexStr += "\\[";
751
+ i++;
752
+ }
753
+ }
754
+ else if (".+^${}()|[]\\".includes(ch)) {
755
+ regexStr += "\\" + ch;
756
+ i++;
757
+ }
758
+ else {
759
+ regexStr += ch;
760
+ i++;
761
+ }
762
+ }
763
+ return new RegExp("^" + regexStr + "$");
764
+ }
765
+ function _globGetBase(pattern) {
766
+ // Find the longest directory prefix that has no glob characters
767
+ const parts = pattern.split("/");
768
+ const baseParts = [];
769
+ for (const part of parts) {
770
+ if (/[*?{}\[\]]/.test(part))
771
+ break;
772
+ baseParts.push(part);
773
+ }
774
+ return baseParts.join("/") || "/";
775
+ }
776
+ // Recursively walk VFS directory and collect matching paths
777
+ // We use a reference to `fs` via late-binding in the fs object method
778
+ function _globCollect(pattern, results) {
779
+ const regex = _globToRegex(pattern);
780
+ const base = _globGetBase(pattern);
781
+ const walk = (dir) => {
782
+ let entries;
783
+ try {
784
+ entries = _globReadDir(dir);
785
+ }
786
+ catch {
787
+ return; // Directory doesn't exist or not readable
788
+ }
789
+ for (const entry of entries) {
790
+ const fullPath = dir === "/" ? "/" + entry : dir + "/" + entry;
791
+ // Check if this path matches the pattern
792
+ if (regex.test(fullPath)) {
793
+ results.push(fullPath);
794
+ }
795
+ // Recurse into directories if pattern has ** or more segments
796
+ try {
797
+ const stat = _globStat(fullPath);
798
+ if (stat.isDirectory()) {
799
+ walk(fullPath);
800
+ }
801
+ }
802
+ catch {
803
+ // Not a directory or stat failed — skip
804
+ }
805
+ }
806
+ };
807
+ // Start walking from the base directory
808
+ try {
809
+ // Check if base itself matches (edge case)
810
+ if (regex.test(base)) {
811
+ const stat = _globStat(base);
812
+ if (!stat.isDirectory()) {
813
+ results.push(base);
814
+ return;
815
+ }
816
+ }
817
+ walk(base);
818
+ }
819
+ catch {
820
+ // Base doesn't exist — no matches
821
+ }
822
+ }
823
+ // Late-bound references — these get assigned after fs is defined
824
+ let _globReadDir;
825
+ let _globStat;
826
+ // Helper to convert PathLike to string
827
+ function toPathString(path) {
828
+ if (typeof path === "string")
829
+ return path;
830
+ if (Buffer.isBuffer(path))
831
+ return path.toString("utf8");
832
+ if (path instanceof URL)
833
+ return path.pathname;
834
+ return String(path);
835
+ }
836
+ // Note: Path normalization is handled by VirtualFileSystem, not here.
837
+ // The VFS expects /data/* paths for Directory access, so we pass paths through unchanged.
838
+ // The fs module implementation
839
+ const fs = {
840
+ // Constants
841
+ constants: {
842
+ // File Access Constants
843
+ F_OK: 0,
844
+ R_OK: 4,
845
+ W_OK: 2,
846
+ X_OK: 1,
847
+ // File Copy Constants
848
+ COPYFILE_EXCL: 1,
849
+ COPYFILE_FICLONE: 2,
850
+ COPYFILE_FICLONE_FORCE: 4,
851
+ // File Open Constants
852
+ O_RDONLY,
853
+ O_WRONLY,
854
+ O_RDWR,
855
+ O_CREAT,
856
+ O_EXCL,
857
+ O_NOCTTY: 256,
858
+ O_TRUNC,
859
+ O_APPEND,
860
+ O_DIRECTORY: 65536,
861
+ O_NOATIME: 262144,
862
+ O_NOFOLLOW: 131072,
863
+ O_SYNC: 1052672,
864
+ O_DSYNC: 4096,
865
+ O_SYMLINK: 2097152,
866
+ O_DIRECT: 16384,
867
+ O_NONBLOCK: 2048,
868
+ // File Type Constants
869
+ S_IFMT: 61440,
870
+ S_IFREG: 32768,
871
+ S_IFDIR: 16384,
872
+ S_IFCHR: 8192,
873
+ S_IFBLK: 24576,
874
+ S_IFIFO: 4096,
875
+ S_IFLNK: 40960,
876
+ S_IFSOCK: 49152,
877
+ // File Mode Constants
878
+ S_IRWXU: 448,
879
+ S_IRUSR: 256,
880
+ S_IWUSR: 128,
881
+ S_IXUSR: 64,
882
+ S_IRWXG: 56,
883
+ S_IRGRP: 32,
884
+ S_IWGRP: 16,
885
+ S_IXGRP: 8,
886
+ S_IRWXO: 7,
887
+ S_IROTH: 4,
888
+ S_IWOTH: 2,
889
+ S_IXOTH: 1,
890
+ UV_FS_O_FILEMAP: 536870912,
891
+ },
892
+ Stats,
893
+ Dirent,
894
+ Dir,
895
+ // Sync methods
896
+ readFileSync(path, options) {
897
+ const rawPath = typeof path === "number" ? fdTable.get(path)?.path : toPathString(path);
898
+ if (!rawPath)
899
+ throw createFsError("EBADF", "EBADF: bad file descriptor", "read");
900
+ const pathStr = rawPath;
901
+ const encoding = typeof options === "string" ? options : options?.encoding;
902
+ try {
903
+ if (encoding) {
904
+ // Text mode - use text read
905
+ const content = _fs.readFile.applySyncPromise(undefined, [pathStr]);
906
+ return content;
907
+ }
908
+ else {
909
+ // Binary mode - use binary read with base64 encoding
910
+ const base64Content = _fs.readFileBinary.applySyncPromise(undefined, [pathStr]);
911
+ return Buffer.from(base64Content, "base64");
912
+ }
913
+ }
914
+ catch (err) {
915
+ const errMsg = err.message || String(err);
916
+ // Convert various "not found" errors to proper ENOENT
917
+ if (errMsg.includes("entry not found") ||
918
+ errMsg.includes("not found") ||
919
+ errMsg.includes("ENOENT") ||
920
+ errMsg.includes("no such file or directory")) {
921
+ throw createFsError("ENOENT", `ENOENT: no such file or directory, open '${rawPath}'`, "open", rawPath);
922
+ }
923
+ // Convert permission errors to proper EACCES
924
+ if (errMsg.includes("EACCES") || errMsg.includes("permission denied")) {
925
+ throw createFsError("EACCES", `EACCES: permission denied, open '${rawPath}'`, "open", rawPath);
926
+ }
927
+ throw err;
928
+ }
929
+ },
930
+ writeFileSync(file, data, _options) {
931
+ const rawPath = typeof file === "number" ? fdTable.get(file)?.path : toPathString(file);
932
+ if (!rawPath)
933
+ throw createFsError("EBADF", "EBADF: bad file descriptor", "write");
934
+ const pathStr = rawPath;
935
+ if (typeof data === "string") {
936
+ // Text mode - use text write
937
+ // Return the result so async callers (fs.promises) can await it.
938
+ return _fs.writeFile.applySyncPromise(undefined, [pathStr, data]);
939
+ }
940
+ else if (ArrayBuffer.isView(data)) {
941
+ // Binary mode - convert to base64 and use binary write
942
+ const uint8 = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
943
+ const base64 = Buffer.from(uint8).toString("base64");
944
+ return _fs.writeFileBinary.applySyncPromise(undefined, [pathStr, base64]);
945
+ }
946
+ else {
947
+ // Fallback to text mode
948
+ return _fs.writeFile.applySyncPromise(undefined, [pathStr, String(data)]);
949
+ }
950
+ },
951
+ appendFileSync(path, data, options) {
952
+ const existing = fs.existsSync(path)
953
+ ? fs.readFileSync(path, "utf8")
954
+ : "";
955
+ const content = typeof data === "string" ? data : String(data);
956
+ fs.writeFileSync(path, existing + content, options);
957
+ },
958
+ readdirSync(path, options) {
959
+ const rawPath = toPathString(path);
960
+ const pathStr = rawPath;
961
+ let entriesJson;
962
+ try {
963
+ entriesJson = _fs.readDir.applySyncPromise(undefined, [pathStr]);
964
+ }
965
+ catch (err) {
966
+ // Convert "entry not found" and similar errors to proper ENOENT
967
+ const errMsg = err.message || String(err);
968
+ if (errMsg.includes("entry not found") || errMsg.includes("not found")) {
969
+ throw createFsError("ENOENT", `ENOENT: no such file or directory, scandir '${rawPath}'`, "scandir", rawPath);
970
+ }
971
+ throw err;
972
+ }
973
+ const entries = JSON.parse(entriesJson);
974
+ if (options?.withFileTypes) {
975
+ return entries.map((e) => new Dirent(e.name, e.isDirectory, rawPath));
976
+ }
977
+ return entries.map((e) => e.name);
978
+ },
979
+ mkdirSync(path, options) {
980
+ const rawPath = toPathString(path);
981
+ const pathStr = rawPath;
982
+ const recursive = typeof options === "object" ? options?.recursive ?? false : false;
983
+ _fs.mkdir.applySyncPromise(undefined, [pathStr, recursive]);
984
+ return recursive ? rawPath : undefined;
985
+ },
986
+ rmdirSync(path, _options) {
987
+ const pathStr = toPathString(path);
988
+ _fs.rmdir.applySyncPromise(undefined, [pathStr]);
989
+ },
990
+ rmSync(path, options) {
991
+ const pathStr = toPathString(path);
992
+ const opts = options || {};
993
+ try {
994
+ const stats = fs.statSync(pathStr);
995
+ if (stats.isDirectory()) {
996
+ if (opts.recursive) {
997
+ // Recursively remove directory contents
998
+ const entries = fs.readdirSync(pathStr);
999
+ for (const entry of entries) {
1000
+ const entryPath = pathStr.endsWith("/") ? pathStr + entry : pathStr + "/" + entry;
1001
+ const entryStats = fs.statSync(entryPath);
1002
+ if (entryStats.isDirectory()) {
1003
+ fs.rmSync(entryPath, { recursive: true });
1004
+ }
1005
+ else {
1006
+ fs.unlinkSync(entryPath);
1007
+ }
1008
+ }
1009
+ fs.rmdirSync(pathStr);
1010
+ }
1011
+ else {
1012
+ fs.rmdirSync(pathStr);
1013
+ }
1014
+ }
1015
+ else {
1016
+ fs.unlinkSync(pathStr);
1017
+ }
1018
+ }
1019
+ catch (e) {
1020
+ if (opts.force && e.code === "ENOENT") {
1021
+ return; // Ignore ENOENT when force is true
1022
+ }
1023
+ throw e;
1024
+ }
1025
+ },
1026
+ existsSync(path) {
1027
+ const pathStr = toPathString(path);
1028
+ return _fs.exists.applySyncPromise(undefined, [pathStr]);
1029
+ },
1030
+ statSync(path, _options) {
1031
+ const rawPath = toPathString(path);
1032
+ const pathStr = rawPath;
1033
+ let statJson;
1034
+ try {
1035
+ statJson = _fs.stat.applySyncPromise(undefined, [pathStr]);
1036
+ }
1037
+ catch (err) {
1038
+ // Convert various "not found" errors to proper ENOENT
1039
+ const errMsg = err.message || String(err);
1040
+ if (errMsg.includes("entry not found") ||
1041
+ errMsg.includes("not found") ||
1042
+ errMsg.includes("ENOENT") ||
1043
+ errMsg.includes("no such file or directory")) {
1044
+ throw createFsError("ENOENT", `ENOENT: no such file or directory, stat '${rawPath}'`, "stat", rawPath);
1045
+ }
1046
+ throw err;
1047
+ }
1048
+ const stat = JSON.parse(statJson);
1049
+ return new Stats(stat);
1050
+ },
1051
+ lstatSync(path, _options) {
1052
+ const pathStr = toPathString(path);
1053
+ const statJson = bridgeCall(() => _fs.lstat.applySyncPromise(undefined, [pathStr]), "lstat", pathStr);
1054
+ const stat = JSON.parse(statJson);
1055
+ return new Stats(stat);
1056
+ },
1057
+ unlinkSync(path) {
1058
+ const pathStr = toPathString(path);
1059
+ _fs.unlink.applySyncPromise(undefined, [pathStr]);
1060
+ },
1061
+ renameSync(oldPath, newPath) {
1062
+ const oldPathStr = toPathString(oldPath);
1063
+ const newPathStr = toPathString(newPath);
1064
+ _fs.rename.applySyncPromise(undefined, [oldPathStr, newPathStr]);
1065
+ },
1066
+ copyFileSync(src, dest, _mode) {
1067
+ // readFileSync and writeFileSync already normalize paths
1068
+ const content = fs.readFileSync(src);
1069
+ fs.writeFileSync(dest, content);
1070
+ },
1071
+ // Recursive copy
1072
+ cpSync(src, dest, options) {
1073
+ const srcPath = toPathString(src);
1074
+ const destPath = toPathString(dest);
1075
+ const opts = options || {};
1076
+ const srcStat = fs.statSync(srcPath);
1077
+ if (srcStat.isDirectory()) {
1078
+ if (!opts.recursive) {
1079
+ throw createFsError("ERR_FS_EISDIR", `Path is a directory: cp '${srcPath}'`, "cp", srcPath);
1080
+ }
1081
+ // Create destination directory
1082
+ try {
1083
+ fs.mkdirSync(destPath, { recursive: true });
1084
+ }
1085
+ catch {
1086
+ // May already exist
1087
+ }
1088
+ // Copy contents recursively
1089
+ const entries = fs.readdirSync(srcPath);
1090
+ for (const entry of entries) {
1091
+ const srcEntry = srcPath.endsWith("/") ? srcPath + entry : srcPath + "/" + entry;
1092
+ const destEntry = destPath.endsWith("/") ? destPath + entry : destPath + "/" + entry;
1093
+ fs.cpSync(srcEntry, destEntry, opts);
1094
+ }
1095
+ }
1096
+ else {
1097
+ // File copy
1098
+ if (opts.errorOnExist && fs.existsSync(destPath)) {
1099
+ throw createFsError("EEXIST", `EEXIST: file already exists, cp '${srcPath}' -> '${destPath}'`, "cp", destPath);
1100
+ }
1101
+ if (!opts.force && opts.force !== undefined && fs.existsSync(destPath)) {
1102
+ return; // Skip without error when force is false
1103
+ }
1104
+ fs.copyFileSync(srcPath, destPath);
1105
+ }
1106
+ },
1107
+ // Temp directory creation
1108
+ mkdtempSync(prefix, _options) {
1109
+ const suffix = Math.random().toString(36).slice(2, 8);
1110
+ const dirPath = prefix + suffix;
1111
+ fs.mkdirSync(dirPath, { recursive: true });
1112
+ return dirPath;
1113
+ },
1114
+ // Directory handle (sync)
1115
+ opendirSync(path, _options) {
1116
+ const pathStr = toPathString(path);
1117
+ // Verify directory exists
1118
+ const stat = fs.statSync(pathStr);
1119
+ if (!stat.isDirectory()) {
1120
+ throw createFsError("ENOTDIR", `ENOTDIR: not a directory, opendir '${pathStr}'`, "opendir", pathStr);
1121
+ }
1122
+ return new Dir(pathStr);
1123
+ },
1124
+ // File descriptor methods
1125
+ openSync(path, flags, _mode) {
1126
+ const rawPath = toPathString(path);
1127
+ const pathStr = rawPath;
1128
+ const numFlags = parseFlags(flags);
1129
+ const fd = nextFd++;
1130
+ // Check if file exists (existsSync already normalizes)
1131
+ const exists = fs.existsSync(path);
1132
+ // Handle O_CREAT - create file if it doesn't exist
1133
+ if (numFlags & 64 && !exists) {
1134
+ fs.writeFileSync(path, "");
1135
+ }
1136
+ else if (!exists && !(numFlags & 64)) {
1137
+ throw createFsError("ENOENT", `ENOENT: no such file or directory, open '${rawPath}'`, "open", rawPath);
1138
+ }
1139
+ // Handle O_TRUNC - truncate file
1140
+ if (numFlags & 512 && exists) {
1141
+ fs.writeFileSync(path, "");
1142
+ }
1143
+ // Store normalized path in fd table for subsequent operations
1144
+ fdTable.set(fd, { path: pathStr, flags: numFlags, position: 0 });
1145
+ return fd;
1146
+ },
1147
+ closeSync(fd) {
1148
+ if (!fdTable.has(fd)) {
1149
+ throw createFsError("EBADF", "EBADF: bad file descriptor, close", "close");
1150
+ }
1151
+ fdTable.delete(fd);
1152
+ },
1153
+ readSync(fd, buffer, offset, length, position) {
1154
+ const entry = fdTable.get(fd);
1155
+ if (!entry) {
1156
+ throw createFsError("EBADF", "EBADF: bad file descriptor, read", "read");
1157
+ }
1158
+ if (!canRead(entry.flags)) {
1159
+ throw createFsError("EBADF", "EBADF: bad file descriptor, read", "read");
1160
+ }
1161
+ const content = fs.readFileSync(entry.path, "utf8");
1162
+ const readOffset = offset ?? 0;
1163
+ const readLength = length ?? (buffer.byteLength - readOffset);
1164
+ const pos = position !== null && position !== undefined ? Number(position) : entry.position;
1165
+ const toRead = content.slice(pos, pos + readLength);
1166
+ const bytes = Buffer.from(toRead);
1167
+ const targetBuffer = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1168
+ for (let i = 0; i < bytes.length && i < readLength; i++) {
1169
+ targetBuffer[readOffset + i] = bytes[i];
1170
+ }
1171
+ if (position === null || position === undefined) {
1172
+ entry.position += bytes.length;
1173
+ }
1174
+ return bytes.length;
1175
+ },
1176
+ writeSync(fd, buffer, offsetOrPosition, lengthOrEncoding, position) {
1177
+ const entry = fdTable.get(fd);
1178
+ if (!entry) {
1179
+ throw createFsError("EBADF", "EBADF: bad file descriptor, write", "write");
1180
+ }
1181
+ // fs.writeSync
1182
+ if (!canWrite(entry.flags)) {
1183
+ throw createFsError("EBADF", "EBADF: bad file descriptor, write", "write");
1184
+ }
1185
+ // Handle string or buffer
1186
+ let data;
1187
+ let writePosition;
1188
+ if (typeof buffer === "string") {
1189
+ data = buffer;
1190
+ writePosition = offsetOrPosition;
1191
+ }
1192
+ else {
1193
+ const offset = offsetOrPosition ?? 0;
1194
+ const length = (typeof lengthOrEncoding === "number" ? lengthOrEncoding : null) ?? (buffer.byteLength - offset);
1195
+ const view = new Uint8Array(buffer.buffer, buffer.byteOffset + offset, length);
1196
+ data = new TextDecoder().decode(view);
1197
+ writePosition = position;
1198
+ }
1199
+ // Read existing content
1200
+ let content = "";
1201
+ if (fs.existsSync(entry.path)) {
1202
+ content = fs.readFileSync(entry.path, "utf8");
1203
+ }
1204
+ // Determine write position
1205
+ let writePos;
1206
+ if (entry.flags & 1024) {
1207
+ // O_APPEND
1208
+ writePos = content.length;
1209
+ }
1210
+ else if (writePosition !== null && writePosition !== undefined) {
1211
+ writePos = writePosition;
1212
+ }
1213
+ else {
1214
+ writePos = entry.position;
1215
+ }
1216
+ // Pad with nulls if writing past end
1217
+ while (content.length < writePos) {
1218
+ content += "\0";
1219
+ }
1220
+ // Write data
1221
+ const newContent = content.slice(0, writePos) + data + content.slice(writePos + data.length);
1222
+ fs.writeFileSync(entry.path, newContent);
1223
+ // Update position if not using explicit position
1224
+ if (writePosition === null || writePosition === undefined) {
1225
+ entry.position = writePos + data.length;
1226
+ }
1227
+ return data.length;
1228
+ },
1229
+ fstatSync(fd) {
1230
+ const entry = fdTable.get(fd);
1231
+ if (!entry) {
1232
+ throw createFsError("EBADF", "EBADF: bad file descriptor, fstat", "fstat");
1233
+ }
1234
+ return fs.statSync(entry.path);
1235
+ },
1236
+ ftruncateSync(fd, len) {
1237
+ const entry = fdTable.get(fd);
1238
+ if (!entry) {
1239
+ throw createFsError("EBADF", "EBADF: bad file descriptor, ftruncate", "ftruncate");
1240
+ }
1241
+ const content = fs.existsSync(entry.path)
1242
+ ? fs.readFileSync(entry.path, "utf8")
1243
+ : "";
1244
+ const newLen = len ?? 0;
1245
+ if (content.length > newLen) {
1246
+ fs.writeFileSync(entry.path, content.slice(0, newLen));
1247
+ }
1248
+ else {
1249
+ let padded = content;
1250
+ while (padded.length < newLen)
1251
+ padded += "\0";
1252
+ fs.writeFileSync(entry.path, padded);
1253
+ }
1254
+ },
1255
+ // fsync / fdatasync — no-op for in-memory VFS (nothing to flush to disk)
1256
+ fsyncSync(fd) {
1257
+ if (!fdTable.has(fd)) {
1258
+ throw createFsError("EBADF", "EBADF: bad file descriptor, fsync", "fsync");
1259
+ }
1260
+ },
1261
+ fdatasyncSync(fd) {
1262
+ if (!fdTable.has(fd)) {
1263
+ throw createFsError("EBADF", "EBADF: bad file descriptor, fdatasync", "fdatasync");
1264
+ }
1265
+ },
1266
+ // readv — scatter-read into multiple buffers
1267
+ readvSync(fd, buffers, position) {
1268
+ const entry = fdTable.get(fd);
1269
+ if (!entry) {
1270
+ throw createFsError("EBADF", "EBADF: bad file descriptor, readv", "readv");
1271
+ }
1272
+ if (!canRead(entry.flags)) {
1273
+ throw createFsError("EBADF", "EBADF: bad file descriptor, readv", "readv");
1274
+ }
1275
+ let totalBytesRead = 0;
1276
+ for (const buffer of buffers) {
1277
+ const target = buffer instanceof Uint8Array
1278
+ ? buffer
1279
+ : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1280
+ const bytesRead = fs.readSync(fd, target, 0, target.byteLength, position);
1281
+ totalBytesRead += bytesRead;
1282
+ if (position !== null && position !== undefined) {
1283
+ position += bytesRead;
1284
+ }
1285
+ // EOF — stop filling further buffers
1286
+ if (bytesRead < target.byteLength)
1287
+ break;
1288
+ }
1289
+ return totalBytesRead;
1290
+ },
1291
+ // statfs — return synthetic filesystem stats for the in-memory VFS
1292
+ statfsSync(path, _options) {
1293
+ const pathStr = toPathString(path);
1294
+ // Verify path exists
1295
+ if (!fs.existsSync(pathStr)) {
1296
+ throw createFsError("ENOENT", `ENOENT: no such file or directory, statfs '${pathStr}'`, "statfs", pathStr);
1297
+ }
1298
+ // Return synthetic stats — in-memory VFS has no real block device
1299
+ return {
1300
+ type: 0x01021997, // TMPFS_MAGIC
1301
+ bsize: 4096,
1302
+ blocks: 262144, // 1GB virtual capacity
1303
+ bfree: 262144,
1304
+ bavail: 262144,
1305
+ files: 1000000,
1306
+ ffree: 999999,
1307
+ };
1308
+ },
1309
+ // glob — pattern matching over VFS files
1310
+ globSync(pattern, _options) {
1311
+ const patterns = Array.isArray(pattern) ? pattern : [pattern];
1312
+ const results = [];
1313
+ for (const pat of patterns) {
1314
+ _globCollect(pat, results);
1315
+ }
1316
+ return [...new Set(results)].sort();
1317
+ },
1318
+ // Metadata and link sync methods — delegate to VFS via host refs
1319
+ chmodSync(path, mode) {
1320
+ const pathStr = toPathString(path);
1321
+ const modeNum = typeof mode === "string" ? parseInt(mode, 8) : mode;
1322
+ bridgeCall(() => _fs.chmod.applySyncPromise(undefined, [pathStr, modeNum]), "chmod", pathStr);
1323
+ },
1324
+ chownSync(path, uid, gid) {
1325
+ const pathStr = toPathString(path);
1326
+ bridgeCall(() => _fs.chown.applySyncPromise(undefined, [pathStr, uid, gid]), "chown", pathStr);
1327
+ },
1328
+ linkSync(existingPath, newPath) {
1329
+ const existingStr = toPathString(existingPath);
1330
+ const newStr = toPathString(newPath);
1331
+ bridgeCall(() => _fs.link.applySyncPromise(undefined, [existingStr, newStr]), "link", newStr);
1332
+ },
1333
+ symlinkSync(target, path, _type) {
1334
+ const targetStr = toPathString(target);
1335
+ const pathStr = toPathString(path);
1336
+ bridgeCall(() => _fs.symlink.applySyncPromise(undefined, [targetStr, pathStr]), "symlink", pathStr);
1337
+ },
1338
+ readlinkSync(path, _options) {
1339
+ const pathStr = toPathString(path);
1340
+ return bridgeCall(() => _fs.readlink.applySyncPromise(undefined, [pathStr]), "readlink", pathStr);
1341
+ },
1342
+ truncateSync(path, len) {
1343
+ const pathStr = toPathString(path);
1344
+ bridgeCall(() => _fs.truncate.applySyncPromise(undefined, [pathStr, len ?? 0]), "truncate", pathStr);
1345
+ },
1346
+ utimesSync(path, atime, mtime) {
1347
+ const pathStr = toPathString(path);
1348
+ const atimeNum = typeof atime === "number" ? atime : new Date(atime).getTime() / 1000;
1349
+ const mtimeNum = typeof mtime === "number" ? mtime : new Date(mtime).getTime() / 1000;
1350
+ bridgeCall(() => _fs.utimes.applySyncPromise(undefined, [pathStr, atimeNum, mtimeNum]), "utimes", pathStr);
1351
+ },
1352
+ // Async methods - wrap sync methods in callbacks/promises
1353
+ //
1354
+ // IMPORTANT: Low-level fd operations (open, close, read, write) and operations commonly
1355
+ // used by streaming libraries (stat, lstat, rename, unlink) must defer their callbacks
1356
+ // using queueMicrotask(). This is critical for proper stream operation.
1357
+ //
1358
+ // Why: Node.js streams (like tar, minipass, fs-minipass) use callback chains where each
1359
+ // callback triggers the next read/write operation. These streams also rely on events like
1360
+ // 'drain' to know when to resume writing. If callbacks fire synchronously, the event loop
1361
+ // never gets a chance to process these events, causing streams to stall after the first chunk.
1362
+ //
1363
+ // Example problem without queueMicrotask:
1364
+ // 1. tar calls fs.read() with callback
1365
+ // 2. Our sync implementation calls callback immediately
1366
+ // 3. Callback writes to stream, stream buffer fills, returns false (needs drain)
1367
+ // 4. Code sets up 'drain' listener and returns
1368
+ // 5. But we never returned to event loop, so 'drain' never fires
1369
+ // 6. Stream hangs forever
1370
+ //
1371
+ // With queueMicrotask, step 2 defers the callback, allowing the event loop to process
1372
+ // pending events (including 'drain') before the next operation starts.
1373
+ readFile(path, options, callback) {
1374
+ if (typeof options === "function") {
1375
+ callback = options;
1376
+ options = undefined;
1377
+ }
1378
+ if (callback) {
1379
+ try {
1380
+ callback(null, fs.readFileSync(path, options));
1381
+ }
1382
+ catch (e) {
1383
+ callback(e);
1384
+ }
1385
+ }
1386
+ else {
1387
+ return Promise.resolve(fs.readFileSync(path, options));
1388
+ }
1389
+ },
1390
+ writeFile(path, data, options, callback) {
1391
+ if (typeof options === "function") {
1392
+ callback = options;
1393
+ options = undefined;
1394
+ }
1395
+ if (callback) {
1396
+ try {
1397
+ fs.writeFileSync(path, data, options);
1398
+ callback(null);
1399
+ }
1400
+ catch (e) {
1401
+ callback(e);
1402
+ }
1403
+ }
1404
+ else {
1405
+ return Promise.resolve(fs.writeFileSync(path, data, options));
1406
+ }
1407
+ },
1408
+ appendFile(path, data, options, callback) {
1409
+ if (typeof options === "function") {
1410
+ callback = options;
1411
+ options = undefined;
1412
+ }
1413
+ if (callback) {
1414
+ try {
1415
+ fs.appendFileSync(path, data, options);
1416
+ callback(null);
1417
+ }
1418
+ catch (e) {
1419
+ callback(e);
1420
+ }
1421
+ }
1422
+ else {
1423
+ return Promise.resolve(fs.appendFileSync(path, data, options));
1424
+ }
1425
+ },
1426
+ readdir(path, options, callback) {
1427
+ if (typeof options === "function") {
1428
+ callback = options;
1429
+ options = undefined;
1430
+ }
1431
+ if (callback) {
1432
+ try {
1433
+ callback(null, fs.readdirSync(path, options));
1434
+ }
1435
+ catch (e) {
1436
+ callback(e);
1437
+ }
1438
+ }
1439
+ else {
1440
+ return Promise.resolve(fs.readdirSync(path, options));
1441
+ }
1442
+ },
1443
+ mkdir(path, options, callback) {
1444
+ if (typeof options === "function") {
1445
+ callback = options;
1446
+ options = undefined;
1447
+ }
1448
+ if (callback) {
1449
+ try {
1450
+ fs.mkdirSync(path, options);
1451
+ callback(null);
1452
+ }
1453
+ catch (e) {
1454
+ callback(e);
1455
+ }
1456
+ }
1457
+ else {
1458
+ fs.mkdirSync(path, options);
1459
+ return Promise.resolve();
1460
+ }
1461
+ },
1462
+ rmdir(path, callback) {
1463
+ if (callback) {
1464
+ // Defer callback to next tick to allow event loop to process stream events
1465
+ const cb = callback;
1466
+ try {
1467
+ fs.rmdirSync(path);
1468
+ queueMicrotask(() => cb(null));
1469
+ }
1470
+ catch (e) {
1471
+ queueMicrotask(() => cb(e));
1472
+ }
1473
+ }
1474
+ else {
1475
+ return Promise.resolve(fs.rmdirSync(path));
1476
+ }
1477
+ },
1478
+ // rm - remove files or directories (with recursive support)
1479
+ rm(path, options, callback) {
1480
+ let opts = {};
1481
+ let cb;
1482
+ if (typeof options === "function") {
1483
+ cb = options;
1484
+ }
1485
+ else if (options) {
1486
+ opts = options;
1487
+ cb = callback;
1488
+ }
1489
+ else {
1490
+ cb = callback;
1491
+ }
1492
+ const doRm = () => {
1493
+ try {
1494
+ const stats = fs.statSync(path);
1495
+ if (stats.isDirectory()) {
1496
+ if (opts.recursive) {
1497
+ // Recursively remove directory contents
1498
+ const entries = fs.readdirSync(path);
1499
+ for (const entry of entries) {
1500
+ const entryPath = path.endsWith("/") ? path + entry : path + "/" + entry;
1501
+ const entryStats = fs.statSync(entryPath);
1502
+ if (entryStats.isDirectory()) {
1503
+ fs.rmSync(entryPath, { recursive: true });
1504
+ }
1505
+ else {
1506
+ fs.unlinkSync(entryPath);
1507
+ }
1508
+ }
1509
+ fs.rmdirSync(path);
1510
+ }
1511
+ else {
1512
+ fs.rmdirSync(path);
1513
+ }
1514
+ }
1515
+ else {
1516
+ fs.unlinkSync(path);
1517
+ }
1518
+ }
1519
+ catch (e) {
1520
+ if (opts.force && e.code === "ENOENT") {
1521
+ return; // Ignore ENOENT when force is true
1522
+ }
1523
+ throw e;
1524
+ }
1525
+ };
1526
+ if (cb) {
1527
+ // Defer callback to next tick to allow event loop to process stream events
1528
+ try {
1529
+ doRm();
1530
+ queueMicrotask(() => cb(null));
1531
+ }
1532
+ catch (e) {
1533
+ queueMicrotask(() => cb(e));
1534
+ }
1535
+ }
1536
+ else {
1537
+ doRm();
1538
+ return Promise.resolve();
1539
+ }
1540
+ },
1541
+ exists(path, callback) {
1542
+ if (callback) {
1543
+ callback(fs.existsSync(path));
1544
+ }
1545
+ else {
1546
+ return Promise.resolve(fs.existsSync(path));
1547
+ }
1548
+ },
1549
+ stat(path, callback) {
1550
+ if (callback) {
1551
+ // Defer callback to next tick to allow event loop to process stream events
1552
+ const cb = callback;
1553
+ try {
1554
+ const stats = fs.statSync(path);
1555
+ queueMicrotask(() => cb(null, stats));
1556
+ }
1557
+ catch (e) {
1558
+ queueMicrotask(() => cb(e));
1559
+ }
1560
+ }
1561
+ else {
1562
+ return Promise.resolve(fs.statSync(path));
1563
+ }
1564
+ },
1565
+ lstat(path, callback) {
1566
+ if (callback) {
1567
+ // Defer callback to next tick to allow event loop to process stream events
1568
+ const cb = callback;
1569
+ try {
1570
+ const stats = fs.lstatSync(path);
1571
+ queueMicrotask(() => cb(null, stats));
1572
+ }
1573
+ catch (e) {
1574
+ queueMicrotask(() => cb(e));
1575
+ }
1576
+ }
1577
+ else {
1578
+ return Promise.resolve(fs.lstatSync(path));
1579
+ }
1580
+ },
1581
+ unlink(path, callback) {
1582
+ if (callback) {
1583
+ // Defer callback to next tick to allow event loop to process stream events
1584
+ const cb = callback;
1585
+ try {
1586
+ fs.unlinkSync(path);
1587
+ queueMicrotask(() => cb(null));
1588
+ }
1589
+ catch (e) {
1590
+ queueMicrotask(() => cb(e));
1591
+ }
1592
+ }
1593
+ else {
1594
+ return Promise.resolve(fs.unlinkSync(path));
1595
+ }
1596
+ },
1597
+ rename(oldPath, newPath, callback) {
1598
+ if (callback) {
1599
+ // Defer callback to next tick to allow event loop to process stream events
1600
+ const cb = callback;
1601
+ try {
1602
+ fs.renameSync(oldPath, newPath);
1603
+ queueMicrotask(() => cb(null));
1604
+ }
1605
+ catch (e) {
1606
+ queueMicrotask(() => cb(e));
1607
+ }
1608
+ }
1609
+ else {
1610
+ return Promise.resolve(fs.renameSync(oldPath, newPath));
1611
+ }
1612
+ },
1613
+ copyFile(src, dest, callback) {
1614
+ if (callback) {
1615
+ try {
1616
+ fs.copyFileSync(src, dest);
1617
+ callback(null);
1618
+ }
1619
+ catch (e) {
1620
+ callback(e);
1621
+ }
1622
+ }
1623
+ else {
1624
+ return Promise.resolve(fs.copyFileSync(src, dest));
1625
+ }
1626
+ },
1627
+ cp(src, dest, options, callback) {
1628
+ if (typeof options === "function") {
1629
+ callback = options;
1630
+ options = undefined;
1631
+ }
1632
+ if (callback) {
1633
+ try {
1634
+ fs.cpSync(src, dest, options);
1635
+ callback(null);
1636
+ }
1637
+ catch (e) {
1638
+ callback(e);
1639
+ }
1640
+ }
1641
+ else {
1642
+ return Promise.resolve(fs.cpSync(src, dest, options));
1643
+ }
1644
+ },
1645
+ mkdtemp(prefix, options, callback) {
1646
+ if (typeof options === "function") {
1647
+ callback = options;
1648
+ options = undefined;
1649
+ }
1650
+ if (callback) {
1651
+ try {
1652
+ callback(null, fs.mkdtempSync(prefix, options));
1653
+ }
1654
+ catch (e) {
1655
+ callback(e);
1656
+ }
1657
+ }
1658
+ else {
1659
+ return Promise.resolve(fs.mkdtempSync(prefix, options));
1660
+ }
1661
+ },
1662
+ opendir(path, options, callback) {
1663
+ if (typeof options === "function") {
1664
+ callback = options;
1665
+ options = undefined;
1666
+ }
1667
+ if (callback) {
1668
+ try {
1669
+ callback(null, fs.opendirSync(path, options));
1670
+ }
1671
+ catch (e) {
1672
+ callback(e);
1673
+ }
1674
+ }
1675
+ else {
1676
+ return Promise.resolve(fs.opendirSync(path, options));
1677
+ }
1678
+ },
1679
+ open(path, flags, mode, callback) {
1680
+ if (typeof mode === "function") {
1681
+ callback = mode;
1682
+ mode = undefined;
1683
+ }
1684
+ if (callback) {
1685
+ // Defer callback to next tick to allow event loop to process stream events
1686
+ const cb = callback;
1687
+ try {
1688
+ const fd = fs.openSync(path, flags, mode);
1689
+ queueMicrotask(() => cb(null, fd));
1690
+ }
1691
+ catch (e) {
1692
+ queueMicrotask(() => cb(e));
1693
+ }
1694
+ }
1695
+ else {
1696
+ return Promise.resolve(fs.openSync(path, flags, mode));
1697
+ }
1698
+ },
1699
+ close(fd, callback) {
1700
+ if (callback) {
1701
+ // Defer callback to next tick to allow event loop to process stream events
1702
+ const cb = callback;
1703
+ try {
1704
+ fs.closeSync(fd);
1705
+ queueMicrotask(() => cb(null));
1706
+ }
1707
+ catch (e) {
1708
+ queueMicrotask(() => cb(e));
1709
+ }
1710
+ }
1711
+ else {
1712
+ return Promise.resolve(fs.closeSync(fd));
1713
+ }
1714
+ },
1715
+ read(fd, buffer, offset, length, position, callback) {
1716
+ if (callback) {
1717
+ // Defer callback to next tick to allow event loop to process stream events
1718
+ const cb = callback;
1719
+ try {
1720
+ const bytesRead = fs.readSync(fd, buffer, offset, length, position);
1721
+ queueMicrotask(() => cb(null, bytesRead, buffer));
1722
+ }
1723
+ catch (e) {
1724
+ queueMicrotask(() => cb(e));
1725
+ }
1726
+ }
1727
+ else {
1728
+ return Promise.resolve(fs.readSync(fd, buffer, offset, length, position));
1729
+ }
1730
+ },
1731
+ write(fd, buffer, offset, length, position, callback) {
1732
+ if (typeof offset === "function") {
1733
+ callback = offset;
1734
+ offset = undefined;
1735
+ length = undefined;
1736
+ position = undefined;
1737
+ }
1738
+ else if (typeof length === "function") {
1739
+ callback = length;
1740
+ length = undefined;
1741
+ position = undefined;
1742
+ }
1743
+ else if (typeof position === "function") {
1744
+ callback = position;
1745
+ position = undefined;
1746
+ }
1747
+ if (callback) {
1748
+ // Defer callback to next tick to allow event loop to process stream events
1749
+ const cb = callback;
1750
+ try {
1751
+ const bytesWritten = fs.writeSync(fd, buffer, offset, length, position);
1752
+ queueMicrotask(() => cb(null, bytesWritten));
1753
+ }
1754
+ catch (e) {
1755
+ queueMicrotask(() => cb(e));
1756
+ }
1757
+ }
1758
+ else {
1759
+ return Promise.resolve(fs.writeSync(fd, buffer, offset, length, position));
1760
+ }
1761
+ },
1762
+ // writev - write multiple buffers to a file descriptor
1763
+ writev(fd, buffers, position, callback) {
1764
+ if (typeof position === "function") {
1765
+ callback = position;
1766
+ position = null;
1767
+ }
1768
+ if (callback) {
1769
+ try {
1770
+ const bytesWritten = fs.writevSync(fd, buffers, position);
1771
+ callback(null, bytesWritten, buffers);
1772
+ }
1773
+ catch (e) {
1774
+ callback(e);
1775
+ }
1776
+ }
1777
+ },
1778
+ writevSync(fd, buffers, position) {
1779
+ let totalBytesWritten = 0;
1780
+ for (const buffer of buffers) {
1781
+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1782
+ totalBytesWritten += fs.writeSync(fd, bytes, 0, bytes.length, position);
1783
+ if (position !== null && position !== undefined) {
1784
+ position += bytes.length;
1785
+ }
1786
+ }
1787
+ return totalBytesWritten;
1788
+ },
1789
+ fstat(fd, callback) {
1790
+ if (callback) {
1791
+ try {
1792
+ callback(null, fs.fstatSync(fd));
1793
+ }
1794
+ catch (e) {
1795
+ callback(e);
1796
+ }
1797
+ }
1798
+ else {
1799
+ return Promise.resolve(fs.fstatSync(fd));
1800
+ }
1801
+ },
1802
+ // fsync / fdatasync async callback forms
1803
+ fsync(fd, callback) {
1804
+ if (callback) {
1805
+ try {
1806
+ fs.fsyncSync(fd);
1807
+ callback(null);
1808
+ }
1809
+ catch (e) {
1810
+ callback(e);
1811
+ }
1812
+ }
1813
+ else {
1814
+ return Promise.resolve(fs.fsyncSync(fd));
1815
+ }
1816
+ },
1817
+ fdatasync(fd, callback) {
1818
+ if (callback) {
1819
+ try {
1820
+ fs.fdatasyncSync(fd);
1821
+ callback(null);
1822
+ }
1823
+ catch (e) {
1824
+ callback(e);
1825
+ }
1826
+ }
1827
+ else {
1828
+ return Promise.resolve(fs.fdatasyncSync(fd));
1829
+ }
1830
+ },
1831
+ // readv async callback form
1832
+ readv(fd, buffers, position, callback) {
1833
+ if (typeof position === "function") {
1834
+ callback = position;
1835
+ position = null;
1836
+ }
1837
+ if (callback) {
1838
+ try {
1839
+ const bytesRead = fs.readvSync(fd, buffers, position);
1840
+ callback(null, bytesRead, buffers);
1841
+ }
1842
+ catch (e) {
1843
+ callback(e);
1844
+ }
1845
+ }
1846
+ },
1847
+ // statfs async callback form
1848
+ statfs(path, options, callback) {
1849
+ if (typeof options === "function") {
1850
+ callback = options;
1851
+ options = undefined;
1852
+ }
1853
+ if (callback) {
1854
+ try {
1855
+ callback(null, fs.statfsSync(path, options));
1856
+ }
1857
+ catch (e) {
1858
+ callback(e);
1859
+ }
1860
+ }
1861
+ else {
1862
+ return Promise.resolve(fs.statfsSync(path, options));
1863
+ }
1864
+ },
1865
+ // glob async callback form
1866
+ glob(pattern, options, callback) {
1867
+ if (typeof options === "function") {
1868
+ callback = options;
1869
+ options = undefined;
1870
+ }
1871
+ if (callback) {
1872
+ try {
1873
+ callback(null, fs.globSync(pattern, options));
1874
+ }
1875
+ catch (e) {
1876
+ callback(e);
1877
+ }
1878
+ }
1879
+ },
1880
+ // fs.promises API
1881
+ // Note: Using async functions to properly catch sync errors and return rejected promises
1882
+ promises: {
1883
+ async readFile(path, options) {
1884
+ return fs.readFileSync(path, options);
1885
+ },
1886
+ async writeFile(path, data, options) {
1887
+ return fs.writeFileSync(path, data, options);
1888
+ },
1889
+ async appendFile(path, data, options) {
1890
+ return fs.appendFileSync(path, data, options);
1891
+ },
1892
+ async readdir(path, options) {
1893
+ return fs.readdirSync(path, options);
1894
+ },
1895
+ async mkdir(path, options) {
1896
+ return fs.mkdirSync(path, options);
1897
+ },
1898
+ async rmdir(path) {
1899
+ return fs.rmdirSync(path);
1900
+ },
1901
+ async stat(path) {
1902
+ return fs.statSync(path);
1903
+ },
1904
+ async lstat(path) {
1905
+ return fs.lstatSync(path);
1906
+ },
1907
+ async unlink(path) {
1908
+ return fs.unlinkSync(path);
1909
+ },
1910
+ async rename(oldPath, newPath) {
1911
+ return fs.renameSync(oldPath, newPath);
1912
+ },
1913
+ async copyFile(src, dest) {
1914
+ return fs.copyFileSync(src, dest);
1915
+ },
1916
+ async cp(src, dest, options) {
1917
+ return fs.cpSync(src, dest, options);
1918
+ },
1919
+ async mkdtemp(prefix, options) {
1920
+ return fs.mkdtempSync(prefix, options);
1921
+ },
1922
+ async opendir(path, options) {
1923
+ return fs.opendirSync(path, options);
1924
+ },
1925
+ async statfs(path, options) {
1926
+ return fs.statfsSync(path, options);
1927
+ },
1928
+ async glob(pattern, _options) {
1929
+ return fs.globSync(pattern, _options);
1930
+ },
1931
+ async access(path) {
1932
+ if (!fs.existsSync(path)) {
1933
+ throw createFsError("ENOENT", `ENOENT: no such file or directory, access '${path}'`, "access", path);
1934
+ }
1935
+ },
1936
+ async rm(path, options) {
1937
+ return fs.rmSync(path, options);
1938
+ },
1939
+ async chmod(path, mode) {
1940
+ return fs.chmodSync(path, mode);
1941
+ },
1942
+ async chown(path, uid, gid) {
1943
+ return fs.chownSync(path, uid, gid);
1944
+ },
1945
+ async link(existingPath, newPath) {
1946
+ return fs.linkSync(existingPath, newPath);
1947
+ },
1948
+ async symlink(target, path) {
1949
+ return fs.symlinkSync(target, path);
1950
+ },
1951
+ async readlink(path) {
1952
+ return fs.readlinkSync(path);
1953
+ },
1954
+ async truncate(path, len) {
1955
+ return fs.truncateSync(path, len);
1956
+ },
1957
+ async utimes(path, atime, mtime) {
1958
+ return fs.utimesSync(path, atime, mtime);
1959
+ },
1960
+ },
1961
+ // Compatibility methods
1962
+ accessSync(path) {
1963
+ // existsSync already normalizes the path
1964
+ if (!fs.existsSync(path)) {
1965
+ throw createFsError("ENOENT", `ENOENT: no such file or directory, access '${path}'`, "access", path);
1966
+ }
1967
+ },
1968
+ access(path, mode, callback) {
1969
+ if (typeof mode === "function") {
1970
+ callback = mode;
1971
+ mode = undefined;
1972
+ }
1973
+ if (callback) {
1974
+ try {
1975
+ fs.accessSync(path);
1976
+ callback(null);
1977
+ }
1978
+ catch (e) {
1979
+ callback(e);
1980
+ }
1981
+ }
1982
+ else {
1983
+ return fs.promises.access(path);
1984
+ }
1985
+ },
1986
+ realpathSync: Object.assign(function realpathSync(path) {
1987
+ // In our virtual fs, just normalize the path (keep /data prefix for consistency)
1988
+ return toPathString(path)
1989
+ .replace(/\/\/+/g, "/")
1990
+ .replace(/\/$/, "") || "/";
1991
+ }, {
1992
+ native(path) {
1993
+ return toPathString(path)
1994
+ .replace(/\/\/+/g, "/")
1995
+ .replace(/\/$/, "") || "/";
1996
+ }
1997
+ }),
1998
+ realpath: Object.assign(function realpath(path, callback) {
1999
+ if (callback) {
2000
+ callback(null, fs.realpathSync(path));
2001
+ }
2002
+ else {
2003
+ return Promise.resolve(fs.realpathSync(path));
2004
+ }
2005
+ }, {
2006
+ native(path, callback) {
2007
+ if (callback) {
2008
+ callback(null, fs.realpathSync.native(path));
2009
+ }
2010
+ else {
2011
+ return Promise.resolve(fs.realpathSync.native(path));
2012
+ }
2013
+ }
2014
+ }),
2015
+ createReadStream(path, options) {
2016
+ const pathStr = typeof path === "string" ? path : path instanceof Buffer ? path.toString() : String(path);
2017
+ const opts = typeof options === "string" ? { encoding: options } : options;
2018
+ // Use type assertion since our ReadStream has all the methods npm needs
2019
+ // but not all the complex overloaded signatures of the full Node.js interface
2020
+ return new ReadStream(pathStr, opts);
2021
+ },
2022
+ createWriteStream(path, options) {
2023
+ const pathStr = typeof path === "string" ? path : path instanceof Buffer ? path.toString() : String(path);
2024
+ const opts = typeof options === "string" ? { encoding: options } : options;
2025
+ // Use type assertion since our WriteStream has all the methods npm needs
2026
+ // but not all the complex overloaded signatures of the full Node.js interface
2027
+ return new WriteStream(pathStr, opts);
2028
+ },
2029
+ // Unsupported fs APIs — watch requires kernel-level inotify, use polling instead
2030
+ watch(..._args) {
2031
+ throw new Error("fs.watch is not supported in sandbox — use polling");
2032
+ },
2033
+ watchFile(..._args) {
2034
+ throw new Error("fs.watchFile is not supported in sandbox — use polling");
2035
+ },
2036
+ unwatchFile(..._args) {
2037
+ throw new Error("fs.unwatchFile is not supported in sandbox — use polling");
2038
+ },
2039
+ chmod(path, mode, callback) {
2040
+ if (callback) {
2041
+ try {
2042
+ fs.chmodSync(path, mode);
2043
+ callback(null);
2044
+ }
2045
+ catch (e) {
2046
+ callback(e);
2047
+ }
2048
+ }
2049
+ else {
2050
+ return Promise.resolve(fs.chmodSync(path, mode));
2051
+ }
2052
+ },
2053
+ chown(path, uid, gid, callback) {
2054
+ if (callback) {
2055
+ try {
2056
+ fs.chownSync(path, uid, gid);
2057
+ callback(null);
2058
+ }
2059
+ catch (e) {
2060
+ callback(e);
2061
+ }
2062
+ }
2063
+ else {
2064
+ return Promise.resolve(fs.chownSync(path, uid, gid));
2065
+ }
2066
+ },
2067
+ link(existingPath, newPath, callback) {
2068
+ if (callback) {
2069
+ try {
2070
+ fs.linkSync(existingPath, newPath);
2071
+ callback(null);
2072
+ }
2073
+ catch (e) {
2074
+ callback(e);
2075
+ }
2076
+ }
2077
+ else {
2078
+ return Promise.resolve(fs.linkSync(existingPath, newPath));
2079
+ }
2080
+ },
2081
+ symlink(target, path, typeOrCb, callback) {
2082
+ if (typeof typeOrCb === "function") {
2083
+ callback = typeOrCb;
2084
+ }
2085
+ if (callback) {
2086
+ try {
2087
+ fs.symlinkSync(target, path);
2088
+ callback(null);
2089
+ }
2090
+ catch (e) {
2091
+ callback(e);
2092
+ }
2093
+ }
2094
+ else {
2095
+ return Promise.resolve(fs.symlinkSync(target, path));
2096
+ }
2097
+ },
2098
+ readlink(path, optionsOrCb, callback) {
2099
+ if (typeof optionsOrCb === "function") {
2100
+ callback = optionsOrCb;
2101
+ }
2102
+ if (callback) {
2103
+ try {
2104
+ callback(null, fs.readlinkSync(path));
2105
+ }
2106
+ catch (e) {
2107
+ callback(e);
2108
+ }
2109
+ }
2110
+ else {
2111
+ return Promise.resolve(fs.readlinkSync(path));
2112
+ }
2113
+ },
2114
+ truncate(path, lenOrCb, callback) {
2115
+ if (typeof lenOrCb === "function") {
2116
+ callback = lenOrCb;
2117
+ lenOrCb = 0;
2118
+ }
2119
+ if (callback) {
2120
+ try {
2121
+ fs.truncateSync(path, lenOrCb);
2122
+ callback(null);
2123
+ }
2124
+ catch (e) {
2125
+ callback(e);
2126
+ }
2127
+ }
2128
+ else {
2129
+ return Promise.resolve(fs.truncateSync(path, lenOrCb));
2130
+ }
2131
+ },
2132
+ utimes(path, atime, mtime, callback) {
2133
+ if (callback) {
2134
+ try {
2135
+ fs.utimesSync(path, atime, mtime);
2136
+ callback(null);
2137
+ }
2138
+ catch (e) {
2139
+ callback(e);
2140
+ }
2141
+ }
2142
+ else {
2143
+ return Promise.resolve(fs.utimesSync(path, atime, mtime));
2144
+ }
2145
+ },
2146
+ };
2147
+ // Wire late-bound glob helpers to the fs object
2148
+ _globReadDir = (dir) => fs.readdirSync(dir);
2149
+ _globStat = (path) => fs.statSync(path);
2150
+ // Export the fs module
2151
+ export default fs;