bililive-cli 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3515 @@
1
+ 'use strict';
2
+
3
+ var os$3 = require('node:os');
4
+ var path$5 = require('node:path');
5
+ var fs$3 = require('node:fs');
6
+ var index = require('./bili-CQgv-F-q.js');
7
+ var require$$0$1 = require('fs');
8
+ var require$$0 = require('path');
9
+ var require$$0$2 = require('child_process');
10
+ var require$$0$3 = require('os');
11
+ var require$$1 = require('util');
12
+ var require$$5 = require('assert');
13
+ var require$$0$4 = require('events');
14
+ var require$$0$6 = require('buffer');
15
+ var require$$0$5 = require('stream');
16
+ var process$2 = require('node:process');
17
+ var v4 = require('./v4-D4KzFnn8.js');
18
+ require('node:crypto');
19
+ require('node:child_process');
20
+ require('http');
21
+ require('https');
22
+ require('url');
23
+ require('tty');
24
+ require('zlib');
25
+ require('node:events');
26
+ require('crypto');
27
+ require('node:url');
28
+ require('constants');
29
+ require('node:module');
30
+ require('net');
31
+ require('dns');
32
+ require('tls');
33
+ require('@autorecord/manager');
34
+ require('@autorecord/douyu-recorder');
35
+
36
+ var xdgTrashdir$1 = {exports: {}};
37
+
38
+ var df$5 = {exports: {}};
39
+
40
+ var execa$2 = {exports: {}};
41
+
42
+ var crossSpawn$1 = {exports: {}};
43
+
44
+ const isWindows = process.platform === 'win32' ||
45
+ process.env.OSTYPE === 'cygwin' ||
46
+ process.env.OSTYPE === 'msys';
47
+
48
+ const path$4 = require$$0;
49
+ const COLON = isWindows ? ';' : ':';
50
+ const isexe = index.isexe_1;
51
+
52
+ const getNotFoundError = (cmd) =>
53
+ Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' });
54
+
55
+ const getPathInfo = (cmd, opt) => {
56
+ const colon = opt.colon || COLON;
57
+
58
+ // If it has a slash, then we don't bother searching the pathenv.
59
+ // just check the file itself, and that's it.
60
+ const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
61
+ : (
62
+ [
63
+ // windows always checks the cwd first
64
+ ...(isWindows ? [process.cwd()] : []),
65
+ ...(opt.path || process.env.PATH ||
66
+ /* istanbul ignore next: very unusual */ '').split(colon),
67
+ ]
68
+ );
69
+ const pathExtExe = isWindows
70
+ ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
71
+ : '';
72
+ const pathExt = isWindows ? pathExtExe.split(colon) : [''];
73
+
74
+ if (isWindows) {
75
+ if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
76
+ pathExt.unshift('');
77
+ }
78
+
79
+ return {
80
+ pathEnv,
81
+ pathExt,
82
+ pathExtExe,
83
+ }
84
+ };
85
+
86
+ const which$1 = (cmd, opt, cb) => {
87
+ if (typeof opt === 'function') {
88
+ cb = opt;
89
+ opt = {};
90
+ }
91
+ if (!opt)
92
+ opt = {};
93
+
94
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
95
+ const found = [];
96
+
97
+ const step = i => new Promise((resolve, reject) => {
98
+ if (i === pathEnv.length)
99
+ return opt.all && found.length ? resolve(found)
100
+ : reject(getNotFoundError(cmd))
101
+
102
+ const ppRaw = pathEnv[i];
103
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
104
+
105
+ const pCmd = path$4.join(pathPart, cmd);
106
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
107
+ : pCmd;
108
+
109
+ resolve(subStep(p, i, 0));
110
+ });
111
+
112
+ const subStep = (p, i, ii) => new Promise((resolve, reject) => {
113
+ if (ii === pathExt.length)
114
+ return resolve(step(i + 1))
115
+ const ext = pathExt[ii];
116
+ isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
117
+ if (!er && is) {
118
+ if (opt.all)
119
+ found.push(p + ext);
120
+ else
121
+ return resolve(p + ext)
122
+ }
123
+ return resolve(subStep(p, i, ii + 1))
124
+ });
125
+ });
126
+
127
+ return cb ? step(0).then(res => cb(null, res), cb) : step(0)
128
+ };
129
+
130
+ const whichSync = (cmd, opt) => {
131
+ opt = opt || {};
132
+
133
+ const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
134
+ const found = [];
135
+
136
+ for (let i = 0; i < pathEnv.length; i ++) {
137
+ const ppRaw = pathEnv[i];
138
+ const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
139
+
140
+ const pCmd = path$4.join(pathPart, cmd);
141
+ const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
142
+ : pCmd;
143
+
144
+ for (let j = 0; j < pathExt.length; j ++) {
145
+ const cur = p + pathExt[j];
146
+ try {
147
+ const is = isexe.sync(cur, { pathExt: pathExtExe });
148
+ if (is) {
149
+ if (opt.all)
150
+ found.push(cur);
151
+ else
152
+ return cur
153
+ }
154
+ } catch (ex) {}
155
+ }
156
+ }
157
+
158
+ if (opt.all && found.length)
159
+ return found
160
+
161
+ if (opt.nothrow)
162
+ return null
163
+
164
+ throw getNotFoundError(cmd)
165
+ };
166
+
167
+ var which_1 = which$1;
168
+ which$1.sync = whichSync;
169
+
170
+ var pathKey$1 = {exports: {}};
171
+
172
+ const pathKey = (options = {}) => {
173
+ const environment = options.env || process.env;
174
+ const platform = options.platform || process.platform;
175
+
176
+ if (platform !== 'win32') {
177
+ return 'PATH';
178
+ }
179
+
180
+ return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
181
+ };
182
+
183
+ pathKey$1.exports = pathKey;
184
+ // TODO: Remove this for the next major release
185
+ pathKey$1.exports.default = pathKey;
186
+
187
+ var pathKeyExports = pathKey$1.exports;
188
+
189
+ const path$3 = require$$0;
190
+ const which = which_1;
191
+ const getPathKey = pathKeyExports;
192
+
193
+ function resolveCommandAttempt(parsed, withoutPathExt) {
194
+ const env = parsed.options.env || process.env;
195
+ const cwd = process.cwd();
196
+ const hasCustomCwd = parsed.options.cwd != null;
197
+ // Worker threads do not have process.chdir()
198
+ const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
199
+
200
+ // If a custom `cwd` was specified, we need to change the process cwd
201
+ // because `which` will do stat calls but does not support a custom cwd
202
+ if (shouldSwitchCwd) {
203
+ try {
204
+ process.chdir(parsed.options.cwd);
205
+ } catch (err) {
206
+ /* Empty */
207
+ }
208
+ }
209
+
210
+ let resolved;
211
+
212
+ try {
213
+ resolved = which.sync(parsed.command, {
214
+ path: env[getPathKey({ env })],
215
+ pathExt: withoutPathExt ? path$3.delimiter : undefined,
216
+ });
217
+ } catch (e) {
218
+ /* Empty */
219
+ } finally {
220
+ if (shouldSwitchCwd) {
221
+ process.chdir(cwd);
222
+ }
223
+ }
224
+
225
+ // If we successfully resolved, ensure that an absolute path is returned
226
+ // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
227
+ if (resolved) {
228
+ resolved = path$3.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
229
+ }
230
+
231
+ return resolved;
232
+ }
233
+
234
+ function resolveCommand$1(parsed) {
235
+ return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
236
+ }
237
+
238
+ var resolveCommand_1 = resolveCommand$1;
239
+
240
+ var _escape = {};
241
+
242
+ // See http://www.robvanderwoude.com/escapechars.php
243
+ const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
244
+
245
+ function escapeCommand(arg) {
246
+ // Escape meta chars
247
+ arg = arg.replace(metaCharsRegExp, '^$1');
248
+
249
+ return arg;
250
+ }
251
+
252
+ function escapeArgument(arg, doubleEscapeMetaChars) {
253
+ // Convert to string
254
+ arg = `${arg}`;
255
+
256
+ // Algorithm below is based on https://qntm.org/cmd
257
+
258
+ // Sequence of backslashes followed by a double quote:
259
+ // double up all the backslashes and escape the double quote
260
+ arg = arg.replace(/(\\*)"/g, '$1$1\\"');
261
+
262
+ // Sequence of backslashes followed by the end of the string
263
+ // (which will become a double quote later):
264
+ // double up all the backslashes
265
+ arg = arg.replace(/(\\*)$/, '$1$1');
266
+
267
+ // All other backslashes occur literally
268
+
269
+ // Quote the whole thing:
270
+ arg = `"${arg}"`;
271
+
272
+ // Escape meta chars
273
+ arg = arg.replace(metaCharsRegExp, '^$1');
274
+
275
+ // Double escape meta chars if necessary
276
+ if (doubleEscapeMetaChars) {
277
+ arg = arg.replace(metaCharsRegExp, '^$1');
278
+ }
279
+
280
+ return arg;
281
+ }
282
+
283
+ _escape.command = escapeCommand;
284
+ _escape.argument = escapeArgument;
285
+
286
+ var shebangRegex$1 = /^#!(.*)/;
287
+
288
+ const shebangRegex = shebangRegex$1;
289
+
290
+ var shebangCommand$1 = (string = '') => {
291
+ const match = string.match(shebangRegex);
292
+
293
+ if (!match) {
294
+ return null;
295
+ }
296
+
297
+ const [path, argument] = match[0].replace(/#! ?/, '').split(' ');
298
+ const binary = path.split('/').pop();
299
+
300
+ if (binary === 'env') {
301
+ return argument;
302
+ }
303
+
304
+ return argument ? `${binary} ${argument}` : binary;
305
+ };
306
+
307
+ const fs$2 = require$$0$1;
308
+ const shebangCommand = shebangCommand$1;
309
+
310
+ function readShebang$1(command) {
311
+ // Read the first 150 bytes from the file
312
+ const size = 150;
313
+ const buffer = Buffer.alloc(size);
314
+
315
+ let fd;
316
+
317
+ try {
318
+ fd = fs$2.openSync(command, 'r');
319
+ fs$2.readSync(fd, buffer, 0, size, 0);
320
+ fs$2.closeSync(fd);
321
+ } catch (e) { /* Empty */ }
322
+
323
+ // Attempt to extract shebang (null is returned if not a shebang)
324
+ return shebangCommand(buffer.toString());
325
+ }
326
+
327
+ var readShebang_1 = readShebang$1;
328
+
329
+ const path$2 = require$$0;
330
+ const resolveCommand = resolveCommand_1;
331
+ const escape = _escape;
332
+ const readShebang = readShebang_1;
333
+
334
+ const isWin$2 = process.platform === 'win32';
335
+ const isExecutableRegExp = /\.(?:com|exe)$/i;
336
+ const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
337
+
338
+ function detectShebang(parsed) {
339
+ parsed.file = resolveCommand(parsed);
340
+
341
+ const shebang = parsed.file && readShebang(parsed.file);
342
+
343
+ if (shebang) {
344
+ parsed.args.unshift(parsed.file);
345
+ parsed.command = shebang;
346
+
347
+ return resolveCommand(parsed);
348
+ }
349
+
350
+ return parsed.file;
351
+ }
352
+
353
+ function parseNonShell(parsed) {
354
+ if (!isWin$2) {
355
+ return parsed;
356
+ }
357
+
358
+ // Detect & add support for shebangs
359
+ const commandFile = detectShebang(parsed);
360
+
361
+ // We don't need a shell if the command filename is an executable
362
+ const needsShell = !isExecutableRegExp.test(commandFile);
363
+
364
+ // If a shell is required, use cmd.exe and take care of escaping everything correctly
365
+ // Note that `forceShell` is an hidden option used only in tests
366
+ if (parsed.options.forceShell || needsShell) {
367
+ // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
368
+ // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
369
+ // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
370
+ // we need to double escape them
371
+ const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
372
+
373
+ // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
374
+ // This is necessary otherwise it will always fail with ENOENT in those cases
375
+ parsed.command = path$2.normalize(parsed.command);
376
+
377
+ // Escape command & arguments
378
+ parsed.command = escape.command(parsed.command);
379
+ parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
380
+
381
+ const shellCommand = [parsed.command].concat(parsed.args).join(' ');
382
+
383
+ parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
384
+ parsed.command = process.env.comspec || 'cmd.exe';
385
+ parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
386
+ }
387
+
388
+ return parsed;
389
+ }
390
+
391
+ function parse$1(command, args, options) {
392
+ // Normalize arguments, similar to nodejs
393
+ if (args && !Array.isArray(args)) {
394
+ options = args;
395
+ args = null;
396
+ }
397
+
398
+ args = args ? args.slice(0) : []; // Clone array to avoid changing the original
399
+ options = Object.assign({}, options); // Clone object to avoid changing the original
400
+
401
+ // Build our parsed object
402
+ const parsed = {
403
+ command,
404
+ args,
405
+ options,
406
+ file: undefined,
407
+ original: {
408
+ command,
409
+ args,
410
+ },
411
+ };
412
+
413
+ // Delegate further parsing to shell or non-shell
414
+ return options.shell ? parsed : parseNonShell(parsed);
415
+ }
416
+
417
+ var parse_1 = parse$1;
418
+
419
+ const isWin$1 = process.platform === 'win32';
420
+
421
+ function notFoundError(original, syscall) {
422
+ return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
423
+ code: 'ENOENT',
424
+ errno: 'ENOENT',
425
+ syscall: `${syscall} ${original.command}`,
426
+ path: original.command,
427
+ spawnargs: original.args,
428
+ });
429
+ }
430
+
431
+ function hookChildProcess(cp, parsed) {
432
+ if (!isWin$1) {
433
+ return;
434
+ }
435
+
436
+ const originalEmit = cp.emit;
437
+
438
+ cp.emit = function (name, arg1) {
439
+ // If emitting "exit" event and exit code is 1, we need to check if
440
+ // the command exists and emit an "error" instead
441
+ // See https://github.com/IndigoUnited/node-cross-spawn/issues/16
442
+ if (name === 'exit') {
443
+ const err = verifyENOENT(arg1, parsed);
444
+
445
+ if (err) {
446
+ return originalEmit.call(cp, 'error', err);
447
+ }
448
+ }
449
+
450
+ return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
451
+ };
452
+ }
453
+
454
+ function verifyENOENT(status, parsed) {
455
+ if (isWin$1 && status === 1 && !parsed.file) {
456
+ return notFoundError(parsed.original, 'spawn');
457
+ }
458
+
459
+ return null;
460
+ }
461
+
462
+ function verifyENOENTSync(status, parsed) {
463
+ if (isWin$1 && status === 1 && !parsed.file) {
464
+ return notFoundError(parsed.original, 'spawnSync');
465
+ }
466
+
467
+ return null;
468
+ }
469
+
470
+ var enoent$1 = {
471
+ hookChildProcess,
472
+ verifyENOENT,
473
+ verifyENOENTSync,
474
+ notFoundError,
475
+ };
476
+
477
+ const cp = require$$0$2;
478
+ const parse = parse_1;
479
+ const enoent = enoent$1;
480
+
481
+ function spawn(command, args, options) {
482
+ // Parse the arguments
483
+ const parsed = parse(command, args, options);
484
+
485
+ // Spawn the child process
486
+ const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
487
+
488
+ // Hook into child process "exit" event to emit an error if the command
489
+ // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
490
+ enoent.hookChildProcess(spawned, parsed);
491
+
492
+ return spawned;
493
+ }
494
+
495
+ function spawnSync(command, args, options) {
496
+ // Parse the arguments
497
+ const parsed = parse(command, args, options);
498
+
499
+ // Spawn the child process
500
+ const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
501
+
502
+ // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
503
+ result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
504
+
505
+ return result;
506
+ }
507
+
508
+ crossSpawn$1.exports = spawn;
509
+ crossSpawn$1.exports.spawn = spawn;
510
+ crossSpawn$1.exports.sync = spawnSync;
511
+
512
+ crossSpawn$1.exports._parse = parse;
513
+ crossSpawn$1.exports._enoent = enoent;
514
+
515
+ var crossSpawnExports = crossSpawn$1.exports;
516
+
517
+ var stripFinalNewline$1 = input => {
518
+ const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt();
519
+ const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt();
520
+
521
+ if (input[input.length - 1] === LF) {
522
+ input = input.slice(0, input.length - 1);
523
+ }
524
+
525
+ if (input[input.length - 1] === CR) {
526
+ input = input.slice(0, input.length - 1);
527
+ }
528
+
529
+ return input;
530
+ };
531
+
532
+ var npmRunPath$1 = {exports: {}};
533
+
534
+ npmRunPath$1.exports;
535
+
536
+ (function (module) {
537
+ const path = require$$0;
538
+ const pathKey = pathKeyExports;
539
+
540
+ const npmRunPath = options => {
541
+ options = {
542
+ cwd: process.cwd(),
543
+ path: process.env[pathKey()],
544
+ ...options
545
+ };
546
+
547
+ let previous;
548
+ let cwdPath = path.resolve(options.cwd);
549
+ const result = [];
550
+
551
+ while (previous !== cwdPath) {
552
+ result.push(path.join(cwdPath, 'node_modules/.bin'));
553
+ previous = cwdPath;
554
+ cwdPath = path.resolve(cwdPath, '..');
555
+ }
556
+
557
+ // Ensure the running `node` binary is used
558
+ result.push(path.dirname(process.execPath));
559
+
560
+ return result.concat(options.path).join(path.delimiter);
561
+ };
562
+
563
+ module.exports = npmRunPath;
564
+ // TODO: Remove this for the next major release
565
+ module.exports.default = npmRunPath;
566
+
567
+ module.exports.env = options => {
568
+ options = {
569
+ env: process.env,
570
+ ...options
571
+ };
572
+
573
+ const env = {...options.env};
574
+ const path = pathKey({env});
575
+
576
+ options.path = env[path];
577
+ env[path] = module.exports(options);
578
+
579
+ return env;
580
+ };
581
+ } (npmRunPath$1));
582
+
583
+ var npmRunPathExports = npmRunPath$1.exports;
584
+
585
+ var onetime$2 = {exports: {}};
586
+
587
+ var mimicFn$2 = {exports: {}};
588
+
589
+ const mimicFn$1 = (to, from) => {
590
+ for (const prop of Reflect.ownKeys(from)) {
591
+ Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
592
+ }
593
+
594
+ return to;
595
+ };
596
+
597
+ mimicFn$2.exports = mimicFn$1;
598
+ // TODO: Remove this for the next major release
599
+ mimicFn$2.exports.default = mimicFn$1;
600
+
601
+ var mimicFnExports = mimicFn$2.exports;
602
+
603
+ const mimicFn = mimicFnExports;
604
+
605
+ const calledFunctions = new WeakMap();
606
+
607
+ const onetime$1 = (function_, options = {}) => {
608
+ if (typeof function_ !== 'function') {
609
+ throw new TypeError('Expected a function');
610
+ }
611
+
612
+ let returnValue;
613
+ let callCount = 0;
614
+ const functionName = function_.displayName || function_.name || '<anonymous>';
615
+
616
+ const onetime = function (...arguments_) {
617
+ calledFunctions.set(onetime, ++callCount);
618
+
619
+ if (callCount === 1) {
620
+ returnValue = function_.apply(this, arguments_);
621
+ function_ = null;
622
+ } else if (options.throw === true) {
623
+ throw new Error(`Function \`${functionName}\` can only be called once`);
624
+ }
625
+
626
+ return returnValue;
627
+ };
628
+
629
+ mimicFn(onetime, function_);
630
+ calledFunctions.set(onetime, callCount);
631
+
632
+ return onetime;
633
+ };
634
+
635
+ onetime$2.exports = onetime$1;
636
+ // TODO: Remove this for the next major release
637
+ onetime$2.exports.default = onetime$1;
638
+
639
+ onetime$2.exports.callCount = function_ => {
640
+ if (!calledFunctions.has(function_)) {
641
+ throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
642
+ }
643
+
644
+ return calledFunctions.get(function_);
645
+ };
646
+
647
+ var onetimeExports = onetime$2.exports;
648
+
649
+ const os$2 = require$$0$3;
650
+ const util = require$$1;
651
+
652
+ const getCode = (error, code) => {
653
+ if (error && error.code) {
654
+ return [error.code, os$2.constants.errno[error.code]];
655
+ }
656
+
657
+ if (Number.isInteger(code)) {
658
+ return [util.getSystemErrorName(-code), code];
659
+ }
660
+
661
+ return [];
662
+ };
663
+
664
+ const getErrorPrefix = ({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled}) => {
665
+ if (timedOut) {
666
+ return `timed out after ${timeout} milliseconds`;
667
+ }
668
+
669
+ if (isCanceled) {
670
+ return 'was canceled';
671
+ }
672
+
673
+ if (signal) {
674
+ return `was killed with ${signal}`;
675
+ }
676
+
677
+ if (exitCode !== undefined) {
678
+ return `failed with exit code ${exitCode} (${exitCodeName})`;
679
+ }
680
+
681
+ return 'failed';
682
+ };
683
+
684
+ const makeError$1 = ({
685
+ stdout,
686
+ stderr,
687
+ all,
688
+ error,
689
+ signal,
690
+ code,
691
+ command,
692
+ timedOut,
693
+ isCanceled,
694
+ killed,
695
+ parsed: {options: {timeout}}
696
+ }) => {
697
+ const [exitCodeName, exitCode] = getCode(error, code);
698
+
699
+ const prefix = getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled});
700
+ const message = `Command ${prefix}: ${command}`;
701
+
702
+ if (error instanceof Error) {
703
+ error.originalMessage = error.message;
704
+ error.message = `${message}\n${error.message}`;
705
+ } else {
706
+ error = new Error(message);
707
+ }
708
+
709
+ error.command = command;
710
+ delete error.code;
711
+ error.exitCode = exitCode;
712
+ error.exitCodeName = exitCodeName;
713
+ error.stdout = stdout;
714
+ error.stderr = stderr;
715
+
716
+ if (all !== undefined) {
717
+ error.all = all;
718
+ }
719
+
720
+ if ('bufferedData' in error) {
721
+ delete error.bufferedData;
722
+ }
723
+
724
+ error.failed = true;
725
+ error.timedOut = Boolean(timedOut);
726
+ error.isCanceled = isCanceled;
727
+ error.killed = killed && !timedOut;
728
+ // `signal` emitted on `spawned.on('exit')` event can be `null`. We normalize
729
+ // it to `undefined`
730
+ error.signal = signal || undefined;
731
+
732
+ return error;
733
+ };
734
+
735
+ var error = makeError$1;
736
+
737
+ var stdio = {exports: {}};
738
+
739
+ const aliases = ['stdin', 'stdout', 'stderr'];
740
+
741
+ const hasAlias = opts => aliases.some(alias => opts[alias] !== undefined);
742
+
743
+ const normalizeStdio$1 = opts => {
744
+ if (!opts) {
745
+ return;
746
+ }
747
+
748
+ const {stdio} = opts;
749
+
750
+ if (stdio === undefined) {
751
+ return aliases.map(alias => opts[alias]);
752
+ }
753
+
754
+ if (hasAlias(opts)) {
755
+ throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
756
+ }
757
+
758
+ if (typeof stdio === 'string') {
759
+ return stdio;
760
+ }
761
+
762
+ if (!Array.isArray(stdio)) {
763
+ throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
764
+ }
765
+
766
+ const length = Math.max(stdio.length, aliases.length);
767
+ return Array.from({length}, (value, index) => stdio[index]);
768
+ };
769
+
770
+ stdio.exports = normalizeStdio$1;
771
+
772
+ // `ipc` is pushed unless it is already present
773
+ stdio.exports.node = opts => {
774
+ const stdio = normalizeStdio$1(opts);
775
+
776
+ if (stdio === 'ipc') {
777
+ return 'ipc';
778
+ }
779
+
780
+ if (stdio === undefined || typeof stdio === 'string') {
781
+ return [stdio, stdio, stdio, 'ipc'];
782
+ }
783
+
784
+ if (stdio.includes('ipc')) {
785
+ return stdio;
786
+ }
787
+
788
+ return [...stdio, 'ipc'];
789
+ };
790
+
791
+ var stdioExports = stdio.exports;
792
+
793
+ var signalExit = {exports: {}};
794
+
795
+ var signals$1 = {exports: {}};
796
+
797
+ var hasRequiredSignals;
798
+
799
+ function requireSignals () {
800
+ if (hasRequiredSignals) return signals$1.exports;
801
+ hasRequiredSignals = 1;
802
+ (function (module) {
803
+ // This is not the set of all possible signals.
804
+ //
805
+ // It IS, however, the set of all signals that trigger
806
+ // an exit on either Linux or BSD systems. Linux is a
807
+ // superset of the signal names supported on BSD, and
808
+ // the unknown signals just fail to register, so we can
809
+ // catch that easily enough.
810
+ //
811
+ // Don't bother with SIGKILL. It's uncatchable, which
812
+ // means that we can't fire any callbacks anyway.
813
+ //
814
+ // If a user does happen to register a handler on a non-
815
+ // fatal signal like SIGWINCH or something, and then
816
+ // exit, it'll end up firing `process.emit('exit')`, so
817
+ // the handler will be fired anyway.
818
+ //
819
+ // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
820
+ // artificially, inherently leave the process in a
821
+ // state from which it is not safe to try and enter JS
822
+ // listeners.
823
+ module.exports = [
824
+ 'SIGABRT',
825
+ 'SIGALRM',
826
+ 'SIGHUP',
827
+ 'SIGINT',
828
+ 'SIGTERM'
829
+ ];
830
+
831
+ if (process.platform !== 'win32') {
832
+ module.exports.push(
833
+ 'SIGVTALRM',
834
+ 'SIGXCPU',
835
+ 'SIGXFSZ',
836
+ 'SIGUSR2',
837
+ 'SIGTRAP',
838
+ 'SIGSYS',
839
+ 'SIGQUIT',
840
+ 'SIGIOT'
841
+ // should detect profiler and enable/disable accordingly.
842
+ // see #21
843
+ // 'SIGPROF'
844
+ );
845
+ }
846
+
847
+ if (process.platform === 'linux') {
848
+ module.exports.push(
849
+ 'SIGIO',
850
+ 'SIGPOLL',
851
+ 'SIGPWR',
852
+ 'SIGSTKFLT',
853
+ 'SIGUNUSED'
854
+ );
855
+ }
856
+ } (signals$1));
857
+ return signals$1.exports;
858
+ }
859
+
860
+ // Note: since nyc uses this module to output coverage, any lines
861
+ // that are in the direct sync flow of nyc's outputCoverage are
862
+ // ignored, since we can never get coverage for them.
863
+ // grab a reference to node's real process object right away
864
+ var process$1 = index.commonjsGlobal.process;
865
+
866
+ const processOk = function (process) {
867
+ return process &&
868
+ typeof process === 'object' &&
869
+ typeof process.removeListener === 'function' &&
870
+ typeof process.emit === 'function' &&
871
+ typeof process.reallyExit === 'function' &&
872
+ typeof process.listeners === 'function' &&
873
+ typeof process.kill === 'function' &&
874
+ typeof process.pid === 'number' &&
875
+ typeof process.on === 'function'
876
+ };
877
+
878
+ // some kind of non-node environment, just no-op
879
+ /* istanbul ignore if */
880
+ if (!processOk(process$1)) {
881
+ signalExit.exports = function () {
882
+ return function () {}
883
+ };
884
+ } else {
885
+ var assert = require$$5;
886
+ var signals = requireSignals();
887
+ var isWin = /^win/i.test(process$1.platform);
888
+
889
+ var EE = require$$0$4;
890
+ /* istanbul ignore if */
891
+ if (typeof EE !== 'function') {
892
+ EE = EE.EventEmitter;
893
+ }
894
+
895
+ var emitter;
896
+ if (process$1.__signal_exit_emitter__) {
897
+ emitter = process$1.__signal_exit_emitter__;
898
+ } else {
899
+ emitter = process$1.__signal_exit_emitter__ = new EE();
900
+ emitter.count = 0;
901
+ emitter.emitted = {};
902
+ }
903
+
904
+ // Because this emitter is a global, we have to check to see if a
905
+ // previous version of this library failed to enable infinite listeners.
906
+ // I know what you're about to say. But literally everything about
907
+ // signal-exit is a compromise with evil. Get used to it.
908
+ if (!emitter.infinite) {
909
+ emitter.setMaxListeners(Infinity);
910
+ emitter.infinite = true;
911
+ }
912
+
913
+ signalExit.exports = function (cb, opts) {
914
+ /* istanbul ignore if */
915
+ if (!processOk(index.commonjsGlobal.process)) {
916
+ return function () {}
917
+ }
918
+ assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
919
+
920
+ if (loaded === false) {
921
+ load();
922
+ }
923
+
924
+ var ev = 'exit';
925
+ if (opts && opts.alwaysLast) {
926
+ ev = 'afterexit';
927
+ }
928
+
929
+ var remove = function () {
930
+ emitter.removeListener(ev, cb);
931
+ if (emitter.listeners('exit').length === 0 &&
932
+ emitter.listeners('afterexit').length === 0) {
933
+ unload();
934
+ }
935
+ };
936
+ emitter.on(ev, cb);
937
+
938
+ return remove
939
+ };
940
+
941
+ var unload = function unload () {
942
+ if (!loaded || !processOk(index.commonjsGlobal.process)) {
943
+ return
944
+ }
945
+ loaded = false;
946
+
947
+ signals.forEach(function (sig) {
948
+ try {
949
+ process$1.removeListener(sig, sigListeners[sig]);
950
+ } catch (er) {}
951
+ });
952
+ process$1.emit = originalProcessEmit;
953
+ process$1.reallyExit = originalProcessReallyExit;
954
+ emitter.count -= 1;
955
+ };
956
+ signalExit.exports.unload = unload;
957
+
958
+ var emit = function emit (event, code, signal) {
959
+ /* istanbul ignore if */
960
+ if (emitter.emitted[event]) {
961
+ return
962
+ }
963
+ emitter.emitted[event] = true;
964
+ emitter.emit(event, code, signal);
965
+ };
966
+
967
+ // { <signal>: <listener fn>, ... }
968
+ var sigListeners = {};
969
+ signals.forEach(function (sig) {
970
+ sigListeners[sig] = function listener () {
971
+ /* istanbul ignore if */
972
+ if (!processOk(index.commonjsGlobal.process)) {
973
+ return
974
+ }
975
+ // If there are no other listeners, an exit is coming!
976
+ // Simplest way: remove us and then re-send the signal.
977
+ // We know that this will kill the process, so we can
978
+ // safely emit now.
979
+ var listeners = process$1.listeners(sig);
980
+ if (listeners.length === emitter.count) {
981
+ unload();
982
+ emit('exit', null, sig);
983
+ /* istanbul ignore next */
984
+ emit('afterexit', null, sig);
985
+ /* istanbul ignore next */
986
+ if (isWin && sig === 'SIGHUP') {
987
+ // "SIGHUP" throws an `ENOSYS` error on Windows,
988
+ // so use a supported signal instead
989
+ sig = 'SIGINT';
990
+ }
991
+ /* istanbul ignore next */
992
+ process$1.kill(process$1.pid, sig);
993
+ }
994
+ };
995
+ });
996
+
997
+ signalExit.exports.signals = function () {
998
+ return signals
999
+ };
1000
+
1001
+ var loaded = false;
1002
+
1003
+ var load = function load () {
1004
+ if (loaded || !processOk(index.commonjsGlobal.process)) {
1005
+ return
1006
+ }
1007
+ loaded = true;
1008
+
1009
+ // This is the number of onSignalExit's that are in play.
1010
+ // It's important so that we can count the correct number of
1011
+ // listeners on signals, and don't wait for the other one to
1012
+ // handle it instead of us.
1013
+ emitter.count += 1;
1014
+
1015
+ signals = signals.filter(function (sig) {
1016
+ try {
1017
+ process$1.on(sig, sigListeners[sig]);
1018
+ return true
1019
+ } catch (er) {
1020
+ return false
1021
+ }
1022
+ });
1023
+
1024
+ process$1.emit = processEmit;
1025
+ process$1.reallyExit = processReallyExit;
1026
+ };
1027
+ signalExit.exports.load = load;
1028
+
1029
+ var originalProcessReallyExit = process$1.reallyExit;
1030
+ var processReallyExit = function processReallyExit (code) {
1031
+ /* istanbul ignore if */
1032
+ if (!processOk(index.commonjsGlobal.process)) {
1033
+ return
1034
+ }
1035
+ process$1.exitCode = code || /* istanbul ignore next */ 0;
1036
+ emit('exit', process$1.exitCode, null);
1037
+ /* istanbul ignore next */
1038
+ emit('afterexit', process$1.exitCode, null);
1039
+ /* istanbul ignore next */
1040
+ originalProcessReallyExit.call(process$1, process$1.exitCode);
1041
+ };
1042
+
1043
+ var originalProcessEmit = process$1.emit;
1044
+ var processEmit = function processEmit (ev, arg) {
1045
+ if (ev === 'exit' && processOk(index.commonjsGlobal.process)) {
1046
+ /* istanbul ignore else */
1047
+ if (arg !== undefined) {
1048
+ process$1.exitCode = arg;
1049
+ }
1050
+ var ret = originalProcessEmit.apply(this, arguments);
1051
+ /* istanbul ignore next */
1052
+ emit('exit', process$1.exitCode, null);
1053
+ /* istanbul ignore next */
1054
+ emit('afterexit', process$1.exitCode, null);
1055
+ /* istanbul ignore next */
1056
+ return ret
1057
+ } else {
1058
+ return originalProcessEmit.apply(this, arguments)
1059
+ }
1060
+ };
1061
+ }
1062
+
1063
+ var signalExitExports = signalExit.exports;
1064
+
1065
+ var pFinally$1 = async (
1066
+ promise,
1067
+ onFinally = (() => {})
1068
+ ) => {
1069
+ let value;
1070
+ try {
1071
+ value = await promise;
1072
+ } catch (error) {
1073
+ await onFinally();
1074
+ throw error;
1075
+ }
1076
+
1077
+ await onFinally();
1078
+ return value;
1079
+ };
1080
+
1081
+ const os$1 = require$$0$3;
1082
+ const onExit = signalExitExports;
1083
+ const pFinally = pFinally$1;
1084
+
1085
+ const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
1086
+
1087
+ // Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior
1088
+ const spawnedKill$1 = (kill, signal = 'SIGTERM', options = {}) => {
1089
+ const killResult = kill(signal);
1090
+ setKillTimeout(kill, signal, options, killResult);
1091
+ return killResult;
1092
+ };
1093
+
1094
+ const setKillTimeout = (kill, signal, options, killResult) => {
1095
+ if (!shouldForceKill(signal, options, killResult)) {
1096
+ return;
1097
+ }
1098
+
1099
+ const timeout = getForceKillAfterTimeout(options);
1100
+ setTimeout(() => {
1101
+ kill('SIGKILL');
1102
+ }, timeout).unref();
1103
+ };
1104
+
1105
+ const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {
1106
+ return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
1107
+ };
1108
+
1109
+ const isSigterm = signal => {
1110
+ return signal === os$1.constants.signals.SIGTERM ||
1111
+ (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
1112
+ };
1113
+
1114
+ const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
1115
+ if (forceKillAfterTimeout === true) {
1116
+ return DEFAULT_FORCE_KILL_TIMEOUT;
1117
+ }
1118
+
1119
+ if (!Number.isInteger(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
1120
+ throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
1121
+ }
1122
+
1123
+ return forceKillAfterTimeout;
1124
+ };
1125
+
1126
+ // `childProcess.cancel()`
1127
+ const spawnedCancel$1 = (spawned, context) => {
1128
+ const killResult = spawned.kill();
1129
+
1130
+ if (killResult) {
1131
+ context.isCanceled = true;
1132
+ }
1133
+ };
1134
+
1135
+ const timeoutKill = (spawned, signal, reject) => {
1136
+ spawned.kill(signal);
1137
+ reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));
1138
+ };
1139
+
1140
+ // `timeout` option handling
1141
+ const setupTimeout$1 = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {
1142
+ if (timeout === 0 || timeout === undefined) {
1143
+ return spawnedPromise;
1144
+ }
1145
+
1146
+ if (!Number.isInteger(timeout) || timeout < 0) {
1147
+ throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
1148
+ }
1149
+
1150
+ let timeoutId;
1151
+ const timeoutPromise = new Promise((resolve, reject) => {
1152
+ timeoutId = setTimeout(() => {
1153
+ timeoutKill(spawned, killSignal, reject);
1154
+ }, timeout);
1155
+ });
1156
+
1157
+ const safeSpawnedPromise = pFinally(spawnedPromise, () => {
1158
+ clearTimeout(timeoutId);
1159
+ });
1160
+
1161
+ return Promise.race([timeoutPromise, safeSpawnedPromise]);
1162
+ };
1163
+
1164
+ // `cleanup` option handling
1165
+ const setExitHandler$1 = (spawned, {cleanup, detached}, timedPromise) => {
1166
+ if (!cleanup || detached) {
1167
+ return timedPromise;
1168
+ }
1169
+
1170
+ const removeExitHandler = onExit(() => {
1171
+ spawned.kill();
1172
+ });
1173
+
1174
+ // TODO: Use native "finally" syntax when targeting Node.js 10
1175
+ return pFinally(timedPromise, removeExitHandler);
1176
+ };
1177
+
1178
+ var kill = {
1179
+ spawnedKill: spawnedKill$1,
1180
+ spawnedCancel: spawnedCancel$1,
1181
+ setupTimeout: setupTimeout$1,
1182
+ setExitHandler: setExitHandler$1
1183
+ };
1184
+
1185
+ const isStream$1 = stream =>
1186
+ stream !== null &&
1187
+ typeof stream === 'object' &&
1188
+ typeof stream.pipe === 'function';
1189
+
1190
+ isStream$1.writable = stream =>
1191
+ isStream$1(stream) &&
1192
+ stream.writable !== false &&
1193
+ typeof stream._write === 'function' &&
1194
+ typeof stream._writableState === 'object';
1195
+
1196
+ isStream$1.readable = stream =>
1197
+ isStream$1(stream) &&
1198
+ stream.readable !== false &&
1199
+ typeof stream._read === 'function' &&
1200
+ typeof stream._readableState === 'object';
1201
+
1202
+ isStream$1.duplex = stream =>
1203
+ isStream$1.writable(stream) &&
1204
+ isStream$1.readable(stream);
1205
+
1206
+ isStream$1.transform = stream =>
1207
+ isStream$1.duplex(stream) &&
1208
+ typeof stream._transform === 'function';
1209
+
1210
+ var isStream_1 = isStream$1;
1211
+
1212
+ var getStream$2 = {exports: {}};
1213
+
1214
+ var once$1 = index.onceExports;
1215
+
1216
+ var noop$1 = function() {};
1217
+
1218
+ var isRequest$1 = function(stream) {
1219
+ return stream.setHeader && typeof stream.abort === 'function';
1220
+ };
1221
+
1222
+ var isChildProcess = function(stream) {
1223
+ return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
1224
+ };
1225
+
1226
+ var eos$1 = function(stream, opts, callback) {
1227
+ if (typeof opts === 'function') return eos$1(stream, null, opts);
1228
+ if (!opts) opts = {};
1229
+
1230
+ callback = once$1(callback || noop$1);
1231
+
1232
+ var ws = stream._writableState;
1233
+ var rs = stream._readableState;
1234
+ var readable = opts.readable || (opts.readable !== false && stream.readable);
1235
+ var writable = opts.writable || (opts.writable !== false && stream.writable);
1236
+ var cancelled = false;
1237
+
1238
+ var onlegacyfinish = function() {
1239
+ if (!stream.writable) onfinish();
1240
+ };
1241
+
1242
+ var onfinish = function() {
1243
+ writable = false;
1244
+ if (!readable) callback.call(stream);
1245
+ };
1246
+
1247
+ var onend = function() {
1248
+ readable = false;
1249
+ if (!writable) callback.call(stream);
1250
+ };
1251
+
1252
+ var onexit = function(exitCode) {
1253
+ callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
1254
+ };
1255
+
1256
+ var onerror = function(err) {
1257
+ callback.call(stream, err);
1258
+ };
1259
+
1260
+ var onclose = function() {
1261
+ process.nextTick(onclosenexttick);
1262
+ };
1263
+
1264
+ var onclosenexttick = function() {
1265
+ if (cancelled) return;
1266
+ if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));
1267
+ if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));
1268
+ };
1269
+
1270
+ var onrequest = function() {
1271
+ stream.req.on('finish', onfinish);
1272
+ };
1273
+
1274
+ if (isRequest$1(stream)) {
1275
+ stream.on('complete', onfinish);
1276
+ stream.on('abort', onclose);
1277
+ if (stream.req) onrequest();
1278
+ else stream.on('request', onrequest);
1279
+ } else if (writable && !ws) { // legacy streams
1280
+ stream.on('end', onlegacyfinish);
1281
+ stream.on('close', onlegacyfinish);
1282
+ }
1283
+
1284
+ if (isChildProcess(stream)) stream.on('exit', onexit);
1285
+
1286
+ stream.on('end', onend);
1287
+ stream.on('finish', onfinish);
1288
+ if (opts.error !== false) stream.on('error', onerror);
1289
+ stream.on('close', onclose);
1290
+
1291
+ return function() {
1292
+ cancelled = true;
1293
+ stream.removeListener('complete', onfinish);
1294
+ stream.removeListener('abort', onclose);
1295
+ stream.removeListener('request', onrequest);
1296
+ if (stream.req) stream.req.removeListener('finish', onfinish);
1297
+ stream.removeListener('end', onlegacyfinish);
1298
+ stream.removeListener('close', onlegacyfinish);
1299
+ stream.removeListener('finish', onfinish);
1300
+ stream.removeListener('exit', onexit);
1301
+ stream.removeListener('end', onend);
1302
+ stream.removeListener('error', onerror);
1303
+ stream.removeListener('close', onclose);
1304
+ };
1305
+ };
1306
+
1307
+ var endOfStream = eos$1;
1308
+
1309
+ var once = index.onceExports;
1310
+ var eos = endOfStream;
1311
+ var fs$1 = require$$0$1; // we only need fs to get the ReadStream and WriteStream prototypes
1312
+
1313
+ var noop = function () {};
1314
+ var ancient = /^v?\.0/.test(process.version);
1315
+
1316
+ var isFn = function (fn) {
1317
+ return typeof fn === 'function'
1318
+ };
1319
+
1320
+ var isFS = function (stream) {
1321
+ if (!ancient) return false // newer node version do not need to care about fs is a special way
1322
+ if (!fs$1) return false // browser
1323
+ return (stream instanceof (fs$1.ReadStream || noop) || stream instanceof (fs$1.WriteStream || noop)) && isFn(stream.close)
1324
+ };
1325
+
1326
+ var isRequest = function (stream) {
1327
+ return stream.setHeader && isFn(stream.abort)
1328
+ };
1329
+
1330
+ var destroyer = function (stream, reading, writing, callback) {
1331
+ callback = once(callback);
1332
+
1333
+ var closed = false;
1334
+ stream.on('close', function () {
1335
+ closed = true;
1336
+ });
1337
+
1338
+ eos(stream, {readable: reading, writable: writing}, function (err) {
1339
+ if (err) return callback(err)
1340
+ closed = true;
1341
+ callback();
1342
+ });
1343
+
1344
+ var destroyed = false;
1345
+ return function (err) {
1346
+ if (closed) return
1347
+ if (destroyed) return
1348
+ destroyed = true;
1349
+
1350
+ if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks
1351
+ if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want
1352
+
1353
+ if (isFn(stream.destroy)) return stream.destroy()
1354
+
1355
+ callback(err || new Error('stream was destroyed'));
1356
+ }
1357
+ };
1358
+
1359
+ var call = function (fn) {
1360
+ fn();
1361
+ };
1362
+
1363
+ var pipe = function (from, to) {
1364
+ return from.pipe(to)
1365
+ };
1366
+
1367
+ var pump$1 = function () {
1368
+ var streams = Array.prototype.slice.call(arguments);
1369
+ var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop;
1370
+
1371
+ if (Array.isArray(streams[0])) streams = streams[0];
1372
+ if (streams.length < 2) throw new Error('pump requires two streams per minimum')
1373
+
1374
+ var error;
1375
+ var destroys = streams.map(function (stream, i) {
1376
+ var reading = i < streams.length - 1;
1377
+ var writing = i > 0;
1378
+ return destroyer(stream, reading, writing, function (err) {
1379
+ if (!error) error = err;
1380
+ if (err) destroys.forEach(call);
1381
+ if (reading) return
1382
+ destroys.forEach(call);
1383
+ callback(error);
1384
+ })
1385
+ });
1386
+
1387
+ return streams.reduce(pipe)
1388
+ };
1389
+
1390
+ var pump_1 = pump$1;
1391
+
1392
+ const {PassThrough: PassThroughStream} = require$$0$5;
1393
+
1394
+ var bufferStream$1 = options => {
1395
+ options = {...options};
1396
+
1397
+ const {array} = options;
1398
+ let {encoding} = options;
1399
+ const isBuffer = encoding === 'buffer';
1400
+ let objectMode = false;
1401
+
1402
+ if (array) {
1403
+ objectMode = !(encoding || isBuffer);
1404
+ } else {
1405
+ encoding = encoding || 'utf8';
1406
+ }
1407
+
1408
+ if (isBuffer) {
1409
+ encoding = null;
1410
+ }
1411
+
1412
+ const stream = new PassThroughStream({objectMode});
1413
+
1414
+ if (encoding) {
1415
+ stream.setEncoding(encoding);
1416
+ }
1417
+
1418
+ let length = 0;
1419
+ const chunks = [];
1420
+
1421
+ stream.on('data', chunk => {
1422
+ chunks.push(chunk);
1423
+
1424
+ if (objectMode) {
1425
+ length = chunks.length;
1426
+ } else {
1427
+ length += chunk.length;
1428
+ }
1429
+ });
1430
+
1431
+ stream.getBufferedValue = () => {
1432
+ if (array) {
1433
+ return chunks;
1434
+ }
1435
+
1436
+ return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
1437
+ };
1438
+
1439
+ stream.getBufferedLength = () => length;
1440
+
1441
+ return stream;
1442
+ };
1443
+
1444
+ const {constants: BufferConstants} = require$$0$6;
1445
+ const pump = pump_1;
1446
+ const bufferStream = bufferStream$1;
1447
+
1448
+ class MaxBufferError extends Error {
1449
+ constructor() {
1450
+ super('maxBuffer exceeded');
1451
+ this.name = 'MaxBufferError';
1452
+ }
1453
+ }
1454
+
1455
+ async function getStream$1(inputStream, options) {
1456
+ if (!inputStream) {
1457
+ return Promise.reject(new Error('Expected a stream'));
1458
+ }
1459
+
1460
+ options = {
1461
+ maxBuffer: Infinity,
1462
+ ...options
1463
+ };
1464
+
1465
+ const {maxBuffer} = options;
1466
+
1467
+ let stream;
1468
+ await new Promise((resolve, reject) => {
1469
+ const rejectPromise = error => {
1470
+ // Don't retrieve an oversized buffer.
1471
+ if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
1472
+ error.bufferedData = stream.getBufferedValue();
1473
+ }
1474
+
1475
+ reject(error);
1476
+ };
1477
+
1478
+ stream = pump(inputStream, bufferStream(options), error => {
1479
+ if (error) {
1480
+ rejectPromise(error);
1481
+ return;
1482
+ }
1483
+
1484
+ resolve();
1485
+ });
1486
+
1487
+ stream.on('data', () => {
1488
+ if (stream.getBufferedLength() > maxBuffer) {
1489
+ rejectPromise(new MaxBufferError());
1490
+ }
1491
+ });
1492
+ });
1493
+
1494
+ return stream.getBufferedValue();
1495
+ }
1496
+
1497
+ getStream$2.exports = getStream$1;
1498
+ // TODO: Remove this for the next major release
1499
+ getStream$2.exports.default = getStream$1;
1500
+ getStream$2.exports.buffer = (stream, options) => getStream$1(stream, {...options, encoding: 'buffer'});
1501
+ getStream$2.exports.array = (stream, options) => getStream$1(stream, {...options, array: true});
1502
+ getStream$2.exports.MaxBufferError = MaxBufferError;
1503
+
1504
+ var getStreamExports = getStream$2.exports;
1505
+
1506
+ const { PassThrough } = require$$0$5;
1507
+
1508
+ var mergeStream$1 = function (/*streams...*/) {
1509
+ var sources = [];
1510
+ var output = new PassThrough({objectMode: true});
1511
+
1512
+ output.setMaxListeners(0);
1513
+
1514
+ output.add = add;
1515
+ output.isEmpty = isEmpty;
1516
+
1517
+ output.on('unpipe', remove);
1518
+
1519
+ Array.prototype.slice.call(arguments).forEach(add);
1520
+
1521
+ return output
1522
+
1523
+ function add (source) {
1524
+ if (Array.isArray(source)) {
1525
+ source.forEach(add);
1526
+ return this
1527
+ }
1528
+
1529
+ sources.push(source);
1530
+ source.once('end', remove.bind(null, source));
1531
+ source.once('error', output.emit.bind(output, 'error'));
1532
+ source.pipe(output, {end: false});
1533
+ return this
1534
+ }
1535
+
1536
+ function isEmpty () {
1537
+ return sources.length == 0;
1538
+ }
1539
+
1540
+ function remove (source) {
1541
+ sources = sources.filter(function (it) { return it !== source });
1542
+ if (!sources.length && output.readable) { output.end(); }
1543
+ }
1544
+ };
1545
+
1546
+ const isStream = isStream_1;
1547
+ const getStream = getStreamExports;
1548
+ const mergeStream = mergeStream$1;
1549
+
1550
+ // `input` option
1551
+ const handleInput$1 = (spawned, input) => {
1552
+ // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852
1553
+ // TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0
1554
+ if (input === undefined || spawned.stdin === undefined) {
1555
+ return;
1556
+ }
1557
+
1558
+ if (isStream(input)) {
1559
+ input.pipe(spawned.stdin);
1560
+ } else {
1561
+ spawned.stdin.end(input);
1562
+ }
1563
+ };
1564
+
1565
+ // `all` interleaves `stdout` and `stderr`
1566
+ const makeAllStream$1 = spawned => {
1567
+ if (!spawned.stdout && !spawned.stderr) {
1568
+ return;
1569
+ }
1570
+
1571
+ const mixed = mergeStream();
1572
+
1573
+ if (spawned.stdout) {
1574
+ mixed.add(spawned.stdout);
1575
+ }
1576
+
1577
+ if (spawned.stderr) {
1578
+ mixed.add(spawned.stderr);
1579
+ }
1580
+
1581
+ return mixed;
1582
+ };
1583
+
1584
+ // On failure, `result.stdout|stderr|all` should contain the currently buffered stream
1585
+ const getBufferedData = async (stream, streamPromise) => {
1586
+ if (!stream) {
1587
+ return;
1588
+ }
1589
+
1590
+ stream.destroy();
1591
+
1592
+ try {
1593
+ return await streamPromise;
1594
+ } catch (error) {
1595
+ return error.bufferedData;
1596
+ }
1597
+ };
1598
+
1599
+ const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {
1600
+ if (!stream) {
1601
+ return;
1602
+ }
1603
+
1604
+ if (!buffer) {
1605
+ // TODO: Use `ret = util.promisify(stream.finished)(stream);` when targeting Node.js 10
1606
+ return new Promise((resolve, reject) => {
1607
+ stream
1608
+ .once('end', resolve)
1609
+ .once('error', reject);
1610
+ });
1611
+ }
1612
+
1613
+ if (encoding) {
1614
+ return getStream(stream, {encoding, maxBuffer});
1615
+ }
1616
+
1617
+ return getStream.buffer(stream, {maxBuffer});
1618
+ };
1619
+
1620
+ // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)
1621
+ const getSpawnedResult$1 = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {
1622
+ const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});
1623
+ const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});
1624
+ const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});
1625
+
1626
+ try {
1627
+ return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
1628
+ } catch (error) {
1629
+ return Promise.all([
1630
+ {error, code: error.code, signal: error.signal, timedOut: error.timedOut},
1631
+ getBufferedData(stdout, stdoutPromise),
1632
+ getBufferedData(stderr, stderrPromise),
1633
+ getBufferedData(all, allPromise)
1634
+ ]);
1635
+ }
1636
+ };
1637
+
1638
+ const validateInputSync$1 = ({input}) => {
1639
+ if (isStream(input)) {
1640
+ throw new TypeError('The `input` option cannot be a stream in sync mode');
1641
+ }
1642
+ };
1643
+
1644
+ var stream = {
1645
+ handleInput: handleInput$1,
1646
+ makeAllStream: makeAllStream$1,
1647
+ getSpawnedResult: getSpawnedResult$1,
1648
+ validateInputSync: validateInputSync$1
1649
+ };
1650
+
1651
+ const mergePromiseProperty = (spawned, promise, property) => {
1652
+ // Starting the main `promise` is deferred to avoid consuming streams
1653
+ const value = typeof promise === 'function' ?
1654
+ (...args) => promise()[property](...args) :
1655
+ promise[property].bind(promise);
1656
+
1657
+ Object.defineProperty(spawned, property, {
1658
+ value,
1659
+ writable: true,
1660
+ enumerable: false,
1661
+ configurable: true
1662
+ });
1663
+ };
1664
+
1665
+ // The return value is a mixin of `childProcess` and `Promise`
1666
+ const mergePromise$1 = (spawned, promise) => {
1667
+ mergePromiseProperty(spawned, promise, 'then');
1668
+ mergePromiseProperty(spawned, promise, 'catch');
1669
+
1670
+ // TODO: Remove the `if`-guard when targeting Node.js 10
1671
+ if (Promise.prototype.finally) {
1672
+ mergePromiseProperty(spawned, promise, 'finally');
1673
+ }
1674
+
1675
+ return spawned;
1676
+ };
1677
+
1678
+ // Use promises instead of `child_process` events
1679
+ const getSpawnedPromise$1 = spawned => {
1680
+ return new Promise((resolve, reject) => {
1681
+ spawned.on('exit', (code, signal) => {
1682
+ resolve({code, signal});
1683
+ });
1684
+
1685
+ spawned.on('error', error => {
1686
+ reject(error);
1687
+ });
1688
+
1689
+ if (spawned.stdin) {
1690
+ spawned.stdin.on('error', error => {
1691
+ reject(error);
1692
+ });
1693
+ }
1694
+ });
1695
+ };
1696
+
1697
+ var promise = {
1698
+ mergePromise: mergePromise$1,
1699
+ getSpawnedPromise: getSpawnedPromise$1
1700
+ };
1701
+
1702
+ const SPACES_REGEXP = / +/g;
1703
+
1704
+ const joinCommand$1 = (file, args = []) => {
1705
+ if (!Array.isArray(args)) {
1706
+ return file;
1707
+ }
1708
+
1709
+ return [file, ...args].join(' ');
1710
+ };
1711
+
1712
+ // Allow spaces to be escaped by a backslash if not meant as a delimiter
1713
+ const handleEscaping = (tokens, token, index) => {
1714
+ if (index === 0) {
1715
+ return [token];
1716
+ }
1717
+
1718
+ const previousToken = tokens[tokens.length - 1];
1719
+
1720
+ if (previousToken.endsWith('\\')) {
1721
+ return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`];
1722
+ }
1723
+
1724
+ return [...tokens, token];
1725
+ };
1726
+
1727
+ // Handle `execa.command()`
1728
+ const parseCommand$1 = command => {
1729
+ return command
1730
+ .trim()
1731
+ .split(SPACES_REGEXP)
1732
+ .reduce(handleEscaping, []);
1733
+ };
1734
+
1735
+ var command = {
1736
+ joinCommand: joinCommand$1,
1737
+ parseCommand: parseCommand$1
1738
+ };
1739
+
1740
+ const path$1 = require$$0;
1741
+ const childProcess$1 = require$$0$2;
1742
+ const crossSpawn = crossSpawnExports;
1743
+ const stripFinalNewline = stripFinalNewline$1;
1744
+ const npmRunPath = npmRunPathExports;
1745
+ const onetime = onetimeExports;
1746
+ const makeError = error;
1747
+ const normalizeStdio = stdioExports;
1748
+ const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler} = kill;
1749
+ const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = stream;
1750
+ const {mergePromise, getSpawnedPromise} = promise;
1751
+ const {joinCommand, parseCommand} = command;
1752
+
1753
+ const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
1754
+
1755
+ const getEnv = ({env: envOption, extendEnv, preferLocal, localDir}) => {
1756
+ const env = extendEnv ? {...process.env, ...envOption} : envOption;
1757
+
1758
+ if (preferLocal) {
1759
+ return npmRunPath.env({env, cwd: localDir});
1760
+ }
1761
+
1762
+ return env;
1763
+ };
1764
+
1765
+ const handleArgs = (file, args, options = {}) => {
1766
+ const parsed = crossSpawn._parse(file, args, options);
1767
+ file = parsed.command;
1768
+ args = parsed.args;
1769
+ options = parsed.options;
1770
+
1771
+ options = {
1772
+ maxBuffer: DEFAULT_MAX_BUFFER,
1773
+ buffer: true,
1774
+ stripFinalNewline: true,
1775
+ extendEnv: true,
1776
+ preferLocal: false,
1777
+ localDir: options.cwd || process.cwd(),
1778
+ encoding: 'utf8',
1779
+ reject: true,
1780
+ cleanup: true,
1781
+ ...options,
1782
+ windowsHide: true
1783
+ };
1784
+
1785
+ options.env = getEnv(options);
1786
+
1787
+ options.stdio = normalizeStdio(options);
1788
+
1789
+ if (process.platform === 'win32' && path$1.basename(file, '.exe') === 'cmd') {
1790
+ // #116
1791
+ args.unshift('/q');
1792
+ }
1793
+
1794
+ return {file, args, options, parsed};
1795
+ };
1796
+
1797
+ const handleOutput = (options, value, error) => {
1798
+ if (typeof value !== 'string' && !Buffer.isBuffer(value)) {
1799
+ // When `execa.sync()` errors, we normalize it to '' to mimic `execa()`
1800
+ return error === undefined ? undefined : '';
1801
+ }
1802
+
1803
+ if (options.stripFinalNewline) {
1804
+ return stripFinalNewline(value);
1805
+ }
1806
+
1807
+ return value;
1808
+ };
1809
+
1810
+ const execa$1 = (file, args, options) => {
1811
+ const parsed = handleArgs(file, args, options);
1812
+ const command = joinCommand(file, args);
1813
+
1814
+ let spawned;
1815
+ try {
1816
+ spawned = childProcess$1.spawn(parsed.file, parsed.args, parsed.options);
1817
+ } catch (error) {
1818
+ // Ensure the returned error is always both a promise and a child process
1819
+ const dummySpawned = new childProcess$1.ChildProcess();
1820
+ const errorPromise = Promise.reject(makeError({
1821
+ error,
1822
+ stdout: '',
1823
+ stderr: '',
1824
+ all: '',
1825
+ command,
1826
+ parsed,
1827
+ timedOut: false,
1828
+ isCanceled: false,
1829
+ killed: false
1830
+ }));
1831
+ return mergePromise(dummySpawned, errorPromise);
1832
+ }
1833
+
1834
+ const spawnedPromise = getSpawnedPromise(spawned);
1835
+ const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
1836
+ const processDone = setExitHandler(spawned, parsed.options, timedPromise);
1837
+
1838
+ const context = {isCanceled: false};
1839
+
1840
+ spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
1841
+ spawned.cancel = spawnedCancel.bind(null, spawned, context);
1842
+
1843
+ const handlePromise = async () => {
1844
+ const [{error, code, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
1845
+ const stdout = handleOutput(parsed.options, stdoutResult);
1846
+ const stderr = handleOutput(parsed.options, stderrResult);
1847
+ const all = handleOutput(parsed.options, allResult);
1848
+
1849
+ if (error || code !== 0 || signal !== null) {
1850
+ const returnedError = makeError({
1851
+ error,
1852
+ code,
1853
+ signal,
1854
+ stdout,
1855
+ stderr,
1856
+ all,
1857
+ command,
1858
+ parsed,
1859
+ timedOut,
1860
+ isCanceled: context.isCanceled,
1861
+ killed: spawned.killed
1862
+ });
1863
+
1864
+ if (!parsed.options.reject) {
1865
+ return returnedError;
1866
+ }
1867
+
1868
+ throw returnedError;
1869
+ }
1870
+
1871
+ return {
1872
+ command,
1873
+ exitCode: 0,
1874
+ exitCodeName: 'SUCCESS',
1875
+ stdout,
1876
+ stderr,
1877
+ all,
1878
+ failed: false,
1879
+ timedOut: false,
1880
+ isCanceled: false,
1881
+ killed: false
1882
+ };
1883
+ };
1884
+
1885
+ const handlePromiseOnce = onetime(handlePromise);
1886
+
1887
+ crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
1888
+
1889
+ handleInput(spawned, parsed.options.input);
1890
+
1891
+ spawned.all = makeAllStream(spawned);
1892
+
1893
+ return mergePromise(spawned, handlePromiseOnce);
1894
+ };
1895
+
1896
+ execa$2.exports = execa$1;
1897
+
1898
+ execa$2.exports.sync = (file, args, options) => {
1899
+ const parsed = handleArgs(file, args, options);
1900
+ const command = joinCommand(file, args);
1901
+
1902
+ validateInputSync(parsed.options);
1903
+
1904
+ let result;
1905
+ try {
1906
+ result = childProcess$1.spawnSync(parsed.file, parsed.args, parsed.options);
1907
+ } catch (error) {
1908
+ throw makeError({
1909
+ error,
1910
+ stdout: '',
1911
+ stderr: '',
1912
+ all: '',
1913
+ command,
1914
+ parsed,
1915
+ timedOut: false,
1916
+ isCanceled: false,
1917
+ killed: false
1918
+ });
1919
+ }
1920
+
1921
+ result.stdout = handleOutput(parsed.options, result.stdout, result.error);
1922
+ result.stderr = handleOutput(parsed.options, result.stderr, result.error);
1923
+
1924
+ if (result.error || result.status !== 0 || result.signal !== null) {
1925
+ const error = makeError({
1926
+ ...result,
1927
+ code: result.status,
1928
+ command,
1929
+ parsed,
1930
+ timedOut: result.error && result.error.code === 'ETIMEDOUT',
1931
+ isCanceled: false,
1932
+ killed: result.signal !== null
1933
+ });
1934
+
1935
+ if (!parsed.options.reject) {
1936
+ return error;
1937
+ }
1938
+
1939
+ throw error;
1940
+ }
1941
+
1942
+ return {
1943
+ command,
1944
+ exitCode: 0,
1945
+ exitCodeName: 'SUCCESS',
1946
+ stdout: result.stdout,
1947
+ stderr: result.stderr,
1948
+ failed: false,
1949
+ timedOut: false,
1950
+ isCanceled: false,
1951
+ killed: false
1952
+ };
1953
+ };
1954
+
1955
+ execa$2.exports.command = (command, options) => {
1956
+ const [file, ...args] = parseCommand(command);
1957
+ return execa$1(file, args, options);
1958
+ };
1959
+
1960
+ execa$2.exports.commandSync = (command, options) => {
1961
+ const [file, ...args] = parseCommand(command);
1962
+ return execa$1.sync(file, args, options);
1963
+ };
1964
+
1965
+ execa$2.exports.node = (scriptPath, args, options = {}) => {
1966
+ if (args && !Array.isArray(args) && typeof args === 'object') {
1967
+ options = args;
1968
+ args = [];
1969
+ }
1970
+
1971
+ const stdio = normalizeStdio.node(options);
1972
+
1973
+ const {nodePath = process.execPath, nodeOptions = process.execArgv} = options;
1974
+
1975
+ return execa$1(
1976
+ nodePath,
1977
+ [
1978
+ ...nodeOptions,
1979
+ scriptPath,
1980
+ ...(Array.isArray(args) ? args : [])
1981
+ ],
1982
+ {
1983
+ ...options,
1984
+ stdin: undefined,
1985
+ stdout: undefined,
1986
+ stderr: undefined,
1987
+ stdio,
1988
+ shell: false
1989
+ }
1990
+ );
1991
+ };
1992
+
1993
+ var execaExports = execa$2.exports;
1994
+
1995
+ const execa = execaExports;
1996
+
1997
+ const getColumnBoundaries = async header => {
1998
+ // Regex captures each individual column
1999
+ // ^\S+\s+ -> First column
2000
+ // \s*\S+\s*\S+$ -> Last column (combined)
2001
+ // \s*\S+ -> Regular columns
2002
+ const regex = /^\S+\s+|\s*\S+\s*\S+$|\s*\S+/g;
2003
+ const boundaries = [];
2004
+ let match;
2005
+
2006
+ while ((match = regex.exec(header))) {
2007
+ boundaries.push(match[0].length);
2008
+ }
2009
+
2010
+ // Extend last column boundary
2011
+ boundaries[boundaries.length - 1] = -1;
2012
+
2013
+ return boundaries;
2014
+ };
2015
+
2016
+ const parseOutput = async output => {
2017
+ const lines = output.trim().split('\n');
2018
+ const boundaries = await getColumnBoundaries(lines[0]);
2019
+
2020
+ return lines.slice(1).map(line => {
2021
+ const cl = boundaries.map(boundary => {
2022
+ // Handle extra-long last column
2023
+ const column = boundary > 0 ? line.slice(0, boundary) : line;
2024
+ line = line.slice(boundary);
2025
+ return column.trim();
2026
+ });
2027
+
2028
+ return {
2029
+ filesystem: cl[0],
2030
+ size: parseInt(cl[1], 10) * 1024,
2031
+ used: parseInt(cl[2], 10) * 1024,
2032
+ available: parseInt(cl[3], 10) * 1024,
2033
+ capacity: parseInt(cl[4], 10) / 100,
2034
+ mountpoint: cl[5]
2035
+ };
2036
+ });
2037
+ };
2038
+
2039
+ const run$1 = async args => {
2040
+ const {stdout} = await execa('df', args);
2041
+ return parseOutput(stdout);
2042
+ };
2043
+
2044
+ const df$4 = async () => run$1(['-kP']);
2045
+
2046
+ df$4.fs = async name => {
2047
+ if (typeof name !== 'string') {
2048
+ throw new TypeError('The `name` parameter required');
2049
+ }
2050
+
2051
+ const data = await run$1(['-kP']);
2052
+
2053
+ for (const item of data) {
2054
+ if (item.filesystem === name) {
2055
+ return item;
2056
+ }
2057
+ }
2058
+
2059
+ throw new Error(`The specified filesystem \`${name}\` doesn't exist`);
2060
+ };
2061
+
2062
+ df$4.file = async file => {
2063
+ if (typeof file !== 'string') {
2064
+ throw new TypeError('The `file` parameter is required');
2065
+ }
2066
+
2067
+ let data;
2068
+ try {
2069
+ data = await run$1(['-kP', file]);
2070
+ } catch (error) {
2071
+ if (/No such file or directory/.test(error.stderr)) {
2072
+ throw new Error(`The specified file \`${file}\` doesn't exist`);
2073
+ }
2074
+
2075
+ throw error;
2076
+ }
2077
+
2078
+ return data[0];
2079
+ };
2080
+
2081
+ df$5.exports = df$4;
2082
+ // TODO: remove this in the next major version
2083
+ df$5.exports.default = df$4;
2084
+
2085
+ if (process.env.NODE_ENV === 'test') {
2086
+ df$5.exports._parseOutput = parseOutput;
2087
+ }
2088
+
2089
+ var dfExports$1 = df$5.exports;
2090
+
2091
+ var df$3 = {exports: {}};
2092
+
2093
+ var childProcess = require$$0$2;
2094
+
2095
+ function run(args, cb) {
2096
+ childProcess.execFile('df', args, function (err, stdout) {
2097
+ if (err) {
2098
+ cb(err);
2099
+ return;
2100
+ }
2101
+
2102
+ cb(null, stdout.trim().split('\n').slice(1).map(function (el) {
2103
+ var cl = el.split(/\s+(?=[\d\/])/);
2104
+
2105
+ return {
2106
+ filesystem: cl[0],
2107
+ size: parseInt(cl[1], 10) * 1024,
2108
+ used: parseInt(cl[2], 10) * 1024,
2109
+ available: parseInt(cl[3], 10) * 1024,
2110
+ capacity: parseInt(cl[4], 10) / 100,
2111
+ mountpoint: cl[5]
2112
+ };
2113
+ }));
2114
+ });
2115
+ }
2116
+ var df$2 = df$3.exports = function (cb) {
2117
+ run(['-kP'], cb);
2118
+ };
2119
+
2120
+ df$2.fs = function (name, cb) {
2121
+ if (typeof name !== 'string') {
2122
+ throw new Error('name required');
2123
+ }
2124
+
2125
+ run(['-kP'], function (err, data) {
2126
+ if (err) {
2127
+ cb(err);
2128
+ return;
2129
+ }
2130
+
2131
+ var ret;
2132
+
2133
+ data.forEach(function (el) {
2134
+ if (el.filesystem === name) {
2135
+ ret = el;
2136
+ }
2137
+ });
2138
+
2139
+ cb(null, ret);
2140
+ });
2141
+ };
2142
+
2143
+ df$2.file = function (file, cb) {
2144
+ if (typeof file !== 'string') {
2145
+ throw new Error('file required');
2146
+ }
2147
+
2148
+ run(['-kP', file], function (err, data) {
2149
+ if (err) {
2150
+ cb(err);
2151
+ return;
2152
+ }
2153
+
2154
+ cb(null, data[0]);
2155
+ });
2156
+ };
2157
+
2158
+ var dfExports = df$3.exports;
2159
+
2160
+ var pify$2 = {exports: {}};
2161
+
2162
+ var processFn = function (fn, P, opts) {
2163
+ return function () {
2164
+ var that = this;
2165
+ var args = new Array(arguments.length);
2166
+
2167
+ for (var i = 0; i < arguments.length; i++) {
2168
+ args[i] = arguments[i];
2169
+ }
2170
+
2171
+ return new P(function (resolve, reject) {
2172
+ args.push(function (err, result) {
2173
+ if (err) {
2174
+ reject(err);
2175
+ } else if (opts.multiArgs) {
2176
+ var results = new Array(arguments.length - 1);
2177
+
2178
+ for (var i = 1; i < arguments.length; i++) {
2179
+ results[i - 1] = arguments[i];
2180
+ }
2181
+
2182
+ resolve(results);
2183
+ } else {
2184
+ resolve(result);
2185
+ }
2186
+ });
2187
+
2188
+ fn.apply(that, args);
2189
+ });
2190
+ };
2191
+ };
2192
+
2193
+ var pify$1 = pify$2.exports = function (obj, P, opts) {
2194
+ if (typeof P !== 'function') {
2195
+ opts = P;
2196
+ P = Promise;
2197
+ }
2198
+
2199
+ opts = opts || {};
2200
+ opts.exclude = opts.exclude || [/.+Sync$/];
2201
+
2202
+ var filter = function (key) {
2203
+ var match = function (pattern) {
2204
+ return typeof pattern === 'string' ? key === pattern : pattern.test(key);
2205
+ };
2206
+
2207
+ return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
2208
+ };
2209
+
2210
+ var ret = typeof obj === 'function' ? function () {
2211
+ if (opts.excludeMain) {
2212
+ return obj.apply(this, arguments);
2213
+ }
2214
+
2215
+ return processFn(obj, P, opts).apply(this, arguments);
2216
+ } : {};
2217
+
2218
+ return Object.keys(obj).reduce(function (ret, key) {
2219
+ var x = obj[key];
2220
+
2221
+ ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x;
2222
+
2223
+ return ret;
2224
+ }, ret);
2225
+ };
2226
+
2227
+ pify$1.all = pify$1;
2228
+
2229
+ var pifyExports = pify$2.exports;
2230
+
2231
+ var pinkie;
2232
+ var hasRequiredPinkie;
2233
+
2234
+ function requirePinkie () {
2235
+ if (hasRequiredPinkie) return pinkie;
2236
+ hasRequiredPinkie = 1;
2237
+
2238
+ var PENDING = 'pending';
2239
+ var SETTLED = 'settled';
2240
+ var FULFILLED = 'fulfilled';
2241
+ var REJECTED = 'rejected';
2242
+ var NOOP = function () {};
2243
+ var isNode = typeof index.commonjsGlobal !== 'undefined' && typeof index.commonjsGlobal.process !== 'undefined' && typeof index.commonjsGlobal.process.emit === 'function';
2244
+
2245
+ var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate;
2246
+ var asyncQueue = [];
2247
+ var asyncTimer;
2248
+
2249
+ function asyncFlush() {
2250
+ // run promise callbacks
2251
+ for (var i = 0; i < asyncQueue.length; i++) {
2252
+ asyncQueue[i][0](asyncQueue[i][1]);
2253
+ }
2254
+
2255
+ // reset async asyncQueue
2256
+ asyncQueue = [];
2257
+ asyncTimer = false;
2258
+ }
2259
+
2260
+ function asyncCall(callback, arg) {
2261
+ asyncQueue.push([callback, arg]);
2262
+
2263
+ if (!asyncTimer) {
2264
+ asyncTimer = true;
2265
+ asyncSetTimer(asyncFlush, 0);
2266
+ }
2267
+ }
2268
+
2269
+ function invokeResolver(resolver, promise) {
2270
+ function resolvePromise(value) {
2271
+ resolve(promise, value);
2272
+ }
2273
+
2274
+ function rejectPromise(reason) {
2275
+ reject(promise, reason);
2276
+ }
2277
+
2278
+ try {
2279
+ resolver(resolvePromise, rejectPromise);
2280
+ } catch (e) {
2281
+ rejectPromise(e);
2282
+ }
2283
+ }
2284
+
2285
+ function invokeCallback(subscriber) {
2286
+ var owner = subscriber.owner;
2287
+ var settled = owner._state;
2288
+ var value = owner._data;
2289
+ var callback = subscriber[settled];
2290
+ var promise = subscriber.then;
2291
+
2292
+ if (typeof callback === 'function') {
2293
+ settled = FULFILLED;
2294
+ try {
2295
+ value = callback(value);
2296
+ } catch (e) {
2297
+ reject(promise, e);
2298
+ }
2299
+ }
2300
+
2301
+ if (!handleThenable(promise, value)) {
2302
+ if (settled === FULFILLED) {
2303
+ resolve(promise, value);
2304
+ }
2305
+
2306
+ if (settled === REJECTED) {
2307
+ reject(promise, value);
2308
+ }
2309
+ }
2310
+ }
2311
+
2312
+ function handleThenable(promise, value) {
2313
+ var resolved;
2314
+
2315
+ try {
2316
+ if (promise === value) {
2317
+ throw new TypeError('A promises callback cannot return that same promise.');
2318
+ }
2319
+
2320
+ if (value && (typeof value === 'function' || typeof value === 'object')) {
2321
+ // then should be retrieved only once
2322
+ var then = value.then;
2323
+
2324
+ if (typeof then === 'function') {
2325
+ then.call(value, function (val) {
2326
+ if (!resolved) {
2327
+ resolved = true;
2328
+
2329
+ if (value === val) {
2330
+ fulfill(promise, val);
2331
+ } else {
2332
+ resolve(promise, val);
2333
+ }
2334
+ }
2335
+ }, function (reason) {
2336
+ if (!resolved) {
2337
+ resolved = true;
2338
+
2339
+ reject(promise, reason);
2340
+ }
2341
+ });
2342
+
2343
+ return true;
2344
+ }
2345
+ }
2346
+ } catch (e) {
2347
+ if (!resolved) {
2348
+ reject(promise, e);
2349
+ }
2350
+
2351
+ return true;
2352
+ }
2353
+
2354
+ return false;
2355
+ }
2356
+
2357
+ function resolve(promise, value) {
2358
+ if (promise === value || !handleThenable(promise, value)) {
2359
+ fulfill(promise, value);
2360
+ }
2361
+ }
2362
+
2363
+ function fulfill(promise, value) {
2364
+ if (promise._state === PENDING) {
2365
+ promise._state = SETTLED;
2366
+ promise._data = value;
2367
+
2368
+ asyncCall(publishFulfillment, promise);
2369
+ }
2370
+ }
2371
+
2372
+ function reject(promise, reason) {
2373
+ if (promise._state === PENDING) {
2374
+ promise._state = SETTLED;
2375
+ promise._data = reason;
2376
+
2377
+ asyncCall(publishRejection, promise);
2378
+ }
2379
+ }
2380
+
2381
+ function publish(promise) {
2382
+ promise._then = promise._then.forEach(invokeCallback);
2383
+ }
2384
+
2385
+ function publishFulfillment(promise) {
2386
+ promise._state = FULFILLED;
2387
+ publish(promise);
2388
+ }
2389
+
2390
+ function publishRejection(promise) {
2391
+ promise._state = REJECTED;
2392
+ publish(promise);
2393
+ if (!promise._handled && isNode) {
2394
+ index.commonjsGlobal.process.emit('unhandledRejection', promise._data, promise);
2395
+ }
2396
+ }
2397
+
2398
+ function notifyRejectionHandled(promise) {
2399
+ index.commonjsGlobal.process.emit('rejectionHandled', promise);
2400
+ }
2401
+
2402
+ /**
2403
+ * @class
2404
+ */
2405
+ function Promise(resolver) {
2406
+ if (typeof resolver !== 'function') {
2407
+ throw new TypeError('Promise resolver ' + resolver + ' is not a function');
2408
+ }
2409
+
2410
+ if (this instanceof Promise === false) {
2411
+ throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.');
2412
+ }
2413
+
2414
+ this._then = [];
2415
+
2416
+ invokeResolver(resolver, this);
2417
+ }
2418
+
2419
+ Promise.prototype = {
2420
+ constructor: Promise,
2421
+
2422
+ _state: PENDING,
2423
+ _then: null,
2424
+ _data: undefined,
2425
+ _handled: false,
2426
+
2427
+ then: function (onFulfillment, onRejection) {
2428
+ var subscriber = {
2429
+ owner: this,
2430
+ then: new this.constructor(NOOP),
2431
+ fulfilled: onFulfillment,
2432
+ rejected: onRejection
2433
+ };
2434
+
2435
+ if ((onRejection || onFulfillment) && !this._handled) {
2436
+ this._handled = true;
2437
+ if (this._state === REJECTED && isNode) {
2438
+ asyncCall(notifyRejectionHandled, this);
2439
+ }
2440
+ }
2441
+
2442
+ if (this._state === FULFILLED || this._state === REJECTED) {
2443
+ // already resolved, call callback async
2444
+ asyncCall(invokeCallback, subscriber);
2445
+ } else {
2446
+ // subscribe
2447
+ this._then.push(subscriber);
2448
+ }
2449
+
2450
+ return subscriber.then;
2451
+ },
2452
+
2453
+ catch: function (onRejection) {
2454
+ return this.then(null, onRejection);
2455
+ }
2456
+ };
2457
+
2458
+ Promise.all = function (promises) {
2459
+ if (!Array.isArray(promises)) {
2460
+ throw new TypeError('You must pass an array to Promise.all().');
2461
+ }
2462
+
2463
+ return new Promise(function (resolve, reject) {
2464
+ var results = [];
2465
+ var remaining = 0;
2466
+
2467
+ function resolver(index) {
2468
+ remaining++;
2469
+ return function (value) {
2470
+ results[index] = value;
2471
+ if (!--remaining) {
2472
+ resolve(results);
2473
+ }
2474
+ };
2475
+ }
2476
+
2477
+ for (var i = 0, promise; i < promises.length; i++) {
2478
+ promise = promises[i];
2479
+
2480
+ if (promise && typeof promise.then === 'function') {
2481
+ promise.then(resolver(i), reject);
2482
+ } else {
2483
+ results[i] = promise;
2484
+ }
2485
+ }
2486
+
2487
+ if (!remaining) {
2488
+ resolve(results);
2489
+ }
2490
+ });
2491
+ };
2492
+
2493
+ Promise.race = function (promises) {
2494
+ if (!Array.isArray(promises)) {
2495
+ throw new TypeError('You must pass an array to Promise.race().');
2496
+ }
2497
+
2498
+ return new Promise(function (resolve, reject) {
2499
+ for (var i = 0, promise; i < promises.length; i++) {
2500
+ promise = promises[i];
2501
+
2502
+ if (promise && typeof promise.then === 'function') {
2503
+ promise.then(resolve, reject);
2504
+ } else {
2505
+ resolve(promise);
2506
+ }
2507
+ }
2508
+ });
2509
+ };
2510
+
2511
+ Promise.resolve = function (value) {
2512
+ if (value && typeof value === 'object' && value.constructor === Promise) {
2513
+ return value;
2514
+ }
2515
+
2516
+ return new Promise(function (resolve) {
2517
+ resolve(value);
2518
+ });
2519
+ };
2520
+
2521
+ Promise.reject = function (reason) {
2522
+ return new Promise(function (resolve, reject) {
2523
+ reject(reason);
2524
+ });
2525
+ };
2526
+
2527
+ pinkie = Promise;
2528
+ return pinkie;
2529
+ }
2530
+
2531
+ var pinkiePromise = typeof Promise === 'function' ? Promise : requirePinkie();
2532
+
2533
+ var df$1 = dfExports;
2534
+ var pify = pifyExports;
2535
+ var Promise$1 = pinkiePromise;
2536
+
2537
+ var mountPoint$1 = function (file) {
2538
+ return pify(df$1.file, Promise$1)(file).then(function (data) {
2539
+ return data.mountpoint;
2540
+ });
2541
+ };
2542
+
2543
+ var os = require$$0$3;
2544
+
2545
+ function homedir() {
2546
+ var env = process.env;
2547
+ var home = env.HOME;
2548
+ var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME;
2549
+
2550
+ if (process.platform === 'win32') {
2551
+ return env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null;
2552
+ }
2553
+
2554
+ if (process.platform === 'darwin') {
2555
+ return home || (user ? '/Users/' + user : null);
2556
+ }
2557
+
2558
+ if (process.platform === 'linux') {
2559
+ return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null));
2560
+ }
2561
+
2562
+ return home || null;
2563
+ }
2564
+
2565
+ var osHomedir = typeof os.homedir === 'function' ? os.homedir : homedir;
2566
+
2567
+ var userHome$1 = osHomedir();
2568
+
2569
+ var xdgBasedir$1 = {};
2570
+
2571
+ (function (exports) {
2572
+ const os = require$$0$3;
2573
+ const path = require$$0;
2574
+
2575
+ const homeDirectory = os.homedir();
2576
+ const {env} = process;
2577
+
2578
+ exports.data = env.XDG_DATA_HOME ||
2579
+ (homeDirectory ? path.join(homeDirectory, '.local', 'share') : undefined);
2580
+
2581
+ exports.config = env.XDG_CONFIG_HOME ||
2582
+ (homeDirectory ? path.join(homeDirectory, '.config') : undefined);
2583
+
2584
+ exports.cache = env.XDG_CACHE_HOME || (homeDirectory ? path.join(homeDirectory, '.cache') : undefined);
2585
+
2586
+ exports.runtime = env.XDG_RUNTIME_DIR || undefined;
2587
+
2588
+ exports.dataDirs = (env.XDG_DATA_DIRS || '/usr/local/share/:/usr/share/').split(':');
2589
+
2590
+ if (exports.data) {
2591
+ exports.dataDirs.unshift(exports.data);
2592
+ }
2593
+
2594
+ exports.configDirs = (env.XDG_CONFIG_DIRS || '/etc/xdg').split(':');
2595
+
2596
+ if (exports.config) {
2597
+ exports.configDirs.unshift(exports.config);
2598
+ }
2599
+ } (xdgBasedir$1));
2600
+
2601
+ const fs = require$$0$1.promises;
2602
+ const path = require$$0;
2603
+ const df = dfExports$1;
2604
+ const mountPoint = mountPoint$1;
2605
+ const userHome = userHome$1;
2606
+ const xdgBasedir = xdgBasedir$1;
2607
+
2608
+ const check = async filePath => {
2609
+ const topuid = `${filePath}-${process.getuid()}`;
2610
+ const stickyBitMode = 17407;
2611
+
2612
+ try {
2613
+ const stats = await fs.lstat(filePath);
2614
+
2615
+ if (stats.isSymbolicLink() || stats.mode !== stickyBitMode) {
2616
+ return topuid;
2617
+ }
2618
+
2619
+ return path.join(filePath, String(process.getuid()));
2620
+ } catch (error) {
2621
+ if (error.code === 'ENOENT') {
2622
+ return topuid;
2623
+ }
2624
+
2625
+ return path.join(xdgBasedir.data, 'Trash');
2626
+ }
2627
+ };
2628
+
2629
+ xdgTrashdir$1.exports = async filePath => {
2630
+ if (process.platform !== 'linux') {
2631
+ return Promise.reject(new Error('Only Linux systems are supported'));
2632
+ }
2633
+
2634
+ if (!filePath) {
2635
+ return Promise.resolve(path.join(xdgBasedir.data, 'Trash'));
2636
+ }
2637
+
2638
+ const [homeMountPoint, fileMountPoint] = await Promise.all([
2639
+ mountPoint(userHome),
2640
+ // Ignore errors in case `file` is a dangling symlink
2641
+ mountPoint(filePath).catch(() => {})
2642
+ ]);
2643
+
2644
+ if (!fileMountPoint || fileMountPoint === homeMountPoint) {
2645
+ return path.join(xdgBasedir.data, 'Trash');
2646
+ }
2647
+
2648
+ return check(path.join(fileMountPoint, '.Trash'));
2649
+ };
2650
+
2651
+ xdgTrashdir$1.exports.all = async () => {
2652
+ if (process.platform !== 'linux') {
2653
+ return Promise.reject(new Error('Only Linux systems are supported'));
2654
+ }
2655
+
2656
+ return Promise.all((await df()).map(fileSystem => {
2657
+ if (fileSystem.mountpoint === '/') {
2658
+ return path.join(xdgBasedir.data, 'Trash');
2659
+ }
2660
+
2661
+ return check(path.join(fileSystem.mountpoint, '.Trash'));
2662
+ }));
2663
+ };
2664
+
2665
+ var xdgTrashdirExports = xdgTrashdir$1.exports;
2666
+ var xdgTrashdir = /*@__PURE__*/index.getDefaultExportFromCjs(xdgTrashdirExports);
2667
+
2668
+ function indentString(string, count = 1, options = {}) {
2669
+ const {
2670
+ indent = ' ',
2671
+ includeEmptyLines = false
2672
+ } = options;
2673
+
2674
+ if (typeof string !== 'string') {
2675
+ throw new TypeError(
2676
+ `Expected \`input\` to be a \`string\`, got \`${typeof string}\``
2677
+ );
2678
+ }
2679
+
2680
+ if (typeof count !== 'number') {
2681
+ throw new TypeError(
2682
+ `Expected \`count\` to be a \`number\`, got \`${typeof count}\``
2683
+ );
2684
+ }
2685
+
2686
+ if (count < 0) {
2687
+ throw new RangeError(
2688
+ `Expected \`count\` to be at least 0, got \`${count}\``
2689
+ );
2690
+ }
2691
+
2692
+ if (typeof indent !== 'string') {
2693
+ throw new TypeError(
2694
+ `Expected \`options.indent\` to be a \`string\`, got \`${typeof indent}\``
2695
+ );
2696
+ }
2697
+
2698
+ if (count === 0) {
2699
+ return string;
2700
+ }
2701
+
2702
+ const regex = includeEmptyLines ? /^/gm : /^(?!\s*$)/gm;
2703
+
2704
+ return string.replace(regex, indent.repeat(count));
2705
+ }
2706
+
2707
+ function escapeStringRegexp(string) {
2708
+ if (typeof string !== 'string') {
2709
+ throw new TypeError('Expected a string');
2710
+ }
2711
+
2712
+ // Escape characters with special meaning either inside or outside character sets.
2713
+ // Use a simple backslash escape when it’s always valid, and a `\xnn` escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
2714
+ return string
2715
+ .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
2716
+ .replace(/-/g, '\\x2d');
2717
+ }
2718
+
2719
+ const extractPathRegex = /\s+at.*[(\s](.*)\)?/;
2720
+ const pathRegex = /^(?:(?:(?:node|node:[\w/]+|(?:(?:node:)?internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)(?:\.js)?:\d+:\d+)|native)/;
2721
+ const homeDir = typeof require$$0$3.homedir === 'undefined' ? '' : require$$0$3.homedir().replace(/\\/g, '/');
2722
+
2723
+ function cleanStack(stack, {pretty = false, basePath} = {}) {
2724
+ const basePathRegex = basePath && new RegExp(`(at | \\()${escapeStringRegexp(basePath.replace(/\\/g, '/'))}`, 'g');
2725
+
2726
+ if (typeof stack !== 'string') {
2727
+ return undefined;
2728
+ }
2729
+
2730
+ return stack.replace(/\\/g, '/')
2731
+ .split('\n')
2732
+ .filter(line => {
2733
+ const pathMatches = line.match(extractPathRegex);
2734
+ if (pathMatches === null || !pathMatches[1]) {
2735
+ return true;
2736
+ }
2737
+
2738
+ const match = pathMatches[1];
2739
+
2740
+ // Electron
2741
+ if (
2742
+ match.includes('.app/Contents/Resources/electron.asar') ||
2743
+ match.includes('.app/Contents/Resources/default_app.asar') ||
2744
+ match.includes('node_modules/electron/dist/resources/electron.asar') ||
2745
+ match.includes('node_modules/electron/dist/resources/default_app.asar')
2746
+ ) {
2747
+ return false;
2748
+ }
2749
+
2750
+ return !pathRegex.test(match);
2751
+ })
2752
+ .filter(line => line.trim() !== '')
2753
+ .map(line => {
2754
+ if (basePathRegex) {
2755
+ line = line.replace(basePathRegex, '$1');
2756
+ }
2757
+
2758
+ if (pretty) {
2759
+ line = line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~')));
2760
+ }
2761
+
2762
+ return line;
2763
+ })
2764
+ .join('\n');
2765
+ }
2766
+
2767
+ const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, '');
2768
+
2769
+ class AggregateError extends Error {
2770
+ #errors;
2771
+
2772
+ name = 'AggregateError';
2773
+
2774
+ constructor(errors) {
2775
+ if (!Array.isArray(errors)) {
2776
+ throw new TypeError(`Expected input to be an Array, got ${typeof errors}`);
2777
+ }
2778
+
2779
+ errors = errors.map(error => {
2780
+ if (error instanceof Error) {
2781
+ return error;
2782
+ }
2783
+
2784
+ if (error !== null && typeof error === 'object') {
2785
+ // Handle plain error objects with message property and/or possibly other metadata
2786
+ return Object.assign(new Error(error.message), error);
2787
+ }
2788
+
2789
+ return new Error(error);
2790
+ });
2791
+
2792
+ let message = errors
2793
+ .map(error => {
2794
+ // The `stack` property is not standardized, so we can't assume it exists
2795
+ return typeof error.stack === 'string' && error.stack.length > 0 ? cleanInternalStack(cleanStack(error.stack)) : String(error);
2796
+ })
2797
+ .join('\n');
2798
+ message = '\n' + indentString(message, 4);
2799
+ super(message);
2800
+
2801
+ this.#errors = errors;
2802
+ }
2803
+
2804
+ get errors() {
2805
+ return this.#errors.slice();
2806
+ }
2807
+ }
2808
+
2809
+ /**
2810
+ An error to be thrown when the request is aborted by AbortController.
2811
+ DOMException is thrown instead of this Error when DOMException is available.
2812
+ */
2813
+ class AbortError extends Error {
2814
+ constructor(message) {
2815
+ super();
2816
+ this.name = 'AbortError';
2817
+ this.message = message;
2818
+ }
2819
+ }
2820
+
2821
+ /**
2822
+ TODO: Remove AbortError and just throw DOMException when targeting Node 18.
2823
+ */
2824
+ const getDOMException = errorMessage => globalThis.DOMException === undefined
2825
+ ? new AbortError(errorMessage)
2826
+ : new DOMException(errorMessage);
2827
+
2828
+ /**
2829
+ TODO: Remove below function and just 'reject(signal.reason)' when targeting Node 18.
2830
+ */
2831
+ const getAbortedReason = signal => {
2832
+ const reason = signal.reason === undefined
2833
+ ? getDOMException('This operation was aborted.')
2834
+ : signal.reason;
2835
+
2836
+ return reason instanceof Error ? reason : getDOMException(reason);
2837
+ };
2838
+
2839
+ async function pMap(
2840
+ iterable,
2841
+ mapper,
2842
+ {
2843
+ concurrency = Number.POSITIVE_INFINITY,
2844
+ stopOnError = true,
2845
+ signal,
2846
+ } = {},
2847
+ ) {
2848
+ return new Promise((resolve, reject_) => {
2849
+ if (iterable[Symbol.iterator] === undefined && iterable[Symbol.asyncIterator] === undefined) {
2850
+ throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
2851
+ }
2852
+
2853
+ if (typeof mapper !== 'function') {
2854
+ throw new TypeError('Mapper function is required');
2855
+ }
2856
+
2857
+ if (!((Number.isSafeInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency >= 1)) {
2858
+ throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
2859
+ }
2860
+
2861
+ const result = [];
2862
+ const errors = [];
2863
+ const skippedIndexesMap = new Map();
2864
+ let isRejected = false;
2865
+ let isResolved = false;
2866
+ let isIterableDone = false;
2867
+ let resolvingCount = 0;
2868
+ let currentIndex = 0;
2869
+ const iterator = iterable[Symbol.iterator] === undefined ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
2870
+
2871
+ const reject = reason => {
2872
+ isRejected = true;
2873
+ isResolved = true;
2874
+ reject_(reason);
2875
+ };
2876
+
2877
+ if (signal) {
2878
+ if (signal.aborted) {
2879
+ reject(getAbortedReason(signal));
2880
+ }
2881
+
2882
+ signal.addEventListener('abort', () => {
2883
+ reject(getAbortedReason(signal));
2884
+ });
2885
+ }
2886
+
2887
+ const next = async () => {
2888
+ if (isResolved) {
2889
+ return;
2890
+ }
2891
+
2892
+ const nextItem = await iterator.next();
2893
+
2894
+ const index = currentIndex;
2895
+ currentIndex++;
2896
+
2897
+ // Note: `iterator.next()` can be called many times in parallel.
2898
+ // This can cause multiple calls to this `next()` function to
2899
+ // receive a `nextItem` with `done === true`.
2900
+ // The shutdown logic that rejects/resolves must be protected
2901
+ // so it runs only one time as the `skippedIndex` logic is
2902
+ // non-idempotent.
2903
+ if (nextItem.done) {
2904
+ isIterableDone = true;
2905
+
2906
+ if (resolvingCount === 0 && !isResolved) {
2907
+ if (!stopOnError && errors.length > 0) {
2908
+ reject(new AggregateError(errors));
2909
+ return;
2910
+ }
2911
+
2912
+ isResolved = true;
2913
+
2914
+ if (skippedIndexesMap.size === 0) {
2915
+ resolve(result);
2916
+ return;
2917
+ }
2918
+
2919
+ const pureResult = [];
2920
+
2921
+ // Support multiple `pMapSkip`'s.
2922
+ for (const [index, value] of result.entries()) {
2923
+ if (skippedIndexesMap.get(index) === pMapSkip) {
2924
+ continue;
2925
+ }
2926
+
2927
+ pureResult.push(value);
2928
+ }
2929
+
2930
+ resolve(pureResult);
2931
+ }
2932
+
2933
+ return;
2934
+ }
2935
+
2936
+ resolvingCount++;
2937
+
2938
+ // Intentionally detached
2939
+ (async () => {
2940
+ try {
2941
+ const element = await nextItem.value;
2942
+
2943
+ if (isResolved) {
2944
+ return;
2945
+ }
2946
+
2947
+ const value = await mapper(element, index);
2948
+
2949
+ // Use Map to stage the index of the element.
2950
+ if (value === pMapSkip) {
2951
+ skippedIndexesMap.set(index, value);
2952
+ }
2953
+
2954
+ result[index] = value;
2955
+
2956
+ resolvingCount--;
2957
+ await next();
2958
+ } catch (error) {
2959
+ if (stopOnError) {
2960
+ reject(error);
2961
+ } else {
2962
+ errors.push(error);
2963
+ resolvingCount--;
2964
+
2965
+ // In that case we can't really continue regardless of `stopOnError` state
2966
+ // since an iterable is likely to continue throwing after it throws once.
2967
+ // If we continue calling `next()` indefinitely we will likely end up
2968
+ // in an infinite loop of failed iteration.
2969
+ try {
2970
+ await next();
2971
+ } catch (error) {
2972
+ reject(error);
2973
+ }
2974
+ }
2975
+ }
2976
+ })();
2977
+ };
2978
+
2979
+ // Create the concurrent runners in a detached (non-awaited)
2980
+ // promise. We need this so we can await the `next()` calls
2981
+ // to stop creating runners before hitting the concurrency limit
2982
+ // if the iterable has already been marked as done.
2983
+ // NOTE: We *must* do this for async iterators otherwise we'll spin up
2984
+ // infinite `next()` calls by default and never start the event loop.
2985
+ (async () => {
2986
+ for (let index = 0; index < concurrency; index++) {
2987
+ try {
2988
+ // eslint-disable-next-line no-await-in-loop
2989
+ await next();
2990
+ } catch (error) {
2991
+ reject(error);
2992
+ break;
2993
+ }
2994
+
2995
+ if (isIterableDone || isRejected) {
2996
+ break;
2997
+ }
2998
+ }
2999
+ })();
3000
+ });
3001
+ }
3002
+
3003
+ const pMapSkip = Symbol('skip');
3004
+
3005
+ async function pathExists(path) {
3006
+ try {
3007
+ await fs$3.promises.access(path);
3008
+ return true;
3009
+ } catch {
3010
+ return false;
3011
+ }
3012
+ }
3013
+
3014
+ const resolvePath = (cwd, sourcePath, destinationPath) => {
3015
+ sourcePath = path$5.resolve(cwd, sourcePath);
3016
+ destinationPath = path$5.resolve(cwd, destinationPath);
3017
+
3018
+ return {
3019
+ sourcePath,
3020
+ destinationPath,
3021
+ };
3022
+ };
3023
+
3024
+ const validatePathsExist = (sourcePath, destinationPath, suffix = 'Path') => {
3025
+ if (!sourcePath || !destinationPath) {
3026
+ throw new TypeError(`\`source${suffix}\` and \`destination${suffix}\` required`);
3027
+ }
3028
+ };
3029
+
3030
+ const validateSameDirectory = (source, destination) => {
3031
+ if (path$5.dirname(source) !== path$5.dirname(destination)) {
3032
+ throw new Error('`source` and `destination` must be in the same directory');
3033
+ }
3034
+ };
3035
+
3036
+ const _moveFile = async (sourcePath, destinationPath, {overwrite = true, cwd = process$2.cwd(), directoryMode, validateDirectory = false} = {}) => {
3037
+ if (cwd) {
3038
+ ({sourcePath, destinationPath} = resolvePath(cwd, sourcePath, destinationPath));
3039
+ }
3040
+
3041
+ if (validateDirectory) {
3042
+ validateSameDirectory(sourcePath, destinationPath);
3043
+ }
3044
+
3045
+ if (!overwrite && await pathExists(destinationPath)) {
3046
+ throw new Error(`The destination file exists: ${destinationPath}`);
3047
+ }
3048
+
3049
+ await fs$3.promises.mkdir(path$5.dirname(destinationPath), {
3050
+ recursive: true,
3051
+ mode: directoryMode,
3052
+ });
3053
+
3054
+ try {
3055
+ await fs$3.promises.rename(sourcePath, destinationPath);
3056
+ } catch (error) {
3057
+ if (error.code === 'EXDEV') {
3058
+ await fs$3.promises.copyFile(sourcePath, destinationPath);
3059
+ await fs$3.promises.unlink(sourcePath);
3060
+ } else {
3061
+ throw error;
3062
+ }
3063
+ }
3064
+ };
3065
+
3066
+ async function moveFile(sourcePath, destinationPath, options) {
3067
+ validatePathsExist(sourcePath, destinationPath);
3068
+ return _moveFile(sourcePath, destinationPath, options);
3069
+ }
3070
+
3071
+ let ProcfsError$1 = class ProcfsError extends Error {
3072
+ constructor(code, message, sourceError) {
3073
+ super(message);
3074
+ this.name = 'ProcfsError';
3075
+ this.code = code;
3076
+ if (sourceError !== undefined) {
3077
+ this.sourceError = sourceError;
3078
+ }
3079
+ }
3080
+ };
3081
+
3082
+ ProcfsError$1.ERR_PARSING_FAILED = 'EPARSE';
3083
+ ProcfsError$1.ERR_UNKNOWN = 'EUNKNOWN';
3084
+ ProcfsError$1.ERR_NOT_FOUND = 'ENOENT';
3085
+
3086
+ ProcfsError$1.parsingError = (src, msg) => {
3087
+ let e = new ProcfsError$1(ProcfsError$1.ERR_PARSING_FAILED, `Parsing failed: ${msg}`);
3088
+ e.sourceText = src;
3089
+ return e;
3090
+ };
3091
+
3092
+ ProcfsError$1.generic = err => {
3093
+ /* istanbul ignore next should not ever happen */
3094
+ if (err instanceof ProcfsError$1) {
3095
+ return err;
3096
+ }
3097
+
3098
+ switch (err.code) {
3099
+ case 'ENOENT':
3100
+ return new ProcfsError$1(ProcfsError$1.ERR_NOT_FOUND, 'File not found', err);
3101
+ /* istanbul ignore next should not ever happen*/
3102
+ default:
3103
+ return new ProcfsError$1(ProcfsError$1.ERR_UNKNOWN, `Unknown error: ${err.message}`, err);
3104
+ }
3105
+ };
3106
+
3107
+ var procfsError = ProcfsError$1;
3108
+
3109
+ const trim = str => str.trim();
3110
+
3111
+ class Parsers {}
3112
+
3113
+ const parsers$1 = new Parsers();
3114
+
3115
+ for (let name of [
3116
+ 'cgroups',
3117
+ 'config',
3118
+ 'cpuinfo',
3119
+ 'devices',
3120
+ 'diskstats',
3121
+ 'filesystems',
3122
+ 'loadavg',
3123
+ 'meminfo',
3124
+ 'partitions',
3125
+ 'processAutogroup',
3126
+ 'processCgroups',
3127
+ 'processCmdline',
3128
+ 'processEnviron',
3129
+ 'processes',
3130
+ 'processExe',
3131
+ 'processFd',
3132
+ 'processFdinfo',
3133
+ 'processFds',
3134
+ 'processGidMap',
3135
+ 'processIo',
3136
+ 'processLimits',
3137
+ 'processMountinfo',
3138
+ 'processNetDev',
3139
+ 'processNetTcp4',
3140
+ 'processNetTcp6',
3141
+ 'processNetUdp4',
3142
+ 'processNetUdp6',
3143
+ 'processNetUnix',
3144
+ 'processNetWireless',
3145
+ 'processStat',
3146
+ 'processStatm',
3147
+ 'processStatus',
3148
+ 'processThreads',
3149
+ 'processUidMap',
3150
+ 'stat',
3151
+ 'swaps',
3152
+ 'uptime',
3153
+ ]) {
3154
+ Object.defineProperty(Parsers.prototype, name, {
3155
+ get: function () { // eslint-disable-line object-shorthand
3156
+ let value = index.commonjsRequire(`./parsers/${name}`);
3157
+ Object.defineProperty(this, name, {value});
3158
+ return value;
3159
+ },
3160
+ });
3161
+ }
3162
+
3163
+ parsers$1.cmdline = trim;
3164
+ parsers$1.processComm = trim;
3165
+ parsers$1.processCpuset = trim;
3166
+ parsers$1.processOomScore = src => parseInt(src);
3167
+ parsers$1.processTimerslackNs = src => parseInt(src);
3168
+ parsers$1.version = trim;
3169
+ parsers$1.processCwd = src => src;
3170
+ parsers$1.processPersonality = src => parseInt(src, 16);
3171
+
3172
+ var parsers_1 = parsers$1;
3173
+
3174
+ const {
3175
+ readlinkSync,
3176
+ readdirSync,
3177
+ openSync,
3178
+ readSync,
3179
+ closeSync,
3180
+ readFileSync,
3181
+ existsSync,
3182
+ } = require$$0$1;
3183
+
3184
+ const tmpBufMinLen = 4096 * 2;
3185
+ const tmpBufMaxLen = 4096 * 8;
3186
+
3187
+ let tmpBuf = Buffer.allocUnsafeSlow(tmpBufMinLen);
3188
+
3189
+ const read$1 = path => {
3190
+ const fd = openSync(path, 'r', 0o666);
3191
+ let pos = 0;
3192
+ let bytesRead;
3193
+ let buf = tmpBuf;
3194
+ let length = buf.length;
3195
+ do {
3196
+ bytesRead = readSync(fd, buf, pos, buf.length - pos, null);
3197
+ pos += bytesRead;
3198
+ if (pos === tmpBuf.length) {
3199
+ length = length << 1;
3200
+ let newBuf = Buffer.allocUnsafeSlow(length);
3201
+
3202
+ if (length <= tmpBufMaxLen) {
3203
+ tmpBuf = newBuf;
3204
+ }
3205
+
3206
+ buf.copy(newBuf);
3207
+ buf = newBuf;
3208
+ }
3209
+ } while (bytesRead !== 0);
3210
+ closeSync(fd);
3211
+ return buf.toString('utf8', 0, pos);
3212
+ };
3213
+
3214
+ const readIdList = path => {
3215
+ let ls = readdirSync(path);
3216
+ for (let i = 0; i < ls.length; i++) {
3217
+ ls[i] = parseInt(ls[i]);
3218
+ }
3219
+ return ls;
3220
+ };
3221
+
3222
+ const readBuffer$1 = readFileSync;
3223
+ const exists = existsSync;
3224
+ const readdir$1 = readdirSync;
3225
+
3226
+ const devIdGetMinor$1 = devId => (((devId >> 20) << 8) | (devId & 0xFF));
3227
+ const devIdGetMajor$1 = devId => ((devId >> 8) & 0xFF);
3228
+ const devIdFromMajorMinor$1 = (major, minor) => (((minor >> 8) << 20) | ((major & 0xFF) << 8) | (minor & 0xFF));
3229
+
3230
+ var utils = {
3231
+ read: read$1,
3232
+ readLink: readlinkSync,
3233
+ readIdList,
3234
+ readBuffer: readBuffer$1,
3235
+ exists,
3236
+ readdir: readdir$1,
3237
+
3238
+ devIdGetMinor: devIdGetMinor$1,
3239
+ devIdGetMajor: devIdGetMajor$1,
3240
+ devIdFromMajorMinor: devIdFromMajorMinor$1,
3241
+ };
3242
+
3243
+ const ProcfsError = procfsError;
3244
+ const parsers = parsers_1;
3245
+ const {
3246
+ read,
3247
+ readLink,
3248
+ readBuffer,
3249
+ readdir,
3250
+ devIdGetMinor,
3251
+ devIdGetMajor,
3252
+ devIdFromMajorMinor,
3253
+ } = utils;
3254
+
3255
+ class Procfs {
3256
+ constructor(root) {
3257
+ if (root === undefined) {
3258
+ root = '/proc';
3259
+ }
3260
+ this.root = root;
3261
+ this.rootSlash = `${root}/`;
3262
+ }
3263
+
3264
+ processes() {
3265
+ try {
3266
+ return parsers.processes(readdir(this.root));
3267
+ } catch (error) {
3268
+ /* istanbul ignore next should not ever happen when procfs exists */
3269
+ throw ProcfsError.generic(error);
3270
+ }
3271
+ }
3272
+
3273
+ processFds(pid) {
3274
+ if (pid !== undefined && (!Number.isInteger(pid) || pid <= 0)) {
3275
+ throw new TypeError('pid');
3276
+ }
3277
+ try {
3278
+ return parsers.processFds(readdir(`${this.rootSlash}${pid === undefined ? 'self' : pid}/fd`));
3279
+ } catch (error) {
3280
+ throw ProcfsError.generic(error);
3281
+ }
3282
+ }
3283
+
3284
+ processThreads(pid) {
3285
+ if (pid !== undefined && (!Number.isInteger(pid) || pid <= 0)) {
3286
+ throw new TypeError('pid');
3287
+ }
3288
+ try {
3289
+ return parsers.processThreads(readdir(`${this.rootSlash}${pid === undefined ? 'self' : pid}/task`));
3290
+ } catch (error) {
3291
+ throw ProcfsError.generic(error);
3292
+ }
3293
+ }
3294
+
3295
+ processFdinfo(fd, pid) {
3296
+ if (pid !== undefined && !(Number.isInteger(pid) && pid >= 0)) {
3297
+ throw new TypeError('pid');
3298
+ }
3299
+ if (!Number.isInteger(fd) || fd <= 0) {
3300
+ throw new TypeError('fd');
3301
+ }
3302
+ try {
3303
+ return parsers.processFdinfo(read(`${this.rootSlash}${pid === undefined ? 'self' : pid}/fdinfo/${fd}`));
3304
+ } catch (error) {
3305
+ throw ProcfsError.generic(error);
3306
+ }
3307
+ }
3308
+
3309
+ processFd(fd, pid) {
3310
+ if (pid !== undefined && !(Number.isInteger(pid) && pid >= 0)) {
3311
+ throw new TypeError('pid');
3312
+ }
3313
+ if (!Number.isInteger(fd) || fd <= 0) {
3314
+ throw new TypeError('fd');
3315
+ }
3316
+ try {
3317
+ return parsers.processFd(readLink(`${this.rootSlash}${pid === undefined ? 'self' : pid}/fd/${fd}`));
3318
+ } catch (error) {
3319
+ throw ProcfsError.generic(error);
3320
+ }
3321
+ }
3322
+
3323
+ config() {
3324
+ try {
3325
+ return parsers.config(readBuffer(`${this.rootSlash}config.gz`));
3326
+ } catch (error) {
3327
+ /* istanbul ignore next should not ever happen when procfs exists and kernel properly configured */
3328
+ throw ProcfsError.generic(error);
3329
+ }
3330
+ }
3331
+ }
3332
+
3333
+ Procfs.prototype.devIdGetMinor = devIdGetMinor;
3334
+ Procfs.prototype.devIdGetMajor = devIdGetMajor;
3335
+ Procfs.prototype.devIdFromMajorMinor = devIdFromMajorMinor;
3336
+
3337
+ for (let [name, path] of [
3338
+ ['processExe', '/exe'],
3339
+ ['processCwd', '/cwd'],
3340
+ ]) {
3341
+ Procfs.prototype[name] = function (pid) {
3342
+ if (pid !== undefined && !(Number.isInteger(pid) && pid >= 0)) {
3343
+ throw new TypeError('pid');
3344
+ }
3345
+ try {
3346
+ return parsers[name](readLink(`${this.rootSlash}${pid === undefined ? 'self' : pid}${path}`));
3347
+ } catch (error) {
3348
+ throw ProcfsError.generic(error);
3349
+ }
3350
+ };
3351
+ }
3352
+
3353
+ for (let [name, path] of [
3354
+ ['processMountinfo', '/mountinfo'],
3355
+ ['processIo', '/io'],
3356
+ ['processUidMap', '/uid_map'],
3357
+ ['processGidMap', '/gid_map'],
3358
+ ['processEnviron', '/environ'],
3359
+ ['processOomScore', '/oom_score'],
3360
+ ['processTimerslackNs', '/timerslack_ns'],
3361
+ ['processCmdline', '/cmdline'],
3362
+ ['processAutogroup', '/autogroup'],
3363
+ ['processStatm', '/statm'],
3364
+ ['processComm', '/comm'],
3365
+ ['processPersonality', '/personality'],
3366
+ ['processCgroups', '/cgroup'],
3367
+ ['processCpuset', '/cpuset'],
3368
+ ['processLimits', '/limits'],
3369
+ ['processStat', '/stat'],
3370
+ ['processStatus', '/status'],
3371
+ ['processNetDev', '/net/dev'],
3372
+ ['processNetWireless', '/net/wireless'],
3373
+ ['processNetUnix', '/net/unix'],
3374
+ ['processNetTcp4', '/net/tcp'],
3375
+ ['processNetTcp6', '/net/tcp6'],
3376
+ ['processNetUdp4', '/net/udp'],
3377
+ ['processNetUdp6', '/net/udp6'],
3378
+ ]) {
3379
+ Procfs.prototype[name] = function (pid) {
3380
+ if (pid !== undefined && !(Number.isInteger(pid) && pid >= 0)) {
3381
+ throw new TypeError('pid');
3382
+ }
3383
+ try {
3384
+ return parsers[name](read(`${this.rootSlash}${pid === undefined ? 'self' : pid}${path}`));
3385
+ } catch (error) {
3386
+ throw ProcfsError.generic(error);
3387
+ }
3388
+ };
3389
+ }
3390
+
3391
+ for (let name of [
3392
+ 'cpuinfo',
3393
+ 'loadavg',
3394
+ 'uptime',
3395
+ 'version',
3396
+ 'cmdline',
3397
+ 'swaps',
3398
+ 'stat',
3399
+ 'devices',
3400
+ 'filesystems',
3401
+ 'diskstats',
3402
+ 'partitions',
3403
+ 'meminfo',
3404
+ 'cgroups',
3405
+ ]) {
3406
+ Procfs.prototype[name] = function () {
3407
+ try {
3408
+ return parsers[name](read(this.rootSlash + name));
3409
+ } catch (error) {
3410
+ /* istanbul ignore next should not ever happen when procfs exists */
3411
+ throw ProcfsError.generic(error);
3412
+ }
3413
+ };
3414
+ }
3415
+
3416
+ for (let [name, parser, path] of [
3417
+ ['netDev', 'processNetDev', 'net/dev'],
3418
+ ['netWireless', 'processNetWireless', 'net/wireless'],
3419
+ ['netUnix', 'processNetUnix', 'net/unix'],
3420
+ ['netTcp4', 'processNetTcp4', 'net/tcp'],
3421
+ ['netTcp6', 'processNetTcp6', 'net/tcp6'],
3422
+ ['netUdp4', 'processNetUdp4', 'net/udp'],
3423
+ ['netUdp6', 'processNetUdp6', 'net/udp6'],
3424
+ ]) {
3425
+ Procfs.prototype[name] = function () {
3426
+ try {
3427
+ return parsers[parser](read(this.rootSlash + path));
3428
+ } catch (error) {
3429
+ /* istanbul ignore next should not ever happen when procfs exists */
3430
+ throw ProcfsError.generic(error);
3431
+ }
3432
+ };
3433
+ }
3434
+
3435
+ const procfs = new Procfs();
3436
+ var procfs_1 = {
3437
+ procfs,
3438
+ Procfs,
3439
+ ProcfsError,
3440
+ };
3441
+
3442
+ // Educated guess, values of 16 to 64 seem to be optimal for modern SSD, 8-16 and 64-128 can be a bit slower.
3443
+ // We should be ok as long as ssdCount <= cpuCount <= ssdCount*16.
3444
+ // For slower media this is not as important and we rely on OS handling it for us.
3445
+ const concurrency = os$3.cpus().length * 8;
3446
+
3447
+ const pad = number => number < 10 ? '0' + number : number;
3448
+
3449
+ const getDeletionDate = date => date.getFullYear()
3450
+ + '-' + pad(date.getMonth() + 1)
3451
+ + '-' + pad(date.getDate())
3452
+ + 'T' + pad(date.getHours())
3453
+ + ':' + pad(date.getMinutes())
3454
+ + ':' + pad(date.getSeconds());
3455
+
3456
+ const trash = async (filePath, trashPaths) => {
3457
+ const name = v4.v4();
3458
+ const destination = path$5.join(trashPaths.filesPath, name);
3459
+ const trashInfoPath = path$5.join(trashPaths.infoPath, `${name}.trashinfo`);
3460
+
3461
+ const trashInfoData = `[Trash Info]\nPath=${filePath.replace(/\s/g, '%20')}\nDeletionDate=${getDeletionDate(new Date())}`;
3462
+
3463
+ await fs$3.promises.writeFile(trashInfoPath, trashInfoData);
3464
+ await moveFile(filePath, destination);
3465
+
3466
+ return {
3467
+ path: destination,
3468
+ info: trashInfoPath,
3469
+ };
3470
+ };
3471
+
3472
+ async function linux(paths) {
3473
+ const mountPointMap = new Map();
3474
+
3475
+ for (const mountInfo of Object.values(procfs_1.procfs.processMountinfo())) {
3476
+ // Filter out irrelevant drives (that start with `/snap`, `/run`, etc).
3477
+ if (/^\/(snap|var\/snap|run|sys|proc|dev)($|\/)/.test(mountInfo.mountPoint)) {
3478
+ continue;
3479
+ }
3480
+
3481
+ // Keep the first one if there are multiple `devId`.
3482
+ if (!mountPointMap.has(mountInfo.devId)) {
3483
+ mountPointMap.set(mountInfo.devId, mountInfo.mountPoint);
3484
+ }
3485
+ }
3486
+
3487
+ const trashPathsCache = new Map();
3488
+
3489
+ const getDeviceTrashPaths = async devId => {
3490
+ let trashPathsPromise = trashPathsCache.get(devId);
3491
+ if (trashPathsPromise === undefined) {
3492
+ trashPathsPromise = (async () => {
3493
+ const trashPath = await xdgTrashdir(mountPointMap.get(devId));
3494
+ const paths = {
3495
+ filesPath: path$5.join(trashPath, 'files'),
3496
+ infoPath: path$5.join(trashPath, 'info'),
3497
+ };
3498
+ await fs$3.promises.mkdir(paths.filesPath, {mode: 0o700, recursive: true});
3499
+ await fs$3.promises.mkdir(paths.infoPath, {mode: 0o700, recursive: true});
3500
+ return paths;
3501
+ })();
3502
+ trashPathsCache.set(devId, trashPathsPromise);
3503
+ }
3504
+
3505
+ return trashPathsPromise;
3506
+ };
3507
+
3508
+ return pMap(paths, async filePath => {
3509
+ const stats = await fs$3.promises.lstat(filePath);
3510
+ const trashPaths = await getDeviceTrashPaths(stats.dev);
3511
+ return trash(filePath, trashPaths);
3512
+ }, {concurrency});
3513
+ }
3514
+
3515
+ exports.default = linux;