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
/
bootstrap.js
2115 lines (1825 loc) · 61.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 import/no-unresolved */
/* eslint-disable global-require */
/* 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 */
/* global DICT */
/* global DOCOMPRESS */
/* global SYMLINKS */
'use strict';
const childProcess = require('child_process');
const { createHash } = require('crypto');
const fs = require('fs');
const { isRegExp } = require('util').types;
const Module = require('module');
const path = require('path');
const { promisify, _extend } = require('util');
const { Script } = require('vm');
const { tmpdir } = require('os');
const util = require('util');
const {
brotliDecompress,
brotliDecompressSync,
gunzip,
gunzipSync,
} = require('zlib');
const common = {};
REQUIRE_COMMON(common);
const {
STORE_BLOB,
STORE_CONTENT,
STORE_LINKS,
STORE_STAT,
isRootPath,
normalizePath,
insideSnapshot,
stripSnapshot,
removeUplevels,
} = common;
let FLAG_ENABLE_PROJECT = false;
const NODE_VERSION_MAJOR = process.version.match(/^v(\d+)/)[1] | 0;
const NODE_VERSION_MINOR = process.version.match(/^v\d+.(\d+)/)[1] | 0;
// /////////////////////////////////////////////////////////////////
// ENTRYPOINT //////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
// set ENTRYPOINT and ARGV0 here because
// they can be altered during process run
const ARGV0 = process.argv[0];
const EXECPATH = process.execPath;
let 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] = path.resolve(process.argv[1]);
}
} else {
process.argv[1] = DEFAULT_ENTRYPOINT;
}
[, ENTRYPOINT] = process.argv;
delete process.env.PKG_EXECPATH;
// /////////////////////////////////////////////////////////////////
// EXECSTAT ////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
const EXECSTAT = fs.statSync(EXECPATH);
EXECSTAT.atimeMs = EXECSTAT.atime.getTime();
EXECSTAT.mtimeMs = EXECSTAT.mtime.getTime();
EXECSTAT.ctimeMs = EXECSTAT.ctime.getTime();
EXECSTAT.birthtimeMs = EXECSTAT.birthtime.getTime();
// /////////////////////////////////////////////////////////////////
// MOUNTPOINTS /////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
const mountpoints = [];
function insideMountpoint(f) {
if (!insideSnapshot(f)) return null;
const file = normalizePath(f);
const found = mountpoints
.map((mountpoint) => {
const { interior, exterior } = mountpoint;
if (isRegExp(interior) && interior.test(file))
return file.replace(interior, exterior);
if (interior === file) return exterior;
const left = interior + path.sep;
if (file.slice(0, left.length) !== left) return null;
return exterior + file.slice(left.length - 1);
})
.filter((result) => result);
if (found.length >= 2) throw new Error('UNEXPECTED-00');
if (found.length === 0) return null;
return found[0];
}
function readdirMountpoints(path_) {
return mountpoints
.filter(({ interior }) => {
if (isRegExp(interior)) return interior.test(path_);
return path.dirname(interior) === path_;
})
.map(({ interior, exterior }) => {
if (isRegExp(interior)) return path_.replace(interior, exterior);
return path.basename(interior);
});
}
function translate(f) {
const 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) {
const args = cloneArgs(args_);
args[index] = translate(f);
return args;
}
function createMountpoint(interior, exterior) {
// TODO validate
mountpoints.push({ interior, exterior });
}
function copyFileSync(source, target) {
let targetFile = target;
// If target is a directory, a new file with the same name will be created
if (fs.existsSync(target)) {
if (fs.lstatSync(target).isDirectory()) {
targetFile = path.join(target, path.basename(source));
}
}
fs.writeFileSync(targetFile, fs.readFileSync(source));
}
function copyFolderRecursiveSync(source, target) {
let files = [];
// Check if folder needs to be created or integrated
const targetFolder = path.join(target, path.basename(source));
if (!fs.existsSync(targetFolder)) {
fs.mkdirSync(targetFolder);
}
// Copy
if (fs.lstatSync(source).isDirectory()) {
files = fs.readdirSync(source);
files.forEach((file) => {
const curSource = path.join(source, file);
if (fs.lstatSync(curSource).isDirectory()) {
copyFolderRecursiveSync(curSource, targetFolder);
} else {
copyFileSync(curSource, targetFolder);
}
});
}
}
function createDirRecursively(dir) {
if (!fs.existsSync(dir)) {
createDirRecursively(path.join(dir, '..'));
fs.mkdirSync(dir);
}
}
/*
// 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"));
*/
const dictRev = {};
const separator = '/';
let maxKey = Object.values(DICT).length;
function replace(k) {
let v = DICT[k];
// we have found a part of a missing file => let record for latter use
if (v === undefined) {
maxKey += 1;
v = maxKey.toString(36);
DICT[k] = v;
dictRev[v] = k;
}
return v;
}
function findVirtualFileSystemKey(path_, slash) {
const normalizedPath = normalizePath(path_);
if (!DOCOMPRESS) {
return normalizedPath;
}
const a = normalizedPath.split(slash).map(replace).join(separator);
return a || normalizedPath;
}
Object.entries(DICT).forEach(([k, v]) => {
dictRev[v] = k;
});
function toOriginal(fShort) {
if (!DOCOMPRESS) {
return fShort;
}
return fShort
.split(separator)
.map((x) => dictRev[x])
.join(path.sep);
}
const symlinksEntries = Object.entries(SYMLINKS);
// separator for substitution depends on platform;
const sepsep = DOCOMPRESS ? separator : path.sep;
function findVirtualFileSystemKeyAndFollowLinks(path_) {
let vfsKey = findVirtualFileSystemKey(path_, path.sep);
let needToSubstitute = true;
while (needToSubstitute) {
needToSubstitute = false;
for (const [k, v] of symlinksEntries) {
if (vfsKey.startsWith(`${k}${sepsep}`) || vfsKey === k) {
vfsKey = vfsKey.replace(k, v);
needToSubstitute = true;
break;
}
}
}
return vfsKey;
}
function realpathFromSnapshot(path_) {
const realPath = toOriginal(findVirtualFileSystemKeyAndFollowLinks(path_));
return realPath;
}
function findVirtualFileSystemEntry(path_) {
const vfsKey = findVirtualFileSystemKeyAndFollowLinks(path_);
return VIRTUAL_FILESYSTEM[vfsKey];
}
// /////////////////////////////////////////////////////////////////
// PROJECT /////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
const xpdn = path.dirname(EXECPATH);
const maxUplevels = xpdn.split(path.sep).length;
function projectToFilesystem(f) {
const relatives = [];
relatives.push(
removeUplevels(path.relative(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));
}
const uplevels = [];
for (let i = 0, u = ''; i < maxUplevels; i += 1) {
uplevels.push(u);
u += '/..';
}
const results = [];
uplevels.forEach((uplevel) => {
relatives.forEach((relative) => {
results.push(path.join(xpdn, uplevel, relative));
});
});
return results;
}
function projectToNearby(f) {
return path.join(xpdn, path.basename(f));
}
function findNativeAddonSyncFreeFromRequire(path_) {
if (!insideSnapshot(path_)) throw new Error(`UNEXPECTED-10 ${path_}`);
if (path_.slice(-5) !== '.node') return null; // leveldown.node.js
// check nearby first to prevent .node tampering
const projector = projectToNearby(path_);
if (fs.existsSync(projector)) return projector;
const projectors = projectToFilesystem(path_);
for (let i = 0; i < projectors.length; i += 1) {
if (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;
let sync = true;
asap(() => {
sync = false;
});
return function zalgoSafe() {
const args = arguments;
if (sync) {
asap(() => {
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');
}
function readPayload(buffer, offset, length, position, callback) {
fs.read(
EXECPATH_FD,
buffer,
offset,
length,
PAYLOAD_POSITION + position,
callback
);
}
function readPayloadSync(buffer, offset, length, position) {
return fs.readSync(
EXECPATH_FD,
buffer,
offset,
length,
PAYLOAD_POSITION + position
);
}
function payloadCopyUni(
source,
target,
targetStart,
sourceStart,
sourceEnd,
cb
) {
const cb2 = cb || rethrow;
if (sourceStart >= source[1]) return cb2(null, 0);
if (sourceEnd >= source[1]) [, sourceEnd] = source;
const payloadPos = source[0] + sourceStart;
const targetPos = targetStart;
const 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) {
const payloadPos = source[0] + sourceStart;
let targetPos = targetStart;
const targetEnd = targetStart + source[1] - sourceStart;
readPayload(
target,
targetPos,
targetEnd - targetPos,
payloadPos,
(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) {
let payloadPos = source[0] + sourceStart;
let targetPos = targetStart;
const targetEnd = targetStart + source[1] - sourceStart;
while (true) {
const chunkSize = readPayloadSync(
target,
targetPos,
targetEnd - targetPos,
payloadPos
);
payloadPos += chunkSize;
targetPos += chunkSize;
if (!(chunkSize !== 0 && targetPos < targetEnd)) break;
}
}
const GZIP = 1;
const BROTLI = 2;
function payloadFile(pointer, cb) {
const target = Buffer.alloc(pointer[1]);
payloadCopyMany(pointer, target, 0, 0, (error) => {
if (error) return cb(error);
if (DOCOMPRESS === GZIP) {
gunzip(target, (error2, target2) => {
if (error2) return cb(error2);
cb(null, target2);
});
} else if (DOCOMPRESS === BROTLI) {
brotliDecompress(target, (error2, target2) => {
if (error2) return cb(error2);
cb(null, target2);
});
} else {
return cb(null, target);
}
});
}
function payloadFileSync(pointer) {
const target = Buffer.alloc(pointer[1]);
payloadCopyManySync(pointer, target, 0, 0);
if (DOCOMPRESS === GZIP) {
const target1 = gunzipSync(target);
return target1;
}
if (DOCOMPRESS === BROTLI) {
const target1 = brotliDecompressSync(target);
return target1;
}
return target;
}
// /////////////////////////////////////////////////////////////////
// SETUP PROCESS ///////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
(() => {
process.pkg = {};
process.versions.pkg = '%VERSION%';
process.pkg.mount = createMountpoint;
process.pkg.entrypoint = ENTRYPOINT;
process.pkg.defaultEntrypoint = DEFAULT_ENTRYPOINT;
})();
// /////////////////////////////////////////////////////////////////
// PATH.RESOLVE REPLACEMENT ////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
(() => {
process.pkg.path = {};
process.pkg.path.resolve = function resolve() {
const args = cloneArgs(arguments);
args.unshift(path.dirname(ENTRYPOINT));
return path.resolve.apply(path, args); // eslint-disable-line prefer-spread
};
})();
// /////////////////////////////////////////////////////////////////
// PATCH FS ////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////
(() => {
const ancestor = {
openSync: fs.openSync,
open: fs.open,
readSync: fs.readSync,
read: fs.read,
writeSync: fs.writeSync,
write: fs.write,
closeSync: fs.closeSync,
close: fs.close,
readFileSync: fs.readFileSync,
readFile: fs.readFile,
// writeFileSync: fs.writeFileSync, // based on openSync/writeSync/closeSync
// writeFile: fs.writeFile, // based on open/write/close
readdirSync: fs.readdirSync,
readdir: fs.readdir,
realpathSync: fs.realpathSync,
realpath: fs.realpath,
statSync: fs.statSync,
stat: fs.stat,
lstatSync: fs.lstatSync,
lstat: fs.lstat,
fstatSync: fs.fstatSync,
fstat: fs.fstat,
existsSync: fs.existsSync,
exists: fs.exists,
accessSync: fs.accessSync,
access: fs.access,
mkdirSync: fs.mkdirSync,
mkdir: fs.mkdir,
createReadStream: fs.createReadStream,
};
ancestor.realpathSync.native = fs.realpathSync;
ancestor.realpath.native = fs.realpath;
const windows = process.platform === 'win32';
const docks = {};
const ENOTDIR = windows ? 4052 : 20;
const ENOENT = windows ? 4058 : 2;
const EISDIR = windows ? 4068 : 21;
function assertEncoding(encoding) {
if (encoding && !Buffer.isEncoding(encoding)) {
throw new Error(`Unknown encoding: ${encoding}`);
}
}
function maybeCallback(args) {
const cb = args[args.length - 1];
return typeof cb === 'function' ? cb : rethrow;
}
function error_ENOENT(fileOrDirectory, path_) {
const 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_) {
const 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_) {
const 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 removeTemporaryFolderAndContent(folder) {
if (!folder) return;
if (NODE_VERSION_MAJOR <= 14) {
if (NODE_VERSION_MAJOR <= 10) {
// folder must be empty
for (const f of fs.readdirSync(folder)) {
fs.unlinkSync(path.join(folder, f));
}
fs.rmdirSync(folder);
} else {
fs.rmdirSync(folder, { recursive: true });
}
} else {
fs.rmSync(folder, { recursive: true });
}
}
const temporaryFiles = {};
const os = require('os');
let tmpFolder = '';
process.on('beforeExit', () => {
removeTemporaryFolderAndContent(tmpFolder);
});
function deflateSync(snapshotFilename) {
if (!tmpFolder) {
tmpFolder = fs.mkdtempSync(path.join(os.tmpdir(), 'pkg-'));
}
const content = fs.readFileSync(snapshotFilename, { encoding: 'binary' });
// content is already unzipped !
const hash = createHash('sha256').update(content).digest('hex');
const fName = path.join(tmpFolder, hash);
fs.writeFileSync(fName, content, 'binary');
return fName;
}
// eslint-disable-next-line prefer-arrow-callback
const uncompressExternally = function uncompressExternally(dock) {
if (!dock.externalFilename) {
const snapshotFilename = dock.path;
let t = temporaryFiles[snapshotFilename];
if (!t) {
const tmpFile = deflateSync(snapshotFilename);
t = { tmpFile };
temporaryFiles[snapshotFilename] = t;
}
dock.externalFilename = t.tmpFile;
}
return dock.externalFilename;
};
// eslint-disable-next-line prefer-arrow-callback
function uncompressExternallyPath(path_) {
const entity = findVirtualFileSystemEntry(path_);
const dock = { path: path_, entity, position: 0 };
return uncompressExternally(dock);
}
function uncompressExternallyAndOpen(dock) {
const externalFile = uncompressExternally(dock);
const fd = fs.openSync(externalFile, 'r');
return fd;
}
// eslint-disable-next-line prefer-arrow-callback
function openFromSnapshot(path_, uncompress, cb) {
const cb2 = cb || rethrow;
const entity = findVirtualFileSystemEntry(path_);
if (!entity) return cb2(error_ENOENT('File or directory', path_));
const dock = { path: path_, entity, position: 0 };
const nullDevice = windows ? '\\\\.\\NUL' : '/dev/null';
if (cb) {
ancestor.open.call(fs, nullDevice, 'r', (error, fd) => {
if (error) return cb(error);
if (DOCOMPRESS) {
dock._externalFile = uncompressExternallyAndOpen(dock);
}
docks[fd] = dock;
cb(null, fd);
});
} else {
const fd = ancestor.openSync.call(fs, nullDevice, 'r');
if (DOCOMPRESS) {
dock._externalFile = uncompressExternallyAndOpen(dock);
}
docks[fd] = dock;
return fd;
}
}
fs.createReadStream = function createReadStream(path_) {
if (!insideSnapshot(path_)) {
return ancestor.createReadStream.apply(fs, arguments);
}
if (insideMountpoint(path_)) {
return ancestor.createReadStream.apply(
fs,
translateNth(arguments, 0, path_)
);
}
const stream = ancestor.createReadStream.apply(fs, arguments);
return stream;
};
fs.openSync = function openSync(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_, DOCOMPRESS);
};
fs.open = function open(path_) {
if (!insideSnapshot(path_)) {
return ancestor.open.apply(fs, arguments);
}
if (insideMountpoint(path_)) {
return ancestor.open.apply(fs, translateNth(arguments, 0, path_));
}
const callback = dezalgo(maybeCallback(arguments));
openFromSnapshot(path_, DOCOMPRESS, callback);
};
// ///////////////////////////////////////////////////////////////
// read //////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
function readFromSnapshotSub(
entityContent,
dock,
buffer,
offset,
length,
position,
cb
) {
if (DOCOMPRESS) {
// note: source contains info about a compressed file and source[1] does not reflect
// the actual size of the file.
// so random access reading of a compressed virtual file, requires read from
// an externally decompressed file
if (!dock._externalFile) {
dock._externalFile = uncompressExternallyAndOpen(dock);
} else {
position = position === undefined ? 0 : position;
}
return fs.read(dock._externalFile, buffer, offset, length, position, cb);
}
let p;
if (position !== null && position !== undefined) {
p = position;
} else {
p = dock.position;
}
if (cb) {
payloadCopyUni(
entityContent,
buffer,
offset,
p,
p + length,
(error, bytesRead, buffer2) => {
if (error) return cb(error);
dock.position = p + bytesRead;
cb(null, bytesRead, buffer2);
}
);
} else {
const bytesRead = payloadCopyUni(
entityContent,
buffer,
offset,
p,
p + length
);
dock.position = p + bytesRead;
return bytesRead;
}
}
function readFromSnapshot(fd, buffer, offset, length, position, cb) {
const dock = docks[fd];
if (dock && dock._externalFile) {
if (cb) {
return ancestor.read(
dock._externalFile,
buffer,
offset,
length,
position,
cb
);
}
return ancestor.readSync(
dock._externalFile,
buffer,
offset,
length,
position
);
}
const cb2 = cb || rethrow;
if (offset < 0 && NODE_VERSION_MAJOR >= 14)
return cb2(
new Error(
`The value of "offset" is out of range. It must be >= 0. Received ${offset}`
)
);
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) return cb2(null, 0);
if (offset + length > buffer.length && NODE_VERSION_MAJOR >= 14)
return cb2(
new Error(
`The value of "length" is out of range. It must be <= ${(
buffer.length - offset
).toString()}. Received ${length.toString()}`
)
);
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'));
const { entity } = dock;
const entityLinks = entity[STORE_LINKS];
if (entityLinks) return cb2(error_EISDIR(dock.path));
const entityContent = entity[STORE_CONTENT];
if (entityContent)
return readFromSnapshotSub(
entityContent,
dock,
buffer,
offset,
length,
position,
cb
);
return cb2(new Error('UNEXPECTED-15'));
}
fs.readSync = function readSync(fd, buffer, offset, length, position) {
if (!docks[fd]) {
return ancestor.readSync.apply(fs, arguments);
}
return readFromSnapshot(fd, buffer, offset, length, position);
};
fs.read = function read(fd, buffer, offset, length, position) {
if (!docks[fd]) {
return ancestor.read.apply(fs, arguments);
}
const callback = dezalgo(maybeCallback(arguments));
readFromSnapshot(fd, buffer, offset, length, position, callback);
};
// ///////////////////////////////////////////////////////////////
// write /////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
function writeToSnapshot(cb) {
const cb2 = cb || rethrow;
return cb2(new Error('Cannot write to packaged file'));
}
fs.writeSync = function writeSync(fd) {
if (!docks[fd]) {
return ancestor.writeSync.apply(fs, arguments);
}
return writeToSnapshot();
};
fs.write = function write(fd) {
if (!docks[fd]) {
return ancestor.write.apply(fs, arguments);
}
const callback = dezalgo(maybeCallback(arguments));
return writeToSnapshot(callback);
};
// ///////////////////////////////////////////////////////////////
// close /////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
const closeFromSnapshot = (fd, cb) => {
const dock = docks[fd];
if (dock._externalFile) {
ancestor.closeSync(dock._externalFile);
dock._externalFile = undefined;
}
delete docks[fd];
if (cb) {
ancestor.close.call(fs, fd, cb);
} else {
return ancestor.closeSync.call(fs, fd);
}
};
fs.closeSync = function closeSync(fd) {
if (!docks[fd]) {
return ancestor.closeSync.apply(fs, arguments);
}
return closeFromSnapshot(fd);
};
fs.close = function close(fd) {
if (!docks[fd]) {
return ancestor.close.apply(fs, arguments);
}
const callback = dezalgo(maybeCallback(arguments));
closeFromSnapshot(fd, callback);
};
// ///////////////////////////////////////////////////////////////
// readFile //////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
function readFileOptions(options, hasCallback) {
if (!options || (hasCallback && typeof options === 'function')) {
return { encoding: null, flag: 'r' };
}
if (typeof options === 'string') {
return { encoding: options, flag: 'r' };
}
if (typeof options === 'object') {
return options;
}
return null;
}
function readFileFromSnapshotSub(entityContent, cb) {
if (cb) {
payloadFile(entityContent, cb);
} else {
return payloadFileSync(entityContent);
}
}
function readFileFromSnapshot(path_, cb) {
const cb2 = cb || rethrow;
const entity = findVirtualFileSystemEntry(path_);
if (!entity) return cb2(error_ENOENT('File', path_));
const entityLinks = entity[STORE_LINKS];
if (entityLinks) return cb2(error_EISDIR(path_));
const entityContent = entity[STORE_CONTENT];
if (entityContent) return readFileFromSnapshotSub(entityContent, cb);
const entityBlob = entity[STORE_BLOB];
if (entityBlob) {