This repository has been archived by the owner on Jan 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathbootstrap.js
1573 lines (1341 loc) · 48.1 KB
/
bootstrap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable curly */
/* eslint-disable new-cap */
/* eslint-disable no-buffer-constructor */
/* eslint-disable no-multi-spaces */
/* eslint-disable no-underscore-dangle */
/* eslint-disable prefer-rest-params */
/* eslint-disable prefer-spread */
/* global EXECPATH_FD */
/* global PAYLOAD_POSITION */
/* global PAYLOAD_SIZE */
/* global REQUIRE_COMMON */
/* global VIRTUAL_FILESYSTEM */
/* global DEFAULT_ENTRYPOINT */
'use strict';
var common = {};
REQUIRE_COMMON(common);
var STORE_BLOB = common.STORE_BLOB;
var STORE_CONTENT = common.STORE_CONTENT;
var STORE_LINKS = common.STORE_LINKS;
var STORE_STAT = common.STORE_STAT;
var isRootPath = common.isRootPath;
var normalizePath = common.normalizePath;
var insideSnapshot = common.insideSnapshot;
var stripSnapshot = common.stripSnapshot;
var removeUplevels = common.removeUplevels;
var FLAG_ENABLE_PROJECT = false;
var NODE_VERSION_MAJOR = process.version.match(/^v(\d+)/)[1] | 0;
// /////////////////////////////////////////////////////////////////
// ENTRYPOINT //////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
// set ENTRYPOINT and ARGV0 here because
// they can be altered during process run
var ARGV0 = process.argv[0];
var EXECPATH = process.execPath;
var ENTRYPOINT = process.argv[1];
if (process.env.PKG_EXECPATH === 'PKG_INVOKE_NODEJS') {
return { undoPatch: true };
}
if (NODE_VERSION_MAJOR < 12 || require('worker_threads').isMainThread) {
if (process.argv[1] !== 'PKG_DUMMY_ENTRYPOINT') {
// expand once patchless is introduced, that
// will obviously lack any work in node_main.cc
throw new Error('PKG_DUMMY_ENTRYPOINT EXPECTED');
}
}
if (process.env.PKG_EXECPATH === EXECPATH) {
process.argv.splice(1, 1);
if (process.argv[1] && process.argv[1] !== '-') {
// https://github.com/nodejs/node/blob/1a96d83a223ff9f05f7d942fb84440d323f7b596/lib/internal/bootstrap/node.js#L269
process.argv[1] = require('path').resolve(process.argv[1]);
}
} else {
process.argv[1] = DEFAULT_ENTRYPOINT;
}
ENTRYPOINT = process.argv[1];
delete process.env.PKG_EXECPATH;
// /////////////////////////////////////////////////////////////////
// EXECSTAT ////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
var EXECSTAT = require('fs').statSync(EXECPATH);
EXECSTAT.atimeMs = EXECSTAT.atime.getTime();
EXECSTAT.mtimeMs = EXECSTAT.mtime.getTime();
EXECSTAT.ctimeMs = EXECSTAT.ctime.getTime();
EXECSTAT.birthtimeMs = EXECSTAT.birthtime.getTime();
// /////////////////////////////////////////////////////////////////
// MOUNTPOINTS /////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
var mountpoints = [];
function insideMountpoint (f) {
if (!insideSnapshot(f)) return null;
var file = normalizePath(f);
var found = mountpoints.map(function (mountpoint) {
var interior = mountpoint.interior;
var exterior = mountpoint.exterior;
if (interior === file) return exterior;
var left = interior + require('path').sep;
if (file.slice(0, left.length) !== left) return null;
return exterior + file.slice(left.length - 1);
}).filter(function (result) {
return result;
});
if (found.length >= 2) throw new Error('UNEXPECTED-00');
if (found.length === 0) return null;
return found[0];
}
function readdirMountpoints (path) {
return mountpoints.map(function (mountpoint) {
return mountpoint.interior;
}).filter(function (interior) {
return require('path').dirname(interior) === path;
}).map(function (interior) {
return require('path').basename(interior);
});
}
function translate (f) {
var result = insideMountpoint(f);
if (!result) throw new Error('UNEXPECTED-05');
return result;
}
function cloneArgs (args_) {
return Array.prototype.slice.call(args_);
}
function translateNth (args_, index, f) {
var args = cloneArgs(args_);
args[index] = translate(f);
return args;
}
function createMountpoint (interior, exterior) {
// TODO validate
mountpoints.push({ interior: interior, exterior: exterior });
}
/*
// TODO move to some test
createMountpoint("d:\\snapshot\\countly\\plugins-ext", "d:\\deploy\\countly\\v16.02\\plugins-ext");
console.log(insideMountpoint("d:\\snapshot"));
console.log(insideMountpoint("d:\\snapshot\\"));
console.log(insideMountpoint("d:\\snapshot\\countly"));
console.log(insideMountpoint("d:\\snapshot\\countly\\"));
console.log(insideMountpoint("d:\\snapshot\\countly\\plugins-ext"));
console.log(insideMountpoint("d:\\snapshot\\countly\\plugins-ext\\"));
console.log(insideMountpoint("d:\\snapshot\\countly\\plugins-ext\\1234"));
console.log(translate("d:\\snapshot\\countly\\plugins-ext"));
console.log(translate("d:\\snapshot\\countly\\plugins-ext\\"));
console.log(translate("d:\\snapshot\\countly\\plugins-ext\\1234"));
console.log(translateNth([], 0, "d:\\snapshot\\countly\\plugins-ext"));
console.log(translateNth([], 0, "d:\\snapshot\\countly\\plugins-ext\\"));
console.log(translateNth([], 0, "d:\\snapshot\\countly\\plugins-ext\\1234"));
console.log(translateNth(["", "r+"], 0, "d:\\snapshot\\countly\\plugins-ext"));
console.log(translateNth(["", "rw"], 0, "d:\\snapshot\\countly\\plugins-ext\\"));
console.log(translateNth(["", "a+"], 0, "d:\\snapshot\\countly\\plugins-ext\\1234"));
*/
// /////////////////////////////////////////////////////////////////
// PROJECT /////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
function projectToFilesystem (f) {
var xpdn = require('path').dirname(
EXECPATH
);
var relatives = [];
relatives.push(
removeUplevels(
require('path').relative(
require('path').dirname(
DEFAULT_ENTRYPOINT
), f
)
)
);
if (relatives[0].slice(0, 'node_modules'.length) === 'node_modules') {
// one more relative without starting 'node_modules'
relatives.push(relatives[0].slice('node_modules'.length + 1));
}
var uplevels = [];
var maxUplevels = xpdn.split(require('path').sep).length;
for (var i = 0, u = ''; i < maxUplevels; i += 1) {
uplevels.push(u);
u += '/..';
}
var results = [];
uplevels.forEach(function (uplevel) {
relatives.forEach(function (relative) {
results.push(require('path').join(
xpdn,
uplevel,
relative
));
});
});
return results;
}
function projectToNearby (f) {
return require('path').join(
require('path').dirname(
EXECPATH
),
require('path').basename(
f
)
);
}
function findNativeAddonSyncFreeFromRequire (path) {
if (!insideSnapshot(path)) throw new Error('UNEXPECTED-10');
if (path.slice(-5) !== '.node') return null; // leveldown.node.js
// check mearby first to prevent .node tampering
var projector = projectToNearby(path);
if (require('fs').existsSync(projector)) return projector;
var projectors = projectToFilesystem(path);
for (var i = 0; i < projectors.length; i += 1) {
if (require('fs').existsSync(projectors[i])) return projectors[i];
}
return null;
}
function findNativeAddonSyncUnderRequire (path) {
if (!FLAG_ENABLE_PROJECT) return null;
return findNativeAddonSyncFreeFromRequire(path);
}
// /////////////////////////////////////////////////////////////////
// FLOW UTILS //////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
function asap (cb) {
process.nextTick(cb);
}
function dezalgo (cb) {
if (!cb) return cb;
var sync = true;
asap(function () {
sync = false;
});
return function zalgoSafe () {
var args = arguments;
if (sync) {
asap(function () {
cb.apply(undefined, args);
});
} else {
cb.apply(undefined, args);
}
};
}
function rethrow (error, arg) {
if (error) throw error;
return arg;
}
// /////////////////////////////////////////////////////////////////
// PAYLOAD /////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
if (typeof PAYLOAD_POSITION !== 'number' ||
typeof PAYLOAD_SIZE !== 'number') {
throw new Error('MUST HAVE PAYLOAD');
}
var readPayload = function (buffer, offset, length, position, callback) {
require('fs').read(EXECPATH_FD,
buffer, offset, length, PAYLOAD_POSITION + position, callback);
};
var readPayloadSync = function (buffer, offset, length, position) {
return require('fs').readSync(EXECPATH_FD,
buffer, offset, length, PAYLOAD_POSITION + position);
};
function payloadCopyUni (source, target, targetStart, sourceStart, sourceEnd, cb) {
var cb2 = cb || rethrow;
if (sourceStart >= source[1]) return cb2(null, 0);
if (sourceEnd >= source[1]) sourceEnd = source[1];
var payloadPos = source[0] + sourceStart;
var targetPos = targetStart;
var targetEnd = targetStart + sourceEnd - sourceStart;
if (cb) {
readPayload(target, targetPos, targetEnd - targetPos, payloadPos, cb);
} else {
return readPayloadSync(target, targetPos, targetEnd - targetPos, payloadPos);
}
}
function payloadCopyMany (source, target, targetStart, sourceStart, cb) {
var payloadPos = source[0] + sourceStart;
var targetPos = targetStart;
var targetEnd = targetStart + source[1] - sourceStart;
readPayload(target, targetPos, targetEnd - targetPos, payloadPos, function (error, chunkSize) {
if (error) return cb(error);
sourceStart += chunkSize;
targetPos += chunkSize;
if (chunkSize !== 0 && targetPos < targetEnd) {
payloadCopyMany(source, target, targetPos, sourceStart, cb);
} else {
return cb();
}
});
}
function payloadCopyManySync (source, target, targetStart, sourceStart) {
var payloadPos = source[0] + sourceStart;
var targetPos = targetStart;
var targetEnd = targetStart + source[1] - sourceStart;
var chunkSize;
while (true) {
chunkSize = readPayloadSync(target, targetPos, targetEnd - targetPos, payloadPos);
payloadPos += chunkSize;
targetPos += chunkSize;
if (!(chunkSize !== 0 && targetPos < targetEnd)) break;
}
}
function payloadFile (pointer, cb) {
var target = Buffer.alloc(pointer[1]);
payloadCopyMany(pointer, target, 0, 0, function (error) {
if (error) return cb(error);
cb(null, target);
});
}
function payloadFileSync (pointer) {
var target = Buffer.alloc(pointer[1]);
payloadCopyManySync(pointer, target, 0, 0);
return target;
}
// /////////////////////////////////////////////////////////////////
// SETUP PROCESS ///////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
(function () {
process.pkg = {};
process.versions.pkg = '%VERSION%';
process.pkg.mount = createMountpoint;
process.pkg.entrypoint = ENTRYPOINT;
process.pkg.defaultEntrypoint = DEFAULT_ENTRYPOINT;
}());
// /////////////////////////////////////////////////////////////////
// PATH.RESOLVE REPLACEMENT ////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
(function () {
var path = require('path');
process.pkg.path = {};
process.pkg.path.resolve = function () {
var args = cloneArgs(arguments);
args.unshift(path.dirname(ENTRYPOINT));
return path.resolve.apply(path, args); // eslint-disable-line prefer-spread
};
}());
// /////////////////////////////////////////////////////////////////
// PATCH FS ////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
(function () {
var fs = require('fs');
var ancestor = {};
ancestor.openSync = fs.openSync;
ancestor.open = fs.open;
ancestor.readSync = fs.readSync;
ancestor.read = fs.read;
ancestor.writeSync = fs.writeSync;
ancestor.write = fs.write;
ancestor.closeSync = fs.closeSync;
ancestor.close = fs.close;
ancestor.readFileSync = fs.readFileSync;
ancestor.readFile = fs.readFile;
// ancestor.writeFileSync = fs.writeFileSync; // based on openSync/writeSync/closeSync
// ancestor.writeFile = fs.writeFile; // based on open/write/close
ancestor.readdirSync = fs.readdirSync;
ancestor.readdir = fs.readdir;
ancestor.realpathSync = fs.realpathSync;
ancestor.realpath = fs.realpath;
ancestor.statSync = fs.statSync;
ancestor.stat = fs.stat;
ancestor.lstatSync = fs.lstatSync;
ancestor.lstat = fs.lstat;
ancestor.fstatSync = fs.fstatSync;
ancestor.fstat = fs.fstat;
ancestor.existsSync = fs.existsSync;
ancestor.exists = fs.exists;
ancestor.accessSync = fs.accessSync;
ancestor.access = fs.access;
var windows = process.platform === 'win32';
var docks = {};
var ENOTDIR = windows ? 4052 : 20;
var ENOENT = windows ? 4058 : 2;
var EISDIR = windows ? 4068 : 21;
function assertEncoding (encoding) {
if (encoding && !Buffer.isEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
function maybeCallback (args) {
var cb = args[args.length - 1];
return typeof cb === 'function' ? cb : rethrow;
}
function error_ENOENT (fileOrDirectory, path) { // eslint-disable-line camelcase
var error = new Error(
fileOrDirectory + ' \'' + stripSnapshot(path) + '\' ' +
'was not included into executable at compilation stage. ' +
'Please recompile adding it as asset or script.'
);
error.errno = -ENOENT;
error.code = 'ENOENT';
error.path = path;
error.pkg = true;
return error;
}
function error_EISDIR (path) { // eslint-disable-line camelcase
var error = new Error(
'EISDIR: illegal operation on a directory, read'
);
error.errno = -EISDIR;
error.code = 'EISDIR';
error.path = path;
error.pkg = true;
return error;
}
function error_ENOTDIR (path) { // eslint-disable-line camelcase
var error = new Error(
'ENOTDIR: not a directory, scandir \'' + path + '\''
);
error.errno = -ENOTDIR;
error.code = 'ENOTDIR';
error.path = path;
error.pkg = true;
return error;
}
// ///////////////////////////////////////////////////////////////
// open //////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
function openFromSnapshot (path_, cb) {
var cb2 = cb || rethrow;
var path = normalizePath(path_);
// console.log("openFromSnapshot", path);
var entity = VIRTUAL_FILESYSTEM[path];
if (!entity) return cb2(error_ENOENT('File or directory', path));
var dock = { path: path, entity: entity, position: 0 };
var nullDevice = windows ? '\\\\.\\NUL' : '/dev/null';
if (cb) {
ancestor.open.call(fs, nullDevice, 'r', function (error, fd) {
if (error) return cb(error);
docks[fd] = dock;
cb(null, fd);
});
} else {
var fd = ancestor.openSync.call(fs, nullDevice, 'r');
docks[fd] = dock;
return fd;
}
}
fs.openSync = function (path) {
if (!insideSnapshot(path)) {
return ancestor.openSync.apply(fs, arguments);
}
if (insideMountpoint(path)) {
return ancestor.openSync.apply(fs, translateNth(arguments, 0, path));
}
return openFromSnapshot(path);
};
fs.open = function (path) {
if (!insideSnapshot(path)) {
return ancestor.open.apply(fs, arguments);
}
if (insideMountpoint(path)) {
return ancestor.open.apply(fs, translateNth(arguments, 0, path));
}
var callback = dezalgo(maybeCallback(arguments));
openFromSnapshot(path, callback);
};
// ///////////////////////////////////////////////////////////////
// read //////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
function readFromSnapshotSub (entityContent, dock, buffer, offset, length, position, cb) {
var p;
if ((position !== null) && (position !== undefined)) {
p = position;
} else {
p = dock.position;
}
if (cb) {
payloadCopyUni(entityContent, buffer, offset, p, p + length, function (error, bytesRead, buffer2) {
if (error) return cb(error);
dock.position = p + bytesRead;
cb(null, bytesRead, buffer2);
});
} else {
var bytesRead = payloadCopyUni(entityContent, buffer, offset, p, p + length);
dock.position = p + bytesRead;
return bytesRead;
}
}
function readFromSnapshot (fd, buffer, offset, length, position, cb) {
var cb2 = cb || rethrow;
if ((offset < 0) && (NODE_VERSION_MAJOR >= 10)) return cb2(new Error(
'The value of "offset" is out of range. It must be >= 0 && <= ' + buffer.length.toString() + '. Received ' + offset));
if (offset < 0) return cb2(new Error('Offset is out of bounds'));
if ((offset >= buffer.length) && (NODE_VERSION_MAJOR >= 6)) return cb2(null, 0);
if (offset >= buffer.length) return cb2(new Error('Offset is out of bounds'));
if ((offset + length > buffer.length) && (NODE_VERSION_MAJOR >= 10)) return cb2(new Error(
'The value of "length" is out of range. It must be >= 0 && <= ' + (buffer.length - offset).toString() + '. Received ' + length.toString()));
if (offset + length > buffer.length) return cb2(new Error('Length extends beyond buffer'));
var dock = docks[fd];
var entity = dock.entity;
var entityLinks = entity[STORE_LINKS];
if (entityLinks) return cb2(error_EISDIR(dock.path));
var entityContent = entity[STORE_CONTENT];
if (entityContent) return readFromSnapshotSub(entityContent, dock, buffer, offset, length, position, cb);
return cb2(new Error('UNEXPECTED-15'));
}
fs.readSync = function (fd, buffer, offset, length, position) {
if (!docks[fd]) {
return ancestor.readSync.apply(fs, arguments);
}
return readFromSnapshot(fd, buffer, offset, length, position);
};
fs.read = function (fd, buffer, offset, length, position) {
if (!docks[fd]) {
return ancestor.read.apply(fs, arguments);
}
var callback = dezalgo(maybeCallback(arguments));
readFromSnapshot(fd, buffer, offset, length, position, callback);
};
// ///////////////////////////////////////////////////////////////
// write /////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
function writeToSnapshot (cb) {
var cb2 = cb || rethrow;
return cb2(new Error('Cannot write to packaged file'));
}
fs.writeSync = function (fd) {
if (!docks[fd]) {
return ancestor.writeSync.apply(fs, arguments);
}
return writeToSnapshot();
};
fs.write = function (fd) {
if (!docks[fd]) {
return ancestor.write.apply(fs, arguments);
}
var callback = dezalgo(maybeCallback(arguments));
writeToSnapshot(callback);
};
// ///////////////////////////////////////////////////////////////
// close /////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
function closeFromSnapshot (fd, cb) {
delete docks[fd];
if (cb) {
ancestor.close.call(fs, fd, cb);
} else {
return ancestor.closeSync.call(fs, fd);
}
}
fs.closeSync = function (fd) {
if (!docks[fd]) {
return ancestor.closeSync.apply(fs, arguments);
}
return closeFromSnapshot(fd);
};
fs.close = function (fd) {
if (!docks[fd]) {
return ancestor.close.apply(fs, arguments);
}
var callback = dezalgo(maybeCallback(arguments));
closeFromSnapshot(fd, callback);
};
// ///////////////////////////////////////////////////////////////
// readFile //////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
function readFileOptions (options, hasCallback) {
if (!options || (hasCallback && typeof options === 'function')) {
return { encoding: null, flag: 'r' };
} else if (typeof options === 'string') {
return { encoding: options, flag: 'r' };
} else if (typeof options === 'object') {
return options;
} else {
return null;
}
}
function readFileFromSnapshotSub (entityContent, cb) {
if (cb) {
payloadFile(entityContent, cb);
} else {
return payloadFileSync(entityContent);
}
}
function readFileFromSnapshot (path_, cb) {
var cb2 = cb || rethrow;
var path = normalizePath(path_);
// console.log("readFileFromSnapshot", path);
var entity = VIRTUAL_FILESYSTEM[path];
if (!entity) return cb2(error_ENOENT('File', path));
var entityLinks = entity[STORE_LINKS];
if (entityLinks) return cb2(error_EISDIR(path));
var entityContent = entity[STORE_CONTENT];
if (entityContent) return readFileFromSnapshotSub(entityContent, cb);
var entityBlob = entity[STORE_BLOB];
if (entityBlob) return cb2(null, Buffer.from('source-code-not-available'));
// why return empty buffer?
// otherwise this error will arise:
// Error: UNEXPECTED-20
// at readFileFromSnapshot (e:0)
// at Object.fs.readFileSync (e:0)
// at Object.Module._extensions..js (module.js:421:20)
// at Module.load (module.js:357:32)
// at Function.Module._load (module.js:314:12)
// at Function.Module.runMain (e:0)
// at startup (node.js:140:18)
// at node.js:1001:3
return cb2(new Error('UNEXPECTED-20'));
}
fs.readFileSync = function (path, options_) {
if (path === 'dirty-hack-for-testing-purposes') {
return path;
}
if (!insideSnapshot(path)) {
return ancestor.readFileSync.apply(fs, arguments);
}
if (insideMountpoint(path)) {
return ancestor.readFileSync.apply(fs, translateNth(arguments, 0, path));
}
var options = readFileOptions(options_, false);
if (!options) {
return ancestor.readFileSync.apply(fs, arguments);
}
var encoding = options.encoding;
assertEncoding(encoding);
var buffer = readFileFromSnapshot(path);
if (encoding) buffer = buffer.toString(encoding);
return buffer;
};
fs.readFile = function (path, options_) {
if (!insideSnapshot(path)) {
return ancestor.readFile.apply(fs, arguments);
}
if (insideMountpoint(path)) {
return ancestor.readFile.apply(fs, translateNth(arguments, 0, path));
}
var options = readFileOptions(options_, true);
if (!options) {
return ancestor.readFile.apply(fs, arguments);
}
var encoding = options.encoding;
assertEncoding(encoding);
var callback = dezalgo(maybeCallback(arguments));
readFileFromSnapshot(path, function (error, buffer) {
if (error) return callback(error);
if (encoding) buffer = buffer.toString(encoding);
callback(null, buffer);
});
};
// ///////////////////////////////////////////////////////////////
// writeFile /////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
// writeFileSync based on openSync/writeSync/closeSync
// writeFile based on open/write/close
// ///////////////////////////////////////////////////////////////
// readdir ///////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
function readdirOptions (options, hasCallback) {
if (!options || (hasCallback && typeof options === 'function')) {
return { encoding: null };
} else if (typeof options === 'string') {
return { encoding: options };
} else if (typeof options === 'object') {
return options;
} else {
return null;
}
}
function Dirent (name, type) {
this.name = name;
this.type = type;
}
Dirent.prototype.isDirectory = function () {
return this.type === 2;
};
Dirent.prototype.isFile = function () {
return this.type === 1;
};
Dirent.prototype.isBlockDevice =
Dirent.prototype.isCharacterDevice =
Dirent.prototype.isSymbolicLink =
Dirent.prototype.isFIFO =
Dirent.prototype.isSocket = function () {
return false;
};
function getFileTypes (path_, entries) {
return entries.map(function (entry) {
var path = require('path').join(path_, entry);
var entity = VIRTUAL_FILESYSTEM[path];
if (entity[STORE_BLOB] || entity[STORE_CONTENT]) return new Dirent(entry, 1);
if (entity[STORE_LINKS]) return new Dirent(entry, 2);
throw new Error('UNEXPECTED-24');
});
}
function readdirRoot (path, cb) {
if (cb) {
ancestor.readdir(path, function (error, entries) {
if (error) return cb(error);
entries.push('snapshot');
cb(null, entries);
});
} else {
var entries = ancestor.readdirSync(path);
entries.push('snapshot');
return entries;
}
}
function readdirFromSnapshotSub (entityLinks, path, cb) {
if (cb) {
payloadFile(entityLinks, function (error, buffer) {
if (error) return cb(error);
cb(null, JSON.parse(buffer).concat(readdirMountpoints(path)));
});
} else {
var buffer = payloadFileSync(entityLinks);
return JSON.parse(buffer).concat(readdirMountpoints(path));
}
}
function readdirFromSnapshot (path_, isRoot, cb) {
var cb2 = cb || rethrow;
if (isRoot) return readdirRoot(path_, cb);
var path = normalizePath(path_);
// console.log("readdirFromSnapshot", path);
var entity = VIRTUAL_FILESYSTEM[path];
if (!entity) return cb2(error_ENOENT('Directory', path));
var entityBlob = entity[STORE_BLOB];
if (entityBlob) return cb2(error_ENOTDIR(path));
var entityContent = entity[STORE_CONTENT];
if (entityContent) return cb2(error_ENOTDIR(path));
var entityLinks = entity[STORE_LINKS];
if (entityLinks) return readdirFromSnapshotSub(entityLinks, path, cb);
return cb2(new Error('UNEXPECTED-25'));
}
fs.readdirSync = function (path, options_) {
var isRoot = isRootPath(path);
if (!insideSnapshot(path) && !isRoot) {
return ancestor.readdirSync.apply(fs, arguments);
}
if (insideMountpoint(path)) {
return ancestor.readdirSync.apply(fs, translateNth(arguments, 0, path));
}
var options = readdirOptions(options_, false);
if (!options) {
return ancestor.readdirSync.apply(fs, arguments);
}
var entries = readdirFromSnapshot(path, isRoot);
if (options.withFileTypes) entries = getFileTypes(path, entries);
return entries;
};
fs.readdir = function (path, options_) {
var isRoot = isRootPath(path);
if (!insideSnapshot(path) && !isRoot) {
return ancestor.readdir.apply(fs, arguments);
}
if (insideMountpoint(path)) {
return ancestor.readdir.apply(fs, translateNth(arguments, 0, path));
}
var options = readdirOptions(options_, true);
if (!options) {
return ancestor.readdir.apply(fs, arguments);
}
var callback = dezalgo(maybeCallback(arguments));
readdirFromSnapshot(path, isRoot, function (error, entries) {
if (error) return callback(error);
if (options.withFileTypes) entries = getFileTypes(path, entries);
callback(null, entries);
});
};
// ///////////////////////////////////////////////////////////////
// realpath //////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
function realpathFromSnapshot (path_) {
var path = normalizePath(path_);
// console.log("realpathFromSnapshot", path);
return path;
}
fs.realpathSync = function (path) {
if (!insideSnapshot(path)) {
return ancestor.realpathSync.apply(fs, arguments);
}
if (insideMountpoint(path)) {
// app should not know real file name
}
return realpathFromSnapshot(path);
};
fs.realpath = function (path) {
if (!insideSnapshot(path)) {
return ancestor.realpath.apply(fs, arguments);
}
if (insideMountpoint(path)) {
// app should not know real file name
}
var callback = dezalgo(maybeCallback(arguments));
callback(null, realpathFromSnapshot(path));
};
// ///////////////////////////////////////////////////////////////
// stat //////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
function restore (s) {
s.blksize = 4096;
s.blocks = 0;
s.dev = 0;
s.gid = 20;
s.ino = 0;
s.nlink = 0;
s.rdev = 0;
s.uid = 500;
s.atime = new Date(EXECSTAT.atime);
s.mtime = new Date(EXECSTAT.mtime);
s.ctime = new Date(EXECSTAT.ctime);
s.birthtime = new Date(EXECSTAT.birthtime);
s.atimeMs = EXECSTAT.atimeMs;
s.mtimeMs = EXECSTAT.mtimeMs;
s.ctimeMs = EXECSTAT.ctimeMs;
s.birthtimeMs = EXECSTAT.birthtimeMs;
var isFileValue = s.isFileValue;
var isDirectoryValue = s.isDirectoryValue;
delete s.isFileValue;
delete s.isDirectoryValue;
s.isFile = function () {
return isFileValue;
};
s.isDirectory = function () {
return isDirectoryValue;
};
s.isSymbolicLink = function () {
return false;
};
s.isFIFO = function () {
return false;
};
return s;
}
function findNativeAddonForStat (path, cb) {
var cb2 = cb || rethrow;
var foundPath = findNativeAddonSyncUnderRequire(path);
if (!foundPath) return cb2(error_ENOENT('File or directory', path));
if (cb) {
ancestor.stat.call(fs, foundPath, cb);
} else {
return ancestor.statSync.call(fs, foundPath);
}
}
function statFromSnapshotSub (entityStat, cb) {
if (cb) {
payloadFile(entityStat, function (error, buffer) {
if (error) return cb(error);
cb(null, restore(JSON.parse(buffer)));
});
} else {
var buffer = payloadFileSync(entityStat);
return restore(JSON.parse(buffer));
}
}
function statFromSnapshot (path_, cb) {
var cb2 = cb || rethrow;
var path = normalizePath(path_);
// console.log("statFromSnapshot", path);
var entity = VIRTUAL_FILESYSTEM[path];
if (!entity) return findNativeAddonForStat(path, cb);
var entityStat = entity[STORE_STAT];
if (entityStat) return statFromSnapshotSub(entityStat, cb);
return cb2(new Error('UNEXPECTED-35'));
}
fs.statSync = function (path) {
if (!insideSnapshot(path)) {
return ancestor.statSync.apply(fs, arguments);
}
if (insideMountpoint(path)) {
return ancestor.statSync.apply(fs, translateNth(arguments, 0, path));
}
return statFromSnapshot(path);
};
fs.stat = function (path) {
if (!insideSnapshot(path)) {
return ancestor.stat.apply(fs, arguments);
}
if (insideMountpoint(path)) {
return ancestor.stat.apply(fs, translateNth(arguments, 0, path));
}
var callback = dezalgo(maybeCallback(arguments));