-
Notifications
You must be signed in to change notification settings - Fork 0
/
.pnp.cjs
executable file
·7511 lines (7415 loc) · 417 KB
/
.pnp.cjs
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
#!/usr/bin/env node
/* eslint-disable */
// @ts-nocheck
"use strict";
const RAW_RUNTIME_STATE =
'{\
"__info": [\
"This file is automatically generated. Do not touch it, or risk",\
"your modifications being lost."\
],\
"dependencyTreeRoots": [\
{\
"name": "competitive-programming",\
"reference": "workspace:."\
}\
],\
"enableTopLevelFallback": true,\
"ignorePatternData": "(^(?:\\\\.yarn\\\\/sdks(?:\\\\/(?!\\\\.{1,2}(?:\\\\/|$))(?:(?:(?!(?:^|\\\\/)\\\\.{1,2}(?:\\\\/|$)).)*?)|$))$)",\
"fallbackExclusionList": [\
["competitive-programming", ["workspace:."]]\
],\
"fallbackPool": [\
],\
"packageRegistryData": [\
[null, [\
[null, {\
"packageLocation": "./",\
"packageDependencies": [\
],\
"linkType": "SOFT"\
}]\
]],\
["competitive-programming", [\
["workspace:.", {\
"packageLocation": "./",\
"packageDependencies": [\
["competitive-programming", "workspace:."]\
],\
"linkType": "SOFT"\
}]\
]]\
]\
}';
function $$SETUP_STATE(hydrateRuntimeState, basePath) {
return hydrateRuntimeState(JSON.parse(RAW_RUNTIME_STATE), {basePath: basePath || __dirname});
}
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const os = require('os');
const events = require('events');
const nodeUtils = require('util');
const stream = require('stream');
const zlib = require('zlib');
const require$$0 = require('module');
const StringDecoder = require('string_decoder');
const url = require('url');
const buffer = require('buffer');
const readline = require('readline');
const assert = require('assert');
const _interopDefaultLegacy = e => e && typeof e === 'object' && 'default' in e ? e : { default: e };
function _interopNamespace(e) {
if (e && e.__esModule) return e;
const n = Object.create(null);
if (e) {
for (const k in e) {
if (k !== 'default') {
const d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: () => e[k]
});
}
}
}
n.default = e;
return Object.freeze(n);
}
const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
const nodeUtils__namespace = /*#__PURE__*/_interopNamespace(nodeUtils);
const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib);
const require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
const StringDecoder__default = /*#__PURE__*/_interopDefaultLegacy(StringDecoder);
const buffer__default = /*#__PURE__*/_interopDefaultLegacy(buffer);
const assert__default = /*#__PURE__*/_interopDefaultLegacy(assert);
const S_IFMT = 61440;
const S_IFDIR = 16384;
const S_IFREG = 32768;
const S_IFLNK = 40960;
const SAFE_TIME = 456789e3;
function makeError$1(code, message) {
return Object.assign(new Error(`${code}: ${message}`), { code });
}
function EBUSY(message) {
return makeError$1(`EBUSY`, message);
}
function ENOSYS(message, reason) {
return makeError$1(`ENOSYS`, `${message}, ${reason}`);
}
function EINVAL(reason) {
return makeError$1(`EINVAL`, `invalid argument, ${reason}`);
}
function EBADF(reason) {
return makeError$1(`EBADF`, `bad file descriptor, ${reason}`);
}
function ENOENT(reason) {
return makeError$1(`ENOENT`, `no such file or directory, ${reason}`);
}
function ENOTDIR(reason) {
return makeError$1(`ENOTDIR`, `not a directory, ${reason}`);
}
function EISDIR(reason) {
return makeError$1(`EISDIR`, `illegal operation on a directory, ${reason}`);
}
function EEXIST(reason) {
return makeError$1(`EEXIST`, `file already exists, ${reason}`);
}
function EROFS(reason) {
return makeError$1(`EROFS`, `read-only filesystem, ${reason}`);
}
function ENOTEMPTY(reason) {
return makeError$1(`ENOTEMPTY`, `directory not empty, ${reason}`);
}
function EOPNOTSUPP(reason) {
return makeError$1(`EOPNOTSUPP`, `operation not supported, ${reason}`);
}
function ERR_DIR_CLOSED() {
return makeError$1(`ERR_DIR_CLOSED`, `Directory handle was closed`);
}
const DEFAULT_MODE = S_IFREG | 420;
class StatEntry {
uid = 0;
gid = 0;
size = 0;
blksize = 0;
atimeMs = 0;
mtimeMs = 0;
ctimeMs = 0;
birthtimeMs = 0;
atime = /* @__PURE__ */ new Date(0);
mtime = /* @__PURE__ */ new Date(0);
ctime = /* @__PURE__ */ new Date(0);
birthtime = /* @__PURE__ */ new Date(0);
dev = 0;
ino = 0;
mode = DEFAULT_MODE;
nlink = 1;
rdev = 0;
blocks = 1;
isBlockDevice() {
return false;
}
isCharacterDevice() {
return false;
}
isDirectory() {
return (this.mode & S_IFMT) === S_IFDIR;
}
isFIFO() {
return false;
}
isFile() {
return (this.mode & S_IFMT) === S_IFREG;
}
isSocket() {
return false;
}
isSymbolicLink() {
return (this.mode & S_IFMT) === S_IFLNK;
}
}
class BigIntStatsEntry {
uid = BigInt(0);
gid = BigInt(0);
size = BigInt(0);
blksize = BigInt(0);
atimeMs = BigInt(0);
mtimeMs = BigInt(0);
ctimeMs = BigInt(0);
birthtimeMs = BigInt(0);
atimeNs = BigInt(0);
mtimeNs = BigInt(0);
ctimeNs = BigInt(0);
birthtimeNs = BigInt(0);
atime = /* @__PURE__ */ new Date(0);
mtime = /* @__PURE__ */ new Date(0);
ctime = /* @__PURE__ */ new Date(0);
birthtime = /* @__PURE__ */ new Date(0);
dev = BigInt(0);
ino = BigInt(0);
mode = BigInt(DEFAULT_MODE);
nlink = BigInt(1);
rdev = BigInt(0);
blocks = BigInt(1);
isBlockDevice() {
return false;
}
isCharacterDevice() {
return false;
}
isDirectory() {
return (this.mode & BigInt(S_IFMT)) === BigInt(S_IFDIR);
}
isFIFO() {
return false;
}
isFile() {
return (this.mode & BigInt(S_IFMT)) === BigInt(S_IFREG);
}
isSocket() {
return false;
}
isSymbolicLink() {
return (this.mode & BigInt(S_IFMT)) === BigInt(S_IFLNK);
}
}
function makeDefaultStats() {
return new StatEntry();
}
function clearStats(stats) {
for (const key in stats) {
if (Object.hasOwn(stats, key)) {
const element = stats[key];
if (typeof element === `number`) {
stats[key] = 0;
} else if (typeof element === `bigint`) {
stats[key] = BigInt(0);
} else if (nodeUtils__namespace.types.isDate(element)) {
stats[key] = /* @__PURE__ */ new Date(0);
}
}
}
return stats;
}
function convertToBigIntStats(stats) {
const bigintStats = new BigIntStatsEntry();
for (const key in stats) {
if (Object.hasOwn(stats, key)) {
const element = stats[key];
if (typeof element === `number`) {
bigintStats[key] = BigInt(element);
} else if (nodeUtils__namespace.types.isDate(element)) {
bigintStats[key] = new Date(element);
}
}
}
bigintStats.atimeNs = bigintStats.atimeMs * BigInt(1e6);
bigintStats.mtimeNs = bigintStats.mtimeMs * BigInt(1e6);
bigintStats.ctimeNs = bigintStats.ctimeMs * BigInt(1e6);
bigintStats.birthtimeNs = bigintStats.birthtimeMs * BigInt(1e6);
return bigintStats;
}
function areStatsEqual(a, b) {
if (a.atimeMs !== b.atimeMs)
return false;
if (a.birthtimeMs !== b.birthtimeMs)
return false;
if (a.blksize !== b.blksize)
return false;
if (a.blocks !== b.blocks)
return false;
if (a.ctimeMs !== b.ctimeMs)
return false;
if (a.dev !== b.dev)
return false;
if (a.gid !== b.gid)
return false;
if (a.ino !== b.ino)
return false;
if (a.isBlockDevice() !== b.isBlockDevice())
return false;
if (a.isCharacterDevice() !== b.isCharacterDevice())
return false;
if (a.isDirectory() !== b.isDirectory())
return false;
if (a.isFIFO() !== b.isFIFO())
return false;
if (a.isFile() !== b.isFile())
return false;
if (a.isSocket() !== b.isSocket())
return false;
if (a.isSymbolicLink() !== b.isSymbolicLink())
return false;
if (a.mode !== b.mode)
return false;
if (a.mtimeMs !== b.mtimeMs)
return false;
if (a.nlink !== b.nlink)
return false;
if (a.rdev !== b.rdev)
return false;
if (a.size !== b.size)
return false;
if (a.uid !== b.uid)
return false;
const aN = a;
const bN = b;
if (aN.atimeNs !== bN.atimeNs)
return false;
if (aN.mtimeNs !== bN.mtimeNs)
return false;
if (aN.ctimeNs !== bN.ctimeNs)
return false;
if (aN.birthtimeNs !== bN.birthtimeNs)
return false;
return true;
}
const PortablePath = {
root: `/`,
dot: `.`,
parent: `..`
};
const Filename = {
home: `~`,
nodeModules: `node_modules`,
manifest: `package.json`,
lockfile: `yarn.lock`,
virtual: `__virtual__`,
/**
* @deprecated
*/
pnpJs: `.pnp.js`,
pnpCjs: `.pnp.cjs`,
pnpData: `.pnp.data.json`,
pnpEsmLoader: `.pnp.loader.mjs`,
rc: `.yarnrc.yml`,
env: `.env`
};
const npath = Object.create(path__default.default);
const ppath = Object.create(path__default.default.posix);
npath.cwd = () => process.cwd();
ppath.cwd = process.platform === `win32` ? () => toPortablePath(process.cwd()) : process.cwd;
if (process.platform === `win32`) {
ppath.resolve = (...segments) => {
if (segments.length > 0 && ppath.isAbsolute(segments[0])) {
return path__default.default.posix.resolve(...segments);
} else {
return path__default.default.posix.resolve(ppath.cwd(), ...segments);
}
};
}
const contains = function(pathUtils, from, to) {
from = pathUtils.normalize(from);
to = pathUtils.normalize(to);
if (from === to)
return `.`;
if (!from.endsWith(pathUtils.sep))
from = from + pathUtils.sep;
if (to.startsWith(from)) {
return to.slice(from.length);
} else {
return null;
}
};
npath.contains = (from, to) => contains(npath, from, to);
ppath.contains = (from, to) => contains(ppath, from, to);
const WINDOWS_PATH_REGEXP = /^([a-zA-Z]:.*)$/;
const UNC_WINDOWS_PATH_REGEXP = /^\/\/(\.\/)?(.*)$/;
const PORTABLE_PATH_REGEXP = /^\/([a-zA-Z]:.*)$/;
const UNC_PORTABLE_PATH_REGEXP = /^\/unc\/(\.dot\/)?(.*)$/;
function fromPortablePathWin32(p) {
let portablePathMatch, uncPortablePathMatch;
if (portablePathMatch = p.match(PORTABLE_PATH_REGEXP))
p = portablePathMatch[1];
else if (uncPortablePathMatch = p.match(UNC_PORTABLE_PATH_REGEXP))
p = `\\\\${uncPortablePathMatch[1] ? `.\\` : ``}${uncPortablePathMatch[2]}`;
else
return p;
return p.replace(/\//g, `\\`);
}
function toPortablePathWin32(p) {
p = p.replace(/\\/g, `/`);
let windowsPathMatch, uncWindowsPathMatch;
if (windowsPathMatch = p.match(WINDOWS_PATH_REGEXP))
p = `/${windowsPathMatch[1]}`;
else if (uncWindowsPathMatch = p.match(UNC_WINDOWS_PATH_REGEXP))
p = `/unc/${uncWindowsPathMatch[1] ? `.dot/` : ``}${uncWindowsPathMatch[2]}`;
return p;
}
const toPortablePath = process.platform === `win32` ? toPortablePathWin32 : (p) => p;
const fromPortablePath = process.platform === `win32` ? fromPortablePathWin32 : (p) => p;
npath.fromPortablePath = fromPortablePath;
npath.toPortablePath = toPortablePath;
function convertPath(targetPathUtils, sourcePath) {
return targetPathUtils === npath ? fromPortablePath(sourcePath) : toPortablePath(sourcePath);
}
const defaultTime = new Date(SAFE_TIME * 1e3);
const defaultTimeMs = defaultTime.getTime();
async function copyPromise(destinationFs, destination, sourceFs, source, opts) {
const normalizedDestination = destinationFs.pathUtils.normalize(destination);
const normalizedSource = sourceFs.pathUtils.normalize(source);
const prelayout = [];
const postlayout = [];
const { atime, mtime } = opts.stableTime ? { atime: defaultTime, mtime: defaultTime } : await sourceFs.lstatPromise(normalizedSource);
await destinationFs.mkdirpPromise(destinationFs.pathUtils.dirname(destination), { utimes: [atime, mtime] });
await copyImpl(prelayout, postlayout, destinationFs, normalizedDestination, sourceFs, normalizedSource, { ...opts, didParentExist: true });
for (const operation of prelayout)
await operation();
await Promise.all(postlayout.map((operation) => {
return operation();
}));
}
async function copyImpl(prelayout, postlayout, destinationFs, destination, sourceFs, source, opts) {
const destinationStat = opts.didParentExist ? await maybeLStat(destinationFs, destination) : null;
const sourceStat = await sourceFs.lstatPromise(source);
const { atime, mtime } = opts.stableTime ? { atime: defaultTime, mtime: defaultTime } : sourceStat;
let updated;
switch (true) {
case sourceStat.isDirectory():
{
updated = await copyFolder(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
}
break;
case sourceStat.isFile():
{
updated = await copyFile(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
}
break;
case sourceStat.isSymbolicLink():
{
updated = await copySymlink(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
}
break;
default: {
throw new Error(`Unsupported file type (${sourceStat.mode})`);
}
}
if (opts.linkStrategy?.type !== `HardlinkFromIndex` || !sourceStat.isFile()) {
if (updated || destinationStat?.mtime?.getTime() !== mtime.getTime() || destinationStat?.atime?.getTime() !== atime.getTime()) {
postlayout.push(() => destinationFs.lutimesPromise(destination, atime, mtime));
updated = true;
}
if (destinationStat === null || (destinationStat.mode & 511) !== (sourceStat.mode & 511)) {
postlayout.push(() => destinationFs.chmodPromise(destination, sourceStat.mode & 511));
updated = true;
}
}
return updated;
}
async function maybeLStat(baseFs, p) {
try {
return await baseFs.lstatPromise(p);
} catch (e) {
return null;
}
}
async function copyFolder(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
if (destinationStat !== null && !destinationStat.isDirectory()) {
if (opts.overwrite) {
prelayout.push(async () => destinationFs.removePromise(destination));
destinationStat = null;
} else {
return false;
}
}
let updated = false;
if (destinationStat === null) {
prelayout.push(async () => {
try {
await destinationFs.mkdirPromise(destination, { mode: sourceStat.mode });
} catch (err) {
if (err.code !== `EEXIST`) {
throw err;
}
}
});
updated = true;
}
const entries = await sourceFs.readdirPromise(source);
const nextOpts = opts.didParentExist && !destinationStat ? { ...opts, didParentExist: false } : opts;
if (opts.stableSort) {
for (const entry of entries.sort()) {
if (await copyImpl(prelayout, postlayout, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), nextOpts)) {
updated = true;
}
}
} else {
const entriesUpdateStatus = await Promise.all(entries.map(async (entry) => {
await copyImpl(prelayout, postlayout, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), nextOpts);
}));
if (entriesUpdateStatus.some((status) => status)) {
updated = true;
}
}
return updated;
}
async function copyFileViaIndex(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts, linkStrategy) {
const sourceHash = await sourceFs.checksumFilePromise(source, { algorithm: `sha1` });
const defaultMode = 420;
const sourceMode = sourceStat.mode & 511;
const indexFileName = `${sourceHash}${sourceMode !== defaultMode ? sourceMode.toString(8) : ``}`;
const indexPath = destinationFs.pathUtils.join(linkStrategy.indexPath, sourceHash.slice(0, 2), `${indexFileName}.dat`);
let AtomicBehavior;
((AtomicBehavior2) => {
AtomicBehavior2[AtomicBehavior2["Lock"] = 0] = "Lock";
AtomicBehavior2[AtomicBehavior2["Rename"] = 1] = "Rename";
})(AtomicBehavior || (AtomicBehavior = {}));
let atomicBehavior = 1 /* Rename */;
let indexStat = await maybeLStat(destinationFs, indexPath);
if (destinationStat) {
const isDestinationHardlinkedFromIndex = indexStat && destinationStat.dev === indexStat.dev && destinationStat.ino === indexStat.ino;
const isIndexModified = indexStat?.mtimeMs !== defaultTimeMs;
if (isDestinationHardlinkedFromIndex) {
if (isIndexModified && linkStrategy.autoRepair) {
atomicBehavior = 0 /* Lock */;
indexStat = null;
}
}
if (!isDestinationHardlinkedFromIndex) {
if (opts.overwrite) {
prelayout.push(async () => destinationFs.removePromise(destination));
destinationStat = null;
} else {
return false;
}
}
}
const tempPath = !indexStat && atomicBehavior === 1 /* Rename */ ? `${indexPath}.${Math.floor(Math.random() * 4294967296).toString(16).padStart(8, `0`)}` : null;
let tempPathCleaned = false;
prelayout.push(async () => {
if (!indexStat) {
if (atomicBehavior === 0 /* Lock */) {
await destinationFs.lockPromise(indexPath, async () => {
const content = await sourceFs.readFilePromise(source);
await destinationFs.writeFilePromise(indexPath, content);
});
}
if (atomicBehavior === 1 /* Rename */ && tempPath) {
const content = await sourceFs.readFilePromise(source);
await destinationFs.writeFilePromise(tempPath, content);
try {
await destinationFs.linkPromise(tempPath, indexPath);
} catch (err) {
if (err.code === `EEXIST`) {
tempPathCleaned = true;
await destinationFs.unlinkPromise(tempPath);
} else {
throw err;
}
}
}
}
if (!destinationStat) {
await destinationFs.linkPromise(indexPath, destination);
}
});
postlayout.push(async () => {
if (!indexStat) {
await destinationFs.lutimesPromise(indexPath, defaultTime, defaultTime);
if (sourceMode !== defaultMode) {
await destinationFs.chmodPromise(indexPath, sourceMode);
}
}
if (tempPath && !tempPathCleaned) {
await destinationFs.unlinkPromise(tempPath);
}
});
return false;
}
async function copyFileDirect(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
if (destinationStat !== null) {
if (opts.overwrite) {
prelayout.push(async () => destinationFs.removePromise(destination));
destinationStat = null;
} else {
return false;
}
}
prelayout.push(async () => {
const content = await sourceFs.readFilePromise(source);
await destinationFs.writeFilePromise(destination, content);
});
return true;
}
async function copyFile(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
if (opts.linkStrategy?.type === `HardlinkFromIndex`) {
return copyFileViaIndex(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts, opts.linkStrategy);
} else {
return copyFileDirect(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
}
}
async function copySymlink(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
if (destinationStat !== null) {
if (opts.overwrite) {
prelayout.push(async () => destinationFs.removePromise(destination));
destinationStat = null;
} else {
return false;
}
}
prelayout.push(async () => {
await destinationFs.symlinkPromise(convertPath(destinationFs.pathUtils, await sourceFs.readlinkPromise(source)), destination);
});
return true;
}
class CustomDir {
constructor(path, nextDirent, opts = {}) {
this.path = path;
this.nextDirent = nextDirent;
this.opts = opts;
}
closed = false;
throwIfClosed() {
if (this.closed) {
throw ERR_DIR_CLOSED();
}
}
async *[Symbol.asyncIterator]() {
try {
let dirent;
while ((dirent = await this.read()) !== null) {
yield dirent;
}
} finally {
await this.close();
}
}
read(cb) {
const dirent = this.readSync();
if (typeof cb !== `undefined`)
return cb(null, dirent);
return Promise.resolve(dirent);
}
readSync() {
this.throwIfClosed();
return this.nextDirent();
}
close(cb) {
this.closeSync();
if (typeof cb !== `undefined`)
return cb(null);
return Promise.resolve();
}
closeSync() {
this.throwIfClosed();
this.opts.onClose?.();
this.closed = true;
}
}
function opendir(fakeFs, path, entries, opts) {
const nextDirent = () => {
const filename = entries.shift();
if (typeof filename === `undefined`)
return null;
const entryPath = fakeFs.pathUtils.join(path, filename);
return Object.assign(fakeFs.statSync(entryPath), {
name: filename,
path: void 0
});
};
return new CustomDir(path, nextDirent, opts);
}
function assertStatus(current, expected) {
if (current !== expected) {
throw new Error(`Invalid StatWatcher status: expected '${expected}', got '${current}'`);
}
}
class CustomStatWatcher extends events.EventEmitter {
fakeFs;
path;
bigint;
status = "ready" /* Ready */;
changeListeners = /* @__PURE__ */ new Map();
lastStats;
startTimeout = null;
static create(fakeFs, path, opts) {
const statWatcher = new CustomStatWatcher(fakeFs, path, opts);
statWatcher.start();
return statWatcher;
}
constructor(fakeFs, path, { bigint = false } = {}) {
super();
this.fakeFs = fakeFs;
this.path = path;
this.bigint = bigint;
this.lastStats = this.stat();
}
start() {
assertStatus(this.status, "ready" /* Ready */);
this.status = "running" /* Running */;
this.startTimeout = setTimeout(() => {
this.startTimeout = null;
if (!this.fakeFs.existsSync(this.path)) {
this.emit("change" /* Change */, this.lastStats, this.lastStats);
}
}, 3);
}
stop() {
assertStatus(this.status, "running" /* Running */);
this.status = "stopped" /* Stopped */;
if (this.startTimeout !== null) {
clearTimeout(this.startTimeout);
this.startTimeout = null;
}
this.emit("stop" /* Stop */);
}
stat() {
try {
return this.fakeFs.statSync(this.path, { bigint: this.bigint });
} catch (error) {
const statInstance = this.bigint ? new BigIntStatsEntry() : new StatEntry();
return clearStats(statInstance);
}
}
/**
* Creates an interval whose callback compares the current stats with the previous stats and notifies all listeners in case of changes.
*
* @param opts.persistent Decides whether the interval should be immediately unref-ed.
*/
makeInterval(opts) {
const interval = setInterval(() => {
const currentStats = this.stat();
const previousStats = this.lastStats;
if (areStatsEqual(currentStats, previousStats))
return;
this.lastStats = currentStats;
this.emit("change" /* Change */, currentStats, previousStats);
}, opts.interval);
return opts.persistent ? interval : interval.unref();
}
/**
* Registers a listener and assigns it an interval.
*/
registerChangeListener(listener, opts) {
this.addListener("change" /* Change */, listener);
this.changeListeners.set(listener, this.makeInterval(opts));
}
/**
* Unregisters the listener and clears the assigned interval.
*/
unregisterChangeListener(listener) {
this.removeListener("change" /* Change */, listener);
const interval = this.changeListeners.get(listener);
if (typeof interval !== `undefined`)
clearInterval(interval);
this.changeListeners.delete(listener);
}
/**
* Unregisters all listeners and clears all assigned intervals.
*/
unregisterAllChangeListeners() {
for (const listener of this.changeListeners.keys()) {
this.unregisterChangeListener(listener);
}
}
hasChangeListeners() {
return this.changeListeners.size > 0;
}
/**
* Refs all stored intervals.
*/
ref() {
for (const interval of this.changeListeners.values())
interval.ref();
return this;
}
/**
* Unrefs all stored intervals.
*/
unref() {
for (const interval of this.changeListeners.values())
interval.unref();
return this;
}
}
const statWatchersByFakeFS = /* @__PURE__ */ new WeakMap();
function watchFile(fakeFs, path, a, b) {
let bigint;
let persistent;
let interval;
let listener;
switch (typeof a) {
case `function`:
{
bigint = false;
persistent = true;
interval = 5007;
listener = a;
}
break;
default:
{
({
bigint = false,
persistent = true,
interval = 5007
} = a);
listener = b;
}
break;
}
let statWatchers = statWatchersByFakeFS.get(fakeFs);
if (typeof statWatchers === `undefined`)
statWatchersByFakeFS.set(fakeFs, statWatchers = /* @__PURE__ */ new Map());
let statWatcher = statWatchers.get(path);
if (typeof statWatcher === `undefined`) {
statWatcher = CustomStatWatcher.create(fakeFs, path, { bigint });
statWatchers.set(path, statWatcher);
}
statWatcher.registerChangeListener(listener, { persistent, interval });
return statWatcher;
}
function unwatchFile(fakeFs, path, cb) {
const statWatchers = statWatchersByFakeFS.get(fakeFs);
if (typeof statWatchers === `undefined`)
return;
const statWatcher = statWatchers.get(path);
if (typeof statWatcher === `undefined`)
return;
if (typeof cb === `undefined`)
statWatcher.unregisterAllChangeListeners();
else
statWatcher.unregisterChangeListener(cb);
if (!statWatcher.hasChangeListeners()) {
statWatcher.stop();
statWatchers.delete(path);
}
}
function unwatchAllFiles(fakeFs) {
const statWatchers = statWatchersByFakeFS.get(fakeFs);
if (typeof statWatchers === `undefined`)
return;
for (const path of statWatchers.keys()) {
unwatchFile(fakeFs, path);
}
}
class FakeFS {
pathUtils;
constructor(pathUtils) {
this.pathUtils = pathUtils;
}
async *genTraversePromise(init, { stableSort = false } = {}) {
const stack = [init];
while (stack.length > 0) {
const p = stack.shift();
const entry = await this.lstatPromise(p);
if (entry.isDirectory()) {
const entries = await this.readdirPromise(p);
if (stableSort) {
for (const entry2 of entries.sort()) {
stack.push(this.pathUtils.join(p, entry2));
}
} else {
throw new Error(`Not supported`);
}
} else {
yield p;
}
}
}
async checksumFilePromise(path, { algorithm = `sha512` } = {}) {
const fd = await this.openPromise(path, `r`);
try {
const CHUNK_SIZE = 65536;
const chunk = Buffer.allocUnsafeSlow(CHUNK_SIZE);
const hash = crypto.createHash(algorithm);
let bytesRead = 0;
while ((bytesRead = await this.readPromise(fd, chunk, 0, CHUNK_SIZE)) !== 0)
hash.update(bytesRead === CHUNK_SIZE ? chunk : chunk.slice(0, bytesRead));
return hash.digest(`hex`);
} finally {
await this.closePromise(fd);
}
}
async removePromise(p, { recursive = true, maxRetries = 5 } = {}) {
let stat;
try {
stat = await this.lstatPromise(p);
} catch (error) {
if (error.code === `ENOENT`) {
return;
} else {
throw error;
}
}
if (stat.isDirectory()) {
if (recursive) {
const entries = await this.readdirPromise(p);
await Promise.all(entries.map((entry) => {
return this.removePromise(this.pathUtils.resolve(p, entry));
}));
}
for (let t = 0; t <= maxRetries; t++) {
try {
await this.rmdirPromise(p);
break;
} catch (error) {
if (error.code !== `EBUSY` && error.code !== `ENOTEMPTY`) {
throw error;
} else if (t < maxRetries) {
await new Promise((resolve) => setTimeout(resolve, t * 100));
}
}
}
} else {
await this.unlinkPromise(p);
}
}
removeSync(p, { recursive = true } = {}) {
let stat;
try {
stat = this.lstatSync(p);
} catch (error) {
if (error.code === `ENOENT`) {
return;
} else {
throw error;
}
}
if (stat.isDirectory()) {
if (recursive)
for (const entry of this.readdirSync(p))
this.removeSync(this.pathUtils.resolve(p, entry));
this.rmdirSync(p);
} else {
this.unlinkSync(p);
}
}
async mkdirpPromise(p, { chmod, utimes } = {}) {
p = this.resolve(p);
if (p === this.pathUtils.dirname(p))
return void 0;
const parts = p.split(this.pathUtils.sep);
let createdDirectory;
for (let u = 2; u <= parts.length; ++u) {
const subPath = parts.slice(0, u).join(this.pathUtils.sep);
if (!this.existsSync(subPath)) {
try {
await this.mkdirPromise(subPath);
} catch (error) {
if (error.code === `EEXIST`) {
continue;
} else {
throw error;
}
}
createdDirectory ??= subPath;
if (chmod != null)
await this.chmodPromise(subPath, chmod);
if (utimes != null) {
await this.utimesPromise(subPath, utimes[0], utimes[1]);
} else {
const parentStat = await this.statPromise(this.pathUtils.dirname(subPath));
await this.utimesPromise(subPath, parentStat.atime, parentStat.mtime);
}
}
}
return createdDirectory;
}
mkdirpSync(p, { chmod, utimes } = {}) {
p = this.resolve(p);
if (p === this.pathUtils.dirname(p))
return void 0;
const parts = p.split(this.pathUtils.sep);
let createdDirectory;
for (let u = 2; u <= parts.length; ++u) {
const subPath = parts.slice(0, u).join(this.pathUtils.sep);
if (!this.existsSync(subPath)) {
try {
this.mkdirSync(subPath);
} catch (error) {
if (error.code === `EEXIST`) {
continue;
} else {
throw error;
}
}
createdDirectory ??= subPath;
if (chmod != null)
this.chmodSync(subPath, chmod);
if (utimes != null) {
this.utimesSync(subPath, utimes[0], utimes[1]);
} else {
const parentStat = this.statSync(this.pathUtils.dirname(subPath));
this.utimesSync(subPath, parentStat.atime, parentStat.mtime);
}
}
}
return createdDirectory;
}
async copyPromise(destination, source, { baseFs = this, overwrite = true, stableSort = false, stableTime = false, linkStrategy = null } = {}) {
return await copyPromise(this, destination, baseFs, source, { overwrite, stableSort, stableTime, linkStrategy });
}
copySync(destination, source, { baseFs = this, overwrite = true } = {}) {