'use strict';

var os$3 = require('node:os');
var path$5 = require('node:path');
var fs$3 = require('node:fs');
var crypto = require('node:crypto');
var index = require('./index-EjlRQsb6.cjs');
var require$$0$1 = require('fs');
var require$$0 = require('path');
var require$$0$2 = require('child_process');
var require$$1 = require('os');
var require$$1$1 = require('util');
var require$$0$4 = require('assert');
var require$$0$3 = require('events');
var require$$0$6 = require('buffer');
var require$$0$5 = require('stream');
var process$2 = require('node:process');
require('node:dns');
require('constants');
require('url');
require('node:child_process');
require('node:fs/promises');
require('node:util');
require('better-sqlite3');
require('http');
require('https');
require('crypto');
require('http2');
require('tty');
require('zlib');
require('node:events');
require('ntsuspend');
require('node:readline');
require('node:https');
require('node:url');
require('net');
require('node:http');
require('dns');
require('tls');
require('punycode');
require('@napi-rs/canvas');
require('vm');
require('node:stream');
require('node:stream/promises');
require('fs/promises');
require('node:assert');
require('node:net');
require('node:querystring');
require('node:diagnostics_channel');
require('node:tls');
require('node:buffer');
require('node:zlib');
require('node:perf_hooks');
require('node:util/types');
require('node:sqlite');
require('node:worker_threads');
require('node:async_hooks');
require('node:console');
require('node:timers');

var xdgTrashdir$1 = {exports: {}};

var df$5 = {exports: {}};

var execa$2 = {exports: {}};

var crossSpawn$1 = {exports: {}};

const isWindows = process.platform === 'win32' ||
    process.env.OSTYPE === 'cygwin' ||
    process.env.OSTYPE === 'msys';

const path$4 = require$$0;
const COLON = isWindows ? ';' : ':';
const isexe = index.isexe_1;

const getNotFoundError = (cmd) =>
  Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' });

const getPathInfo = (cmd, opt) => {
  const colon = opt.colon || COLON;

  // If it has a slash, then we don't bother searching the pathenv.
  // just check the file itself, and that's it.
  const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? ['']
    : (
      [
        // windows always checks the cwd first
        ...(isWindows ? [process.cwd()] : []),
        ...(opt.path || process.env.PATH ||
          /* istanbul ignore next: very unusual */ '').split(colon),
      ]
    );
  const pathExtExe = isWindows
    ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM'
    : '';
  const pathExt = isWindows ? pathExtExe.split(colon) : [''];

  if (isWindows) {
    if (cmd.indexOf('.') !== -1 && pathExt[0] !== '')
      pathExt.unshift('');
  }

  return {
    pathEnv,
    pathExt,
    pathExtExe,
  }
};

const which$1 = (cmd, opt, cb) => {
  if (typeof opt === 'function') {
    cb = opt;
    opt = {};
  }
  if (!opt)
    opt = {};

  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  const found = [];

  const step = i => new Promise((resolve, reject) => {
    if (i === pathEnv.length)
      return opt.all && found.length ? resolve(found)
        : reject(getNotFoundError(cmd))

    const ppRaw = pathEnv[i];
    const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;

    const pCmd = path$4.join(pathPart, cmd);
    const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
      : pCmd;

    resolve(subStep(p, i, 0));
  });

  const subStep = (p, i, ii) => new Promise((resolve, reject) => {
    if (ii === pathExt.length)
      return resolve(step(i + 1))
    const ext = pathExt[ii];
    isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
      if (!er && is) {
        if (opt.all)
          found.push(p + ext);
        else
          return resolve(p + ext)
      }
      return resolve(subStep(p, i, ii + 1))
    });
  });

  return cb ? step(0).then(res => cb(null, res), cb) : step(0)
};

const whichSync = (cmd, opt) => {
  opt = opt || {};

  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
  const found = [];

  for (let i = 0; i < pathEnv.length; i ++) {
    const ppRaw = pathEnv[i];
    const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;

    const pCmd = path$4.join(pathPart, cmd);
    const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd
      : pCmd;

    for (let j = 0; j < pathExt.length; j ++) {
      const cur = p + pathExt[j];
      try {
        const is = isexe.sync(cur, { pathExt: pathExtExe });
        if (is) {
          if (opt.all)
            found.push(cur);
          else
            return cur
        }
      } catch (ex) {}
    }
  }

  if (opt.all && found.length)
    return found

  if (opt.nothrow)
    return null

  throw getNotFoundError(cmd)
};

var which_1 = which$1;
which$1.sync = whichSync;

var pathKey$1 = {exports: {}};

const pathKey = (options = {}) => {
	const environment = options.env || process.env;
	const platform = options.platform || process.platform;

	if (platform !== 'win32') {
		return 'PATH';
	}

	return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
};

pathKey$1.exports = pathKey;
// TODO: Remove this for the next major release
pathKey$1.exports.default = pathKey;

var pathKeyExports = pathKey$1.exports;

const path$3 = require$$0;
const which = which_1;
const getPathKey = pathKeyExports;

function resolveCommandAttempt(parsed, withoutPathExt) {
    const env = parsed.options.env || process.env;
    const cwd = process.cwd();
    const hasCustomCwd = parsed.options.cwd != null;
    // Worker threads do not have process.chdir()
    const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;

    // If a custom `cwd` was specified, we need to change the process cwd
    // because `which` will do stat calls but does not support a custom cwd
    if (shouldSwitchCwd) {
        try {
            process.chdir(parsed.options.cwd);
        } catch (err) {
            /* Empty */
        }
    }

    let resolved;

    try {
        resolved = which.sync(parsed.command, {
            path: env[getPathKey({ env })],
            pathExt: withoutPathExt ? path$3.delimiter : undefined,
        });
    } catch (e) {
        /* Empty */
    } finally {
        if (shouldSwitchCwd) {
            process.chdir(cwd);
        }
    }

    // If we successfully resolved, ensure that an absolute path is returned
    // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
    if (resolved) {
        resolved = path$3.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
    }

    return resolved;
}

function resolveCommand$1(parsed) {
    return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
}

var resolveCommand_1 = resolveCommand$1;

var _escape = {};

// See http://www.robvanderwoude.com/escapechars.php
const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;

function escapeCommand(arg) {
    // Escape meta chars
    arg = arg.replace(metaCharsRegExp, '^$1');

    return arg;
}

function escapeArgument(arg, doubleEscapeMetaChars) {
    // Convert to string
    arg = `${arg}`;

    // Algorithm below is based on https://qntm.org/cmd
    // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input
    // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information

    // Sequence of backslashes followed by a double quote:
    // double up all the backslashes and escape the double quote
    arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');

    // Sequence of backslashes followed by the end of the string
    // (which will become a double quote later):
    // double up all the backslashes
    arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1');

    // All other backslashes occur literally

    // Quote the whole thing:
    arg = `"${arg}"`;

    // Escape meta chars
    arg = arg.replace(metaCharsRegExp, '^$1');

    // Double escape meta chars if necessary
    if (doubleEscapeMetaChars) {
        arg = arg.replace(metaCharsRegExp, '^$1');
    }

    return arg;
}

_escape.command = escapeCommand;
_escape.argument = escapeArgument;

var shebangRegex$1 = /^#!(.*)/;

const shebangRegex = shebangRegex$1;

var shebangCommand$1 = (string = '') => {
	const match = string.match(shebangRegex);

	if (!match) {
		return null;
	}

	const [path, argument] = match[0].replace(/#! ?/, '').split(' ');
	const binary = path.split('/').pop();

	if (binary === 'env') {
		return argument;
	}

	return argument ? `${binary} ${argument}` : binary;
};

const fs$2 = require$$0$1;
const shebangCommand = shebangCommand$1;

function readShebang$1(command) {
    // Read the first 150 bytes from the file
    const size = 150;
    const buffer = Buffer.alloc(size);

    let fd;

    try {
        fd = fs$2.openSync(command, 'r');
        fs$2.readSync(fd, buffer, 0, size, 0);
        fs$2.closeSync(fd);
    } catch (e) { /* Empty */ }

    // Attempt to extract shebang (null is returned if not a shebang)
    return shebangCommand(buffer.toString());
}

var readShebang_1 = readShebang$1;

const path$2 = require$$0;
const resolveCommand = resolveCommand_1;
const escape = _escape;
const readShebang = readShebang_1;

const isWin$2 = process.platform === 'win32';
const isExecutableRegExp = /\.(?:com|exe)$/i;
const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;

function detectShebang(parsed) {
    parsed.file = resolveCommand(parsed);

    const shebang = parsed.file && readShebang(parsed.file);

    if (shebang) {
        parsed.args.unshift(parsed.file);
        parsed.command = shebang;

        return resolveCommand(parsed);
    }

    return parsed.file;
}

function parseNonShell(parsed) {
    if (!isWin$2) {
        return parsed;
    }

    // Detect & add support for shebangs
    const commandFile = detectShebang(parsed);

    // We don't need a shell if the command filename is an executable
    const needsShell = !isExecutableRegExp.test(commandFile);

    // If a shell is required, use cmd.exe and take care of escaping everything correctly
    // Note that `forceShell` is an hidden option used only in tests
    if (parsed.options.forceShell || needsShell) {
        // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
        // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
        // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
        // we need to double escape them
        const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);

        // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
        // This is necessary otherwise it will always fail with ENOENT in those cases
        parsed.command = path$2.normalize(parsed.command);

        // Escape command & arguments
        parsed.command = escape.command(parsed.command);
        parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));

        const shellCommand = [parsed.command].concat(parsed.args).join(' ');

        parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
        parsed.command = process.env.comspec || 'cmd.exe';
        parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
    }

    return parsed;
}

function parse$1(command, args, options) {
    // Normalize arguments, similar to nodejs
    if (args && !Array.isArray(args)) {
        options = args;
        args = null;
    }

    args = args ? args.slice(0) : []; // Clone array to avoid changing the original
    options = Object.assign({}, options); // Clone object to avoid changing the original

    // Build our parsed object
    const parsed = {
        command,
        args,
        options,
        file: undefined,
        original: {
            command,
            args,
        },
    };

    // Delegate further parsing to shell or non-shell
    return options.shell ? parsed : parseNonShell(parsed);
}

var parse_1 = parse$1;

const isWin$1 = process.platform === 'win32';

function notFoundError(original, syscall) {
    return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
        code: 'ENOENT',
        errno: 'ENOENT',
        syscall: `${syscall} ${original.command}`,
        path: original.command,
        spawnargs: original.args,
    });
}

function hookChildProcess(cp, parsed) {
    if (!isWin$1) {
        return;
    }

    const originalEmit = cp.emit;

    cp.emit = function (name, arg1) {
        // If emitting "exit" event and exit code is 1, we need to check if
        // the command exists and emit an "error" instead
        // See https://github.com/IndigoUnited/node-cross-spawn/issues/16
        if (name === 'exit') {
            const err = verifyENOENT(arg1, parsed);

            if (err) {
                return originalEmit.call(cp, 'error', err);
            }
        }

        return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
    };
}

function verifyENOENT(status, parsed) {
    if (isWin$1 && status === 1 && !parsed.file) {
        return notFoundError(parsed.original, 'spawn');
    }

    return null;
}

function verifyENOENTSync(status, parsed) {
    if (isWin$1 && status === 1 && !parsed.file) {
        return notFoundError(parsed.original, 'spawnSync');
    }

    return null;
}

var enoent$1 = {
    hookChildProcess,
    verifyENOENT,
    verifyENOENTSync,
    notFoundError,
};

const cp = require$$0$2;
const parse = parse_1;
const enoent = enoent$1;

function spawn(command, args, options) {
    // Parse the arguments
    const parsed = parse(command, args, options);

    // Spawn the child process
    const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);

    // Hook into child process "exit" event to emit an error if the command
    // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
    enoent.hookChildProcess(spawned, parsed);

    return spawned;
}

function spawnSync(command, args, options) {
    // Parse the arguments
    const parsed = parse(command, args, options);

    // Spawn the child process
    const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);

    // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
    result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);

    return result;
}

crossSpawn$1.exports = spawn;
crossSpawn$1.exports.spawn = spawn;
crossSpawn$1.exports.sync = spawnSync;

crossSpawn$1.exports._parse = parse;
crossSpawn$1.exports._enoent = enoent;

var crossSpawnExports = crossSpawn$1.exports;

var stripFinalNewline$1 = input => {
	const LF = typeof input === 'string' ? '\n' : '\n'.charCodeAt();
	const CR = typeof input === 'string' ? '\r' : '\r'.charCodeAt();

	if (input[input.length - 1] === LF) {
		input = input.slice(0, input.length - 1);
	}

	if (input[input.length - 1] === CR) {
		input = input.slice(0, input.length - 1);
	}

	return input;
};

var npmRunPath$1 = {exports: {}};

npmRunPath$1.exports;

(function (module) {
	const path = require$$0;
	const pathKey = pathKeyExports;

	const npmRunPath = options => {
		options = {
			cwd: process.cwd(),
			path: process.env[pathKey()],
			...options
		};

		let previous;
		let cwdPath = path.resolve(options.cwd);
		const result = [];

		while (previous !== cwdPath) {
			result.push(path.join(cwdPath, 'node_modules/.bin'));
			previous = cwdPath;
			cwdPath = path.resolve(cwdPath, '..');
		}

		// Ensure the running `node` binary is used
		result.push(path.dirname(process.execPath));

		return result.concat(options.path).join(path.delimiter);
	};

	module.exports = npmRunPath;
	// TODO: Remove this for the next major release
	module.exports.default = npmRunPath;

	module.exports.env = options => {
		options = {
			env: process.env,
			...options
		};

		const env = {...options.env};
		const path = pathKey({env});

		options.path = env[path];
		env[path] = module.exports(options);

		return env;
	}; 
} (npmRunPath$1));

var npmRunPathExports = npmRunPath$1.exports;

var onetime$2 = {exports: {}};

var mimicFn$2 = {exports: {}};

const mimicFn$1 = (to, from) => {
	for (const prop of Reflect.ownKeys(from)) {
		Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
	}

	return to;
};

mimicFn$2.exports = mimicFn$1;
// TODO: Remove this for the next major release
mimicFn$2.exports.default = mimicFn$1;

var mimicFnExports = mimicFn$2.exports;

const mimicFn = mimicFnExports;

const calledFunctions = new WeakMap();

const onetime$1 = (function_, options = {}) => {
	if (typeof function_ !== 'function') {
		throw new TypeError('Expected a function');
	}

	let returnValue;
	let callCount = 0;
	const functionName = function_.displayName || function_.name || '<anonymous>';

	const onetime = function (...arguments_) {
		calledFunctions.set(onetime, ++callCount);

		if (callCount === 1) {
			returnValue = function_.apply(this, arguments_);
			function_ = null;
		} else if (options.throw === true) {
			throw new Error(`Function \`${functionName}\` can only be called once`);
		}

		return returnValue;
	};

	mimicFn(onetime, function_);
	calledFunctions.set(onetime, callCount);

	return onetime;
};

onetime$2.exports = onetime$1;
// TODO: Remove this for the next major release
onetime$2.exports.default = onetime$1;

onetime$2.exports.callCount = function_ => {
	if (!calledFunctions.has(function_)) {
		throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
	}

	return calledFunctions.get(function_);
};

var onetimeExports = onetime$2.exports;

const os$2 = require$$1;
const util = require$$1$1;

const getCode = (error, code) => {
	if (error && error.code) {
		return [error.code, os$2.constants.errno[error.code]];
	}

	if (Number.isInteger(code)) {
		return [util.getSystemErrorName(-code), code];
	}

	return [];
};

const getErrorPrefix = ({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled}) => {
	if (timedOut) {
		return `timed out after ${timeout} milliseconds`;
	}

	if (isCanceled) {
		return 'was canceled';
	}

	if (signal) {
		return `was killed with ${signal}`;
	}

	if (exitCode !== undefined) {
		return `failed with exit code ${exitCode} (${exitCodeName})`;
	}

	return 'failed';
};

const makeError$1 = ({
	stdout,
	stderr,
	all,
	error,
	signal,
	code,
	command,
	timedOut,
	isCanceled,
	killed,
	parsed: {options: {timeout}}
}) => {
	const [exitCodeName, exitCode] = getCode(error, code);

	const prefix = getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled});
	const message = `Command ${prefix}: ${command}`;

	if (error instanceof Error) {
		error.originalMessage = error.message;
		error.message = `${message}\n${error.message}`;
	} else {
		error = new Error(message);
	}

	error.command = command;
	delete error.code;
	error.exitCode = exitCode;
	error.exitCodeName = exitCodeName;
	error.stdout = stdout;
	error.stderr = stderr;

	if (all !== undefined) {
		error.all = all;
	}

	if ('bufferedData' in error) {
		delete error.bufferedData;
	}

	error.failed = true;
	error.timedOut = Boolean(timedOut);
	error.isCanceled = isCanceled;
	error.killed = killed && !timedOut;
	// `signal` emitted on `spawned.on('exit')` event can be `null`. We normalize
	// it to `undefined`
	error.signal = signal || undefined;

	return error;
};

var error = makeError$1;

var stdio = {exports: {}};

const aliases = ['stdin', 'stdout', 'stderr'];

const hasAlias = opts => aliases.some(alias => opts[alias] !== undefined);

const normalizeStdio$1 = opts => {
	if (!opts) {
		return;
	}

	const {stdio} = opts;

	if (stdio === undefined) {
		return aliases.map(alias => opts[alias]);
	}

	if (hasAlias(opts)) {
		throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);
	}

	if (typeof stdio === 'string') {
		return stdio;
	}

	if (!Array.isArray(stdio)) {
		throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
	}

	const length = Math.max(stdio.length, aliases.length);
	return Array.from({length}, (value, index) => stdio[index]);
};

stdio.exports = normalizeStdio$1;

// `ipc` is pushed unless it is already present
stdio.exports.node = opts => {
	const stdio = normalizeStdio$1(opts);

	if (stdio === 'ipc') {
		return 'ipc';
	}

	if (stdio === undefined || typeof stdio === 'string') {
		return [stdio, stdio, stdio, 'ipc'];
	}

	if (stdio.includes('ipc')) {
		return stdio;
	}

	return [...stdio, 'ipc'];
};

var stdioExports = stdio.exports;

var signalExit = {exports: {}};

var signals$1 = {exports: {}};

var hasRequiredSignals;

function requireSignals () {
	if (hasRequiredSignals) return signals$1.exports;
	hasRequiredSignals = 1;
	(function (module) {
		// This is not the set of all possible signals.
		//
		// It IS, however, the set of all signals that trigger
		// an exit on either Linux or BSD systems.  Linux is a
		// superset of the signal names supported on BSD, and
		// the unknown signals just fail to register, so we can
		// catch that easily enough.
		//
		// Don't bother with SIGKILL.  It's uncatchable, which
		// means that we can't fire any callbacks anyway.
		//
		// If a user does happen to register a handler on a non-
		// fatal signal like SIGWINCH or something, and then
		// exit, it'll end up firing `process.emit('exit')`, so
		// the handler will be fired anyway.
		//
		// SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
		// artificially, inherently leave the process in a
		// state from which it is not safe to try and enter JS
		// listeners.
		module.exports = [
		  'SIGABRT',
		  'SIGALRM',
		  'SIGHUP',
		  'SIGINT',
		  'SIGTERM'
		];

		if (process.platform !== 'win32') {
		  module.exports.push(
		    'SIGVTALRM',
		    'SIGXCPU',
		    'SIGXFSZ',
		    'SIGUSR2',
		    'SIGTRAP',
		    'SIGSYS',
		    'SIGQUIT',
		    'SIGIOT'
		    // should detect profiler and enable/disable accordingly.
		    // see #21
		    // 'SIGPROF'
		  );
		}

		if (process.platform === 'linux') {
		  module.exports.push(
		    'SIGIO',
		    'SIGPOLL',
		    'SIGPWR',
		    'SIGSTKFLT',
		    'SIGUNUSED'
		  );
		} 
	} (signals$1));
	return signals$1.exports;
}

// Note: since nyc uses this module to output coverage, any lines
// that are in the direct sync flow of nyc's outputCoverage are
// ignored, since we can never get coverage for them.
// grab a reference to node's real process object right away
var process$1 = index.commonjsGlobal.process;

const processOk = function (process) {
  return process &&
    typeof process === 'object' &&
    typeof process.removeListener === 'function' &&
    typeof process.emit === 'function' &&
    typeof process.reallyExit === 'function' &&
    typeof process.listeners === 'function' &&
    typeof process.kill === 'function' &&
    typeof process.pid === 'number' &&
    typeof process.on === 'function'
};

// some kind of non-node environment, just no-op
/* istanbul ignore if */
if (!processOk(process$1)) {
  signalExit.exports = function () {
    return function () {}
  };
} else {
  var assert = require$$0$4;
  var signals = requireSignals();
  var isWin = /^win/i.test(process$1.platform);

  var EE = require$$0$3;
  /* istanbul ignore if */
  if (typeof EE !== 'function') {
    EE = EE.EventEmitter;
  }

  var emitter;
  if (process$1.__signal_exit_emitter__) {
    emitter = process$1.__signal_exit_emitter__;
  } else {
    emitter = process$1.__signal_exit_emitter__ = new EE();
    emitter.count = 0;
    emitter.emitted = {};
  }

  // Because this emitter is a global, we have to check to see if a
  // previous version of this library failed to enable infinite listeners.
  // I know what you're about to say.  But literally everything about
  // signal-exit is a compromise with evil.  Get used to it.
  if (!emitter.infinite) {
    emitter.setMaxListeners(Infinity);
    emitter.infinite = true;
  }

  signalExit.exports = function (cb, opts) {
    /* istanbul ignore if */
    if (!processOk(index.commonjsGlobal.process)) {
      return function () {}
    }
    assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');

    if (loaded === false) {
      load();
    }

    var ev = 'exit';
    if (opts && opts.alwaysLast) {
      ev = 'afterexit';
    }

    var remove = function () {
      emitter.removeListener(ev, cb);
      if (emitter.listeners('exit').length === 0 &&
          emitter.listeners('afterexit').length === 0) {
        unload();
      }
    };
    emitter.on(ev, cb);

    return remove
  };

  var unload = function unload () {
    if (!loaded || !processOk(index.commonjsGlobal.process)) {
      return
    }
    loaded = false;

    signals.forEach(function (sig) {
      try {
        process$1.removeListener(sig, sigListeners[sig]);
      } catch (er) {}
    });
    process$1.emit = originalProcessEmit;
    process$1.reallyExit = originalProcessReallyExit;
    emitter.count -= 1;
  };
  signalExit.exports.unload = unload;

  var emit = function emit (event, code, signal) {
    /* istanbul ignore if */
    if (emitter.emitted[event]) {
      return
    }
    emitter.emitted[event] = true;
    emitter.emit(event, code, signal);
  };

  // { <signal>: <listener fn>, ... }
  var sigListeners = {};
  signals.forEach(function (sig) {
    sigListeners[sig] = function listener () {
      /* istanbul ignore if */
      if (!processOk(index.commonjsGlobal.process)) {
        return
      }
      // If there are no other listeners, an exit is coming!
      // Simplest way: remove us and then re-send the signal.
      // We know that this will kill the process, so we can
      // safely emit now.
      var listeners = process$1.listeners(sig);
      if (listeners.length === emitter.count) {
        unload();
        emit('exit', null, sig);
        /* istanbul ignore next */
        emit('afterexit', null, sig);
        /* istanbul ignore next */
        if (isWin && sig === 'SIGHUP') {
          // "SIGHUP" throws an `ENOSYS` error on Windows,
          // so use a supported signal instead
          sig = 'SIGINT';
        }
        /* istanbul ignore next */
        process$1.kill(process$1.pid, sig);
      }
    };
  });

  signalExit.exports.signals = function () {
    return signals
  };

  var loaded = false;

  var load = function load () {
    if (loaded || !processOk(index.commonjsGlobal.process)) {
      return
    }
    loaded = true;

    // This is the number of onSignalExit's that are in play.
    // It's important so that we can count the correct number of
    // listeners on signals, and don't wait for the other one to
    // handle it instead of us.
    emitter.count += 1;

    signals = signals.filter(function (sig) {
      try {
        process$1.on(sig, sigListeners[sig]);
        return true
      } catch (er) {
        return false
      }
    });

    process$1.emit = processEmit;
    process$1.reallyExit = processReallyExit;
  };
  signalExit.exports.load = load;

  var originalProcessReallyExit = process$1.reallyExit;
  var processReallyExit = function processReallyExit (code) {
    /* istanbul ignore if */
    if (!processOk(index.commonjsGlobal.process)) {
      return
    }
    process$1.exitCode = code || /* istanbul ignore next */ 0;
    emit('exit', process$1.exitCode, null);
    /* istanbul ignore next */
    emit('afterexit', process$1.exitCode, null);
    /* istanbul ignore next */
    originalProcessReallyExit.call(process$1, process$1.exitCode);
  };

  var originalProcessEmit = process$1.emit;
  var processEmit = function processEmit (ev, arg) {
    if (ev === 'exit' && processOk(index.commonjsGlobal.process)) {
      /* istanbul ignore else */
      if (arg !== undefined) {
        process$1.exitCode = arg;
      }
      var ret = originalProcessEmit.apply(this, arguments);
      /* istanbul ignore next */
      emit('exit', process$1.exitCode, null);
      /* istanbul ignore next */
      emit('afterexit', process$1.exitCode, null);
      /* istanbul ignore next */
      return ret
    } else {
      return originalProcessEmit.apply(this, arguments)
    }
  };
}

var signalExitExports = signalExit.exports;

var pFinally$1 = async (
	promise,
	onFinally = (() => {})
) => {
	let value;
	try {
		value = await promise;
	} catch (error) {
		await onFinally();
		throw error;
	}

	await onFinally();
	return value;
};

const os$1 = require$$1;
const onExit = signalExitExports;
const pFinally = pFinally$1;

const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;

// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior
const spawnedKill$1 = (kill, signal = 'SIGTERM', options = {}) => {
	const killResult = kill(signal);
	setKillTimeout(kill, signal, options, killResult);
	return killResult;
};

const setKillTimeout = (kill, signal, options, killResult) => {
	if (!shouldForceKill(signal, options, killResult)) {
		return;
	}

	const timeout = getForceKillAfterTimeout(options);
	setTimeout(() => {
		kill('SIGKILL');
	}, timeout).unref();
};

const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {
	return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
};

const isSigterm = signal => {
	return signal === os$1.constants.signals.SIGTERM ||
		(typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
};

const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
	if (forceKillAfterTimeout === true) {
		return DEFAULT_FORCE_KILL_TIMEOUT;
	}

	if (!Number.isInteger(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
		throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
	}

	return forceKillAfterTimeout;
};

// `childProcess.cancel()`
const spawnedCancel$1 = (spawned, context) => {
	const killResult = spawned.kill();

	if (killResult) {
		context.isCanceled = true;
	}
};

const timeoutKill = (spawned, signal, reject) => {
	spawned.kill(signal);
	reject(Object.assign(new Error('Timed out'), {timedOut: true, signal}));
};

// `timeout` option handling
const setupTimeout$1 = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {
	if (timeout === 0 || timeout === undefined) {
		return spawnedPromise;
	}

	if (!Number.isInteger(timeout) || timeout < 0) {
		throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
	}

	let timeoutId;
	const timeoutPromise = new Promise((resolve, reject) => {
		timeoutId = setTimeout(() => {
			timeoutKill(spawned, killSignal, reject);
		}, timeout);
	});

	const safeSpawnedPromise = pFinally(spawnedPromise, () => {
		clearTimeout(timeoutId);
	});

	return Promise.race([timeoutPromise, safeSpawnedPromise]);
};

// `cleanup` option handling
const setExitHandler$1 = (spawned, {cleanup, detached}, timedPromise) => {
	if (!cleanup || detached) {
		return timedPromise;
	}

	const removeExitHandler = onExit(() => {
		spawned.kill();
	});

	// TODO: Use native "finally" syntax when targeting Node.js 10
	return pFinally(timedPromise, removeExitHandler);
};

var kill = {
	spawnedKill: spawnedKill$1,
	spawnedCancel: spawnedCancel$1,
	setupTimeout: setupTimeout$1,
	setExitHandler: setExitHandler$1
};

const isStream$1 = stream =>
	stream !== null &&
	typeof stream === 'object' &&
	typeof stream.pipe === 'function';

isStream$1.writable = stream =>
	isStream$1(stream) &&
	stream.writable !== false &&
	typeof stream._write === 'function' &&
	typeof stream._writableState === 'object';

isStream$1.readable = stream =>
	isStream$1(stream) &&
	stream.readable !== false &&
	typeof stream._read === 'function' &&
	typeof stream._readableState === 'object';

isStream$1.duplex = stream =>
	isStream$1.writable(stream) &&
	isStream$1.readable(stream);

isStream$1.transform = stream =>
	isStream$1.duplex(stream) &&
	typeof stream._transform === 'function';

var isStream_1 = isStream$1;

var getStream$2 = {exports: {}};

var once$1 = index.onceExports;

var noop$1 = function() {};

var isRequest$1 = function(stream) {
	return stream.setHeader && typeof stream.abort === 'function';
};

var isChildProcess = function(stream) {
	return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3
};

var eos$1 = function(stream, opts, callback) {
	if (typeof opts === 'function') return eos$1(stream, null, opts);
	if (!opts) opts = {};

	callback = once$1(callback || noop$1);

	var ws = stream._writableState;
	var rs = stream._readableState;
	var readable = opts.readable || (opts.readable !== false && stream.readable);
	var writable = opts.writable || (opts.writable !== false && stream.writable);
	var cancelled = false;

	var onlegacyfinish = function() {
		if (!stream.writable) onfinish();
	};

	var onfinish = function() {
		writable = false;
		if (!readable) callback.call(stream);
	};

	var onend = function() {
		readable = false;
		if (!writable) callback.call(stream);
	};

	var onexit = function(exitCode) {
		callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null);
	};

	var onerror = function(err) {
		callback.call(stream, err);
	};

	var onclose = function() {
		process.nextTick(onclosenexttick);
	};

	var onclosenexttick = function() {
		if (cancelled) return;
		if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));
		if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));
	};

	var onrequest = function() {
		stream.req.on('finish', onfinish);
	};

	if (isRequest$1(stream)) {
		stream.on('complete', onfinish);
		stream.on('abort', onclose);
		if (stream.req) onrequest();
		else stream.on('request', onrequest);
	} else if (writable && !ws) { // legacy streams
		stream.on('end', onlegacyfinish);
		stream.on('close', onlegacyfinish);
	}

	if (isChildProcess(stream)) stream.on('exit', onexit);

	stream.on('end', onend);
	stream.on('finish', onfinish);
	if (opts.error !== false) stream.on('error', onerror);
	stream.on('close', onclose);

	return function() {
		cancelled = true;
		stream.removeListener('complete', onfinish);
		stream.removeListener('abort', onclose);
		stream.removeListener('request', onrequest);
		if (stream.req) stream.req.removeListener('finish', onfinish);
		stream.removeListener('end', onlegacyfinish);
		stream.removeListener('close', onlegacyfinish);
		stream.removeListener('finish', onfinish);
		stream.removeListener('exit', onexit);
		stream.removeListener('end', onend);
		stream.removeListener('error', onerror);
		stream.removeListener('close', onclose);
	};
};

var endOfStream = eos$1;

var once = index.onceExports;
var eos = endOfStream;
var fs$1;

try {
  fs$1 = require('fs'); // we only need fs to get the ReadStream and WriteStream prototypes
} catch (e) {}

var noop = function () {};
var ancient = /^v?\.0/.test(process.version);

var isFn = function (fn) {
  return typeof fn === 'function'
};

var isFS = function (stream) {
  if (!ancient) return false // newer node version do not need to care about fs is a special way
  if (!fs$1) return false // browser
  return (stream instanceof (fs$1.ReadStream || noop) || stream instanceof (fs$1.WriteStream || noop)) && isFn(stream.close)
};

var isRequest = function (stream) {
  return stream.setHeader && isFn(stream.abort)
};

var destroyer = function (stream, reading, writing, callback) {
  callback = once(callback);

  var closed = false;
  stream.on('close', function () {
    closed = true;
  });

  eos(stream, {readable: reading, writable: writing}, function (err) {
    if (err) return callback(err)
    closed = true;
    callback();
  });

  var destroyed = false;
  return function (err) {
    if (closed) return
    if (destroyed) return
    destroyed = true;

    if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks
    if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want

    if (isFn(stream.destroy)) return stream.destroy()

    callback(err || new Error('stream was destroyed'));
  }
};

var call = function (fn) {
  fn();
};

var pipe = function (from, to) {
  return from.pipe(to)
};

var pump$1 = function () {
  var streams = Array.prototype.slice.call(arguments);
  var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop;

  if (Array.isArray(streams[0])) streams = streams[0];
  if (streams.length < 2) throw new Error('pump requires two streams per minimum')

  var error;
  var destroys = streams.map(function (stream, i) {
    var reading = i < streams.length - 1;
    var writing = i > 0;
    return destroyer(stream, reading, writing, function (err) {
      if (!error) error = err;
      if (err) destroys.forEach(call);
      if (reading) return
      destroys.forEach(call);
      callback(error);
    })
  });

  return streams.reduce(pipe)
};

var pump_1 = pump$1;

const {PassThrough: PassThroughStream} = require$$0$5;

var bufferStream$1 = options => {
	options = {...options};

	const {array} = options;
	let {encoding} = options;
	const isBuffer = encoding === 'buffer';
	let objectMode = false;

	if (array) {
		objectMode = !(encoding || isBuffer);
	} else {
		encoding = encoding || 'utf8';
	}

	if (isBuffer) {
		encoding = null;
	}

	const stream = new PassThroughStream({objectMode});

	if (encoding) {
		stream.setEncoding(encoding);
	}

	let length = 0;
	const chunks = [];

	stream.on('data', chunk => {
		chunks.push(chunk);

		if (objectMode) {
			length = chunks.length;
		} else {
			length += chunk.length;
		}
	});

	stream.getBufferedValue = () => {
		if (array) {
			return chunks;
		}

		return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
	};

	stream.getBufferedLength = () => length;

	return stream;
};

const {constants: BufferConstants} = require$$0$6;
const pump = pump_1;
const bufferStream = bufferStream$1;

class MaxBufferError extends Error {
	constructor() {
		super('maxBuffer exceeded');
		this.name = 'MaxBufferError';
	}
}

async function getStream$1(inputStream, options) {
	if (!inputStream) {
		return Promise.reject(new Error('Expected a stream'));
	}

	options = {
		maxBuffer: Infinity,
		...options
	};

	const {maxBuffer} = options;

	let stream;
	await new Promise((resolve, reject) => {
		const rejectPromise = error => {
			// Don't retrieve an oversized buffer.
			if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
				error.bufferedData = stream.getBufferedValue();
			}

			reject(error);
		};

		stream = pump(inputStream, bufferStream(options), error => {
			if (error) {
				rejectPromise(error);
				return;
			}

			resolve();
		});

		stream.on('data', () => {
			if (stream.getBufferedLength() > maxBuffer) {
				rejectPromise(new MaxBufferError());
			}
		});
	});

	return stream.getBufferedValue();
}

getStream$2.exports = getStream$1;
// TODO: Remove this for the next major release
getStream$2.exports.default = getStream$1;
getStream$2.exports.buffer = (stream, options) => getStream$1(stream, {...options, encoding: 'buffer'});
getStream$2.exports.array = (stream, options) => getStream$1(stream, {...options, array: true});
getStream$2.exports.MaxBufferError = MaxBufferError;

var getStreamExports = getStream$2.exports;

const { PassThrough } = require$$0$5;

var mergeStream$1 = function (/*streams...*/) {
  var sources = [];
  var output  = new PassThrough({objectMode: true});

  output.setMaxListeners(0);

  output.add = add;
  output.isEmpty = isEmpty;

  output.on('unpipe', remove);

  Array.prototype.slice.call(arguments).forEach(add);

  return output

  function add (source) {
    if (Array.isArray(source)) {
      source.forEach(add);
      return this
    }

    sources.push(source);
    source.once('end', remove.bind(null, source));
    source.once('error', output.emit.bind(output, 'error'));
    source.pipe(output, {end: false});
    return this
  }

  function isEmpty () {
    return sources.length == 0;
  }

  function remove (source) {
    sources = sources.filter(function (it) { return it !== source });
    if (!sources.length && output.readable) { output.end(); }
  }
};

const isStream = isStream_1;
const getStream = getStreamExports;
const mergeStream = mergeStream$1;

// `input` option
const handleInput$1 = (spawned, input) => {
	// Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852
	// TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0
	if (input === undefined || spawned.stdin === undefined) {
		return;
	}

	if (isStream(input)) {
		input.pipe(spawned.stdin);
	} else {
		spawned.stdin.end(input);
	}
};

// `all` interleaves `stdout` and `stderr`
const makeAllStream$1 = spawned => {
	if (!spawned.stdout && !spawned.stderr) {
		return;
	}

	const mixed = mergeStream();

	if (spawned.stdout) {
		mixed.add(spawned.stdout);
	}

	if (spawned.stderr) {
		mixed.add(spawned.stderr);
	}

	return mixed;
};

// On failure, `result.stdout|stderr|all` should contain the currently buffered stream
const getBufferedData = async (stream, streamPromise) => {
	if (!stream) {
		return;
	}

	stream.destroy();

	try {
		return await streamPromise;
	} catch (error) {
		return error.bufferedData;
	}
};

const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {
	if (!stream) {
		return;
	}

	if (!buffer) {
		// TODO: Use `ret = util.promisify(stream.finished)(stream);` when targeting Node.js 10
		return new Promise((resolve, reject) => {
			stream
				.once('end', resolve)
				.once('error', reject);
		});
	}

	if (encoding) {
		return getStream(stream, {encoding, maxBuffer});
	}

	return getStream.buffer(stream, {maxBuffer});
};

// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)
const getSpawnedResult$1 = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {
	const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});
	const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});
	const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});

	try {
		return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
	} catch (error) {
		return Promise.all([
			{error, code: error.code, signal: error.signal, timedOut: error.timedOut},
			getBufferedData(stdout, stdoutPromise),
			getBufferedData(stderr, stderrPromise),
			getBufferedData(all, allPromise)
		]);
	}
};

const validateInputSync$1 = ({input}) => {
	if (isStream(input)) {
		throw new TypeError('The `input` option cannot be a stream in sync mode');
	}
};

var stream = {
	handleInput: handleInput$1,
	makeAllStream: makeAllStream$1,
	getSpawnedResult: getSpawnedResult$1,
	validateInputSync: validateInputSync$1
};

const mergePromiseProperty = (spawned, promise, property) => {
	// Starting the main `promise` is deferred to avoid consuming streams
	const value = typeof promise === 'function' ?
		(...args) => promise()[property](...args) :
		promise[property].bind(promise);

	Object.defineProperty(spawned, property, {
		value,
		writable: true,
		enumerable: false,
		configurable: true
	});
};

// The return value is a mixin of `childProcess` and `Promise`
const mergePromise$1 = (spawned, promise) => {
	mergePromiseProperty(spawned, promise, 'then');
	mergePromiseProperty(spawned, promise, 'catch');

	// TODO: Remove the `if`-guard when targeting Node.js 10
	if (Promise.prototype.finally) {
		mergePromiseProperty(spawned, promise, 'finally');
	}

	return spawned;
};

// Use promises instead of `child_process` events
const getSpawnedPromise$1 = spawned => {
	return new Promise((resolve, reject) => {
		spawned.on('exit', (code, signal) => {
			resolve({code, signal});
		});

		spawned.on('error', error => {
			reject(error);
		});

		if (spawned.stdin) {
			spawned.stdin.on('error', error => {
				reject(error);
			});
		}
	});
};

var promise = {
	mergePromise: mergePromise$1,
	getSpawnedPromise: getSpawnedPromise$1
};

const SPACES_REGEXP = / +/g;

const joinCommand$1 = (file, args = []) => {
	if (!Array.isArray(args)) {
		return file;
	}

	return [file, ...args].join(' ');
};

// Allow spaces to be escaped by a backslash if not meant as a delimiter
const handleEscaping = (tokens, token, index) => {
	if (index === 0) {
		return [token];
	}

	const previousToken = tokens[tokens.length - 1];

	if (previousToken.endsWith('\\')) {
		return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`];
	}

	return [...tokens, token];
};

// Handle `execa.command()`
const parseCommand$1 = command => {
	return command
		.trim()
		.split(SPACES_REGEXP)
		.reduce(handleEscaping, []);
};

var command = {
	joinCommand: joinCommand$1,
	parseCommand: parseCommand$1
};

const path$1 = require$$0;
const childProcess$1 = require$$0$2;
const crossSpawn = crossSpawnExports;
const stripFinalNewline = stripFinalNewline$1;
const npmRunPath = npmRunPathExports;
const onetime = onetimeExports;
const makeError = error;
const normalizeStdio = stdioExports;
const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler} = kill;
const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = stream;
const {mergePromise, getSpawnedPromise} = promise;
const {joinCommand, parseCommand} = command;

const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;

const getEnv = ({env: envOption, extendEnv, preferLocal, localDir}) => {
	const env = extendEnv ? {...process.env, ...envOption} : envOption;

	if (preferLocal) {
		return npmRunPath.env({env, cwd: localDir});
	}

	return env;
};

const handleArgs = (file, args, options = {}) => {
	const parsed = crossSpawn._parse(file, args, options);
	file = parsed.command;
	args = parsed.args;
	options = parsed.options;

	options = {
		maxBuffer: DEFAULT_MAX_BUFFER,
		buffer: true,
		stripFinalNewline: true,
		extendEnv: true,
		preferLocal: false,
		localDir: options.cwd || process.cwd(),
		encoding: 'utf8',
		reject: true,
		cleanup: true,
		...options,
		windowsHide: true
	};

	options.env = getEnv(options);

	options.stdio = normalizeStdio(options);

	if (process.platform === 'win32' && path$1.basename(file, '.exe') === 'cmd') {
		// #116
		args.unshift('/q');
	}

	return {file, args, options, parsed};
};

const handleOutput = (options, value, error) => {
	if (typeof value !== 'string' && !Buffer.isBuffer(value)) {
		// When `execa.sync()` errors, we normalize it to '' to mimic `execa()`
		return error === undefined ? undefined : '';
	}

	if (options.stripFinalNewline) {
		return stripFinalNewline(value);
	}

	return value;
};

const execa$1 = (file, args, options) => {
	const parsed = handleArgs(file, args, options);
	const command = joinCommand(file, args);

	let spawned;
	try {
		spawned = childProcess$1.spawn(parsed.file, parsed.args, parsed.options);
	} catch (error) {
		// Ensure the returned error is always both a promise and a child process
		const dummySpawned = new childProcess$1.ChildProcess();
		const errorPromise = Promise.reject(makeError({
			error,
			stdout: '',
			stderr: '',
			all: '',
			command,
			parsed,
			timedOut: false,
			isCanceled: false,
			killed: false
		}));
		return mergePromise(dummySpawned, errorPromise);
	}

	const spawnedPromise = getSpawnedPromise(spawned);
	const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
	const processDone = setExitHandler(spawned, parsed.options, timedPromise);

	const context = {isCanceled: false};

	spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
	spawned.cancel = spawnedCancel.bind(null, spawned, context);

	const handlePromise = async () => {
		const [{error, code, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
		const stdout = handleOutput(parsed.options, stdoutResult);
		const stderr = handleOutput(parsed.options, stderrResult);
		const all = handleOutput(parsed.options, allResult);

		if (error || code !== 0 || signal !== null) {
			const returnedError = makeError({
				error,
				code,
				signal,
				stdout,
				stderr,
				all,
				command,
				parsed,
				timedOut,
				isCanceled: context.isCanceled,
				killed: spawned.killed
			});

			if (!parsed.options.reject) {
				return returnedError;
			}

			throw returnedError;
		}

		return {
			command,
			exitCode: 0,
			exitCodeName: 'SUCCESS',
			stdout,
			stderr,
			all,
			failed: false,
			timedOut: false,
			isCanceled: false,
			killed: false
		};
	};

	const handlePromiseOnce = onetime(handlePromise);

	crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);

	handleInput(spawned, parsed.options.input);

	spawned.all = makeAllStream(spawned);

	return mergePromise(spawned, handlePromiseOnce);
};

execa$2.exports = execa$1;

execa$2.exports.sync = (file, args, options) => {
	const parsed = handleArgs(file, args, options);
	const command = joinCommand(file, args);

	validateInputSync(parsed.options);

	let result;
	try {
		result = childProcess$1.spawnSync(parsed.file, parsed.args, parsed.options);
	} catch (error) {
		throw makeError({
			error,
			stdout: '',
			stderr: '',
			all: '',
			command,
			parsed,
			timedOut: false,
			isCanceled: false,
			killed: false
		});
	}

	result.stdout = handleOutput(parsed.options, result.stdout, result.error);
	result.stderr = handleOutput(parsed.options, result.stderr, result.error);

	if (result.error || result.status !== 0 || result.signal !== null) {
		const error = makeError({
			...result,
			code: result.status,
			command,
			parsed,
			timedOut: result.error && result.error.code === 'ETIMEDOUT',
			isCanceled: false,
			killed: result.signal !== null
		});

		if (!parsed.options.reject) {
			return error;
		}

		throw error;
	}

	return {
		command,
		exitCode: 0,
		exitCodeName: 'SUCCESS',
		stdout: result.stdout,
		stderr: result.stderr,
		failed: false,
		timedOut: false,
		isCanceled: false,
		killed: false
	};
};

execa$2.exports.command = (command, options) => {
	const [file, ...args] = parseCommand(command);
	return execa$1(file, args, options);
};

execa$2.exports.commandSync = (command, options) => {
	const [file, ...args] = parseCommand(command);
	return execa$1.sync(file, args, options);
};

execa$2.exports.node = (scriptPath, args, options = {}) => {
	if (args && !Array.isArray(args) && typeof args === 'object') {
		options = args;
		args = [];
	}

	const stdio = normalizeStdio.node(options);

	const {nodePath = process.execPath, nodeOptions = process.execArgv} = options;

	return execa$1(
		nodePath,
		[
			...nodeOptions,
			scriptPath,
			...(Array.isArray(args) ? args : [])
		],
		{
			...options,
			stdin: undefined,
			stdout: undefined,
			stderr: undefined,
			stdio,
			shell: false
		}
	);
};

var execaExports = execa$2.exports;

const execa = execaExports;

const getColumnBoundaries = async header => {
	// Regex captures each individual column
	// ^\S+\s+       -> First column
	// \s*\S+\s*\S+$ -> Last column (combined)
	// \s*\S+        -> Regular columns
	const regex = /^\S+\s+|\s*\S+\s*\S+$|\s*\S+/g;
	const boundaries = [];
	let match;

	while ((match = regex.exec(header))) {
		boundaries.push(match[0].length);
	}

	// Extend last column boundary
	boundaries[boundaries.length - 1] = -1;

	return boundaries;
};

const parseOutput = async output => {
	const lines = output.trim().split('\n');
	const boundaries = await getColumnBoundaries(lines[0]);

	return lines.slice(1).map(line => {
		const cl = boundaries.map(boundary => {
			// Handle extra-long last column
			const column = boundary > 0 ? line.slice(0, boundary) : line;
			line = line.slice(boundary);
			return column.trim();
		});

		return {
			filesystem: cl[0],
			size: parseInt(cl[1], 10) * 1024,
			used: parseInt(cl[2], 10) * 1024,
			available: parseInt(cl[3], 10) * 1024,
			capacity: parseInt(cl[4], 10) / 100,
			mountpoint: cl[5]
		};
	});
};

const run$1 = async args => {
	const {stdout} = await execa('df', args);
	return parseOutput(stdout);
};

const df$4 = async () => run$1(['-kP']);

df$4.fs = async name => {
	if (typeof name !== 'string') {
		throw new TypeError('The `name` parameter required');
	}

	const data = await run$1(['-kP']);

	for (const item of data) {
		if (item.filesystem === name) {
			return item;
		}
	}

	throw new Error(`The specified filesystem \`${name}\` doesn't exist`);
};

df$4.file = async file => {
	if (typeof file !== 'string') {
		throw new TypeError('The `file` parameter is required');
	}

	let data;
	try {
		data = await run$1(['-kP', file]);
	} catch (error) {
		if (/No such file or directory/.test(error.stderr)) {
			throw new Error(`The specified file \`${file}\` doesn't exist`);
		}

		throw error;
	}

	return data[0];
};

df$5.exports = df$4;
// TODO: remove this in the next major version
df$5.exports.default = df$4;

if (process.env.NODE_ENV === 'test') {
	df$5.exports._parseOutput = parseOutput;
}

var dfExports$1 = df$5.exports;

var df$3 = {exports: {}};

var childProcess = require$$0$2;

function run(args, cb) {
	childProcess.execFile('df', args, function (err, stdout) {
		if (err) {
			cb(err);
			return;
		}

		cb(null, stdout.trim().split('\n').slice(1).map(function (el) {
			var cl = el.split(/\s+(?=[\d\/])/);

			return {
				filesystem: cl[0],
				size: parseInt(cl[1], 10) * 1024,
				used: parseInt(cl[2], 10) * 1024,
				available: parseInt(cl[3], 10) * 1024,
				capacity: parseInt(cl[4], 10) / 100,
				mountpoint: cl[5]
			};
		}));
	});
}
var df$2 = df$3.exports = function (cb) {
	run(['-kP'], cb);
};

df$2.fs = function (name, cb) {
	if (typeof name !== 'string') {
		throw new Error('name required');
	}

	run(['-kP'], function (err, data) {
		if (err) {
			cb(err);
			return;
		}

		var ret;

		data.forEach(function (el) {
			if (el.filesystem === name) {
				ret = el;
			}
		});

		cb(null, ret);
	});
};

df$2.file = function (file, cb) {
	if (typeof file !== 'string') {
		throw new Error('file required');
	}

	run(['-kP', file], function (err, data) {
		if (err) {
			cb(err);
			return;
		}

		cb(null, data[0]);
	});
};

var dfExports = df$3.exports;

var pify$2 = {exports: {}};

var processFn = function (fn, P, opts) {
	return function () {
		var that = this;
		var args = new Array(arguments.length);

		for (var i = 0; i < arguments.length; i++) {
			args[i] = arguments[i];
		}

		return new P(function (resolve, reject) {
			args.push(function (err, result) {
				if (err) {
					reject(err);
				} else if (opts.multiArgs) {
					var results = new Array(arguments.length - 1);

					for (var i = 1; i < arguments.length; i++) {
						results[i - 1] = arguments[i];
					}

					resolve(results);
				} else {
					resolve(result);
				}
			});

			fn.apply(that, args);
		});
	};
};

var pify$1 = pify$2.exports = function (obj, P, opts) {
	if (typeof P !== 'function') {
		opts = P;
		P = Promise;
	}

	opts = opts || {};
	opts.exclude = opts.exclude || [/.+Sync$/];

	var filter = function (key) {
		var match = function (pattern) {
			return typeof pattern === 'string' ? key === pattern : pattern.test(key);
		};

		return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
	};

	var ret = typeof obj === 'function' ? function () {
		if (opts.excludeMain) {
			return obj.apply(this, arguments);
		}

		return processFn(obj, P, opts).apply(this, arguments);
	} : {};

	return Object.keys(obj).reduce(function (ret, key) {
		var x = obj[key];

		ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x;

		return ret;
	}, ret);
};

pify$1.all = pify$1;

var pifyExports = pify$2.exports;

var pinkie;
var hasRequiredPinkie;

function requirePinkie () {
	if (hasRequiredPinkie) return pinkie;
	hasRequiredPinkie = 1;

	var PENDING = 'pending';
	var SETTLED = 'settled';
	var FULFILLED = 'fulfilled';
	var REJECTED = 'rejected';
	var NOOP = function () {};
	var isNode = typeof index.commonjsGlobal !== 'undefined' && typeof index.commonjsGlobal.process !== 'undefined' && typeof index.commonjsGlobal.process.emit === 'function';

	var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate;
	var asyncQueue = [];
	var asyncTimer;

	function asyncFlush() {
		// run promise callbacks
		for (var i = 0; i < asyncQueue.length; i++) {
			asyncQueue[i][0](asyncQueue[i][1]);
		}

		// reset async asyncQueue
		asyncQueue = [];
		asyncTimer = false;
	}

	function asyncCall(callback, arg) {
		asyncQueue.push([callback, arg]);

		if (!asyncTimer) {
			asyncTimer = true;
			asyncSetTimer(asyncFlush, 0);
		}
	}

	function invokeResolver(resolver, promise) {
		function resolvePromise(value) {
			resolve(promise, value);
		}

		function rejectPromise(reason) {
			reject(promise, reason);
		}

		try {
			resolver(resolvePromise, rejectPromise);
		} catch (e) {
			rejectPromise(e);
		}
	}

	function invokeCallback(subscriber) {
		var owner = subscriber.owner;
		var settled = owner._state;
		var value = owner._data;
		var callback = subscriber[settled];
		var promise = subscriber.then;

		if (typeof callback === 'function') {
			settled = FULFILLED;
			try {
				value = callback(value);
			} catch (e) {
				reject(promise, e);
			}
		}

		if (!handleThenable(promise, value)) {
			if (settled === FULFILLED) {
				resolve(promise, value);
			}

			if (settled === REJECTED) {
				reject(promise, value);
			}
		}
	}

	function handleThenable(promise, value) {
		var resolved;

		try {
			if (promise === value) {
				throw new TypeError('A promises callback cannot return that same promise.');
			}

			if (value && (typeof value === 'function' || typeof value === 'object')) {
				// then should be retrieved only once
				var then = value.then;

				if (typeof then === 'function') {
					then.call(value, function (val) {
						if (!resolved) {
							resolved = true;

							if (value === val) {
								fulfill(promise, val);
							} else {
								resolve(promise, val);
							}
						}
					}, function (reason) {
						if (!resolved) {
							resolved = true;

							reject(promise, reason);
						}
					});

					return true;
				}
			}
		} catch (e) {
			if (!resolved) {
				reject(promise, e);
			}

			return true;
		}

		return false;
	}

	function resolve(promise, value) {
		if (promise === value || !handleThenable(promise, value)) {
			fulfill(promise, value);
		}
	}

	function fulfill(promise, value) {
		if (promise._state === PENDING) {
			promise._state = SETTLED;
			promise._data = value;

			asyncCall(publishFulfillment, promise);
		}
	}

	function reject(promise, reason) {
		if (promise._state === PENDING) {
			promise._state = SETTLED;
			promise._data = reason;

			asyncCall(publishRejection, promise);
		}
	}

	function publish(promise) {
		promise._then = promise._then.forEach(invokeCallback);
	}

	function publishFulfillment(promise) {
		promise._state = FULFILLED;
		publish(promise);
	}

	function publishRejection(promise) {
		promise._state = REJECTED;
		publish(promise);
		if (!promise._handled && isNode) {
			index.commonjsGlobal.process.emit('unhandledRejection', promise._data, promise);
		}
	}

	function notifyRejectionHandled(promise) {
		index.commonjsGlobal.process.emit('rejectionHandled', promise);
	}

	/**
	 * @class
	 */
	function Promise(resolver) {
		if (typeof resolver !== 'function') {
			throw new TypeError('Promise resolver ' + resolver + ' is not a function');
		}

		if (this instanceof Promise === false) {
			throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.');
		}

		this._then = [];

		invokeResolver(resolver, this);
	}

	Promise.prototype = {
		constructor: Promise,

		_state: PENDING,
		_then: null,
		_data: undefined,
		_handled: false,

		then: function (onFulfillment, onRejection) {
			var subscriber = {
				owner: this,
				then: new this.constructor(NOOP),
				fulfilled: onFulfillment,
				rejected: onRejection
			};

			if ((onRejection || onFulfillment) && !this._handled) {
				this._handled = true;
				if (this._state === REJECTED && isNode) {
					asyncCall(notifyRejectionHandled, this);
				}
			}

			if (this._state === FULFILLED || this._state === REJECTED) {
				// already resolved, call callback async
				asyncCall(invokeCallback, subscriber);
			} else {
				// subscribe
				this._then.push(subscriber);
			}

			return subscriber.then;
		},

		catch: function (onRejection) {
			return this.then(null, onRejection);
		}
	};

	Promise.all = function (promises) {
		if (!Array.isArray(promises)) {
			throw new TypeError('You must pass an array to Promise.all().');
		}

		return new Promise(function (resolve, reject) {
			var results = [];
			var remaining = 0;

			function resolver(index) {
				remaining++;
				return function (value) {
					results[index] = value;
					if (!--remaining) {
						resolve(results);
					}
				};
			}

			for (var i = 0, promise; i < promises.length; i++) {
				promise = promises[i];

				if (promise && typeof promise.then === 'function') {
					promise.then(resolver(i), reject);
				} else {
					results[i] = promise;
				}
			}

			if (!remaining) {
				resolve(results);
			}
		});
	};

	Promise.race = function (promises) {
		if (!Array.isArray(promises)) {
			throw new TypeError('You must pass an array to Promise.race().');
		}

		return new Promise(function (resolve, reject) {
			for (var i = 0, promise; i < promises.length; i++) {
				promise = promises[i];

				if (promise && typeof promise.then === 'function') {
					promise.then(resolve, reject);
				} else {
					resolve(promise);
				}
			}
		});
	};

	Promise.resolve = function (value) {
		if (value && typeof value === 'object' && value.constructor === Promise) {
			return value;
		}

		return new Promise(function (resolve) {
			resolve(value);
		});
	};

	Promise.reject = function (reason) {
		return new Promise(function (resolve, reject) {
			reject(reason);
		});
	};

	pinkie = Promise;
	return pinkie;
}

var pinkiePromise = typeof Promise === 'function' ? Promise : requirePinkie();

var df$1 = dfExports;
var pify = pifyExports;
var Promise$1 = pinkiePromise;

var mountPoint$1 = function (file) {
	return pify(df$1.file, Promise$1)(file).then(function (data) {
		return data.mountpoint;
	});
};

var os = require$$1;

function homedir() {
	var env = process.env;
	var home = env.HOME;
	var user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME;

	if (process.platform === 'win32') {
		return env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null;
	}

	if (process.platform === 'darwin') {
		return home || (user ? '/Users/' + user : null);
	}

	if (process.platform === 'linux') {
		return home || (process.getuid() === 0 ? '/root' : (user ? '/home/' + user : null));
	}

	return home || null;
}

var osHomedir = typeof os.homedir === 'function' ? os.homedir : homedir;

var userHome$1 = osHomedir();

var xdgBasedir$1 = {};

(function (exports) {
	const os = require$$1;
	const path = require$$0;

	const homeDirectory = os.homedir();
	const {env} = process;

	exports.data = env.XDG_DATA_HOME ||
		(homeDirectory ? path.join(homeDirectory, '.local', 'share') : undefined);

	exports.config = env.XDG_CONFIG_HOME ||
		(homeDirectory ? path.join(homeDirectory, '.config') : undefined);

	exports.cache = env.XDG_CACHE_HOME || (homeDirectory ? path.join(homeDirectory, '.cache') : undefined);

	exports.runtime = env.XDG_RUNTIME_DIR || undefined;

	exports.dataDirs = (env.XDG_DATA_DIRS || '/usr/local/share/:/usr/share/').split(':');

	if (exports.data) {
		exports.dataDirs.unshift(exports.data);
	}

	exports.configDirs = (env.XDG_CONFIG_DIRS || '/etc/xdg').split(':');

	if (exports.config) {
		exports.configDirs.unshift(exports.config);
	} 
} (xdgBasedir$1));

const fs = require$$0$1.promises;
const path = require$$0;
const df = dfExports$1;
const mountPoint = mountPoint$1;
const userHome = userHome$1;
const xdgBasedir = xdgBasedir$1;

const check = async filePath => {
	const topuid = `${filePath}-${process.getuid()}`;
	const stickyBitMode = 17407;

	try {
		const stats = await fs.lstat(filePath);

		if (stats.isSymbolicLink() || stats.mode !== stickyBitMode) {
			return topuid;
		}

		return path.join(filePath, String(process.getuid()));
	} catch (error) {
		if (error.code === 'ENOENT') {
			return topuid;
		}

		return path.join(xdgBasedir.data, 'Trash');
	}
};

xdgTrashdir$1.exports = async filePath => {
	if (process.platform !== 'linux') {
		return Promise.reject(new Error('Only Linux systems are supported'));
	}

	if (!filePath) {
		return Promise.resolve(path.join(xdgBasedir.data, 'Trash'));
	}

	const [homeMountPoint, fileMountPoint] = await Promise.all([
		mountPoint(userHome),
		// Ignore errors in case `file` is a dangling symlink
		mountPoint(filePath).catch(() => {})
	]);

	if (!fileMountPoint || fileMountPoint === homeMountPoint) {
		return path.join(xdgBasedir.data, 'Trash');
	}

	return check(path.join(fileMountPoint, '.Trash'));
};

xdgTrashdir$1.exports.all = async () => {
	if (process.platform !== 'linux') {
		return Promise.reject(new Error('Only Linux systems are supported'));
	}

	return Promise.all((await df()).map(fileSystem => {
		if (fileSystem.mountpoint === '/') {
			return path.join(xdgBasedir.data, 'Trash');
		}

		return check(path.join(fileSystem.mountpoint, '.Trash'));
	}));
};

var xdgTrashdirExports = xdgTrashdir$1.exports;
var xdgTrashdir = /*@__PURE__*/index.getDefaultExportFromCjs(xdgTrashdirExports);

async function pMap(
	iterable,
	mapper,
	{
		concurrency = Number.POSITIVE_INFINITY,
		stopOnError = true,
		signal,
	} = {},
) {
	return new Promise((resolve, reject_) => {
		if (iterable[Symbol.iterator] === undefined && iterable[Symbol.asyncIterator] === undefined) {
			throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
		}

		if (typeof mapper !== 'function') {
			throw new TypeError('Mapper function is required');
		}

		if (!((Number.isSafeInteger(concurrency) && concurrency >= 1) || concurrency === Number.POSITIVE_INFINITY)) {
			throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
		}

		const result = [];
		const errors = [];
		const skippedIndexesMap = new Map();
		let isRejected = false;
		let isResolved = false;
		let isIterableDone = false;
		let resolvingCount = 0;
		let currentIndex = 0;
		const iterator = iterable[Symbol.iterator] === undefined ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();

		const reject = reason => {
			isRejected = true;
			isResolved = true;
			reject_(reason);
		};

		if (signal) {
			if (signal.aborted) {
				reject(signal.reason);
			}

			signal.addEventListener('abort', () => {
				reject(signal.reason);
			});
		}

		const next = async () => {
			if (isResolved) {
				return;
			}

			const nextItem = await iterator.next();

			const index = currentIndex;
			currentIndex++;

			// Note: `iterator.next()` can be called many times in parallel.
			// This can cause multiple calls to this `next()` function to
			// receive a `nextItem` with `done === true`.
			// The shutdown logic that rejects/resolves must be protected
			// so it runs only one time as the `skippedIndex` logic is
			// non-idempotent.
			if (nextItem.done) {
				isIterableDone = true;

				if (resolvingCount === 0 && !isResolved) {
					if (!stopOnError && errors.length > 0) {
						reject(new AggregateError(errors)); // eslint-disable-line unicorn/error-message
						return;
					}

					isResolved = true;

					if (skippedIndexesMap.size === 0) {
						resolve(result);
						return;
					}

					const pureResult = [];

					// Support multiple `pMapSkip`'s.
					for (const [index, value] of result.entries()) {
						if (skippedIndexesMap.get(index) === pMapSkip) {
							continue;
						}

						pureResult.push(value);
					}

					resolve(pureResult);
				}

				return;
			}

			resolvingCount++;

			// Intentionally detached
			(async () => {
				try {
					const element = await nextItem.value;

					if (isResolved) {
						return;
					}

					const value = await mapper(element, index);

					// Use Map to stage the index of the element.
					if (value === pMapSkip) {
						skippedIndexesMap.set(index, value);
					}

					result[index] = value;

					resolvingCount--;
					await next();
				} catch (error) {
					if (stopOnError) {
						reject(error);
					} else {
						errors.push(error);
						resolvingCount--;

						// In that case we can't really continue regardless of `stopOnError` state
						// since an iterable is likely to continue throwing after it throws once.
						// If we continue calling `next()` indefinitely we will likely end up
						// in an infinite loop of failed iteration.
						try {
							await next();
						} catch (error) {
							reject(error);
						}
					}
				}
			})();
		};

		// Create the concurrent runners in a detached (non-awaited)
		// promise. We need this so we can await the `next()` calls
		// to stop creating runners before hitting the concurrency limit
		// if the iterable has already been marked as done.
		// NOTE: We *must* do this for async iterators otherwise we'll spin up
		// infinite `next()` calls by default and never start the event loop.
		(async () => {
			for (let index = 0; index < concurrency; index++) {
				try {
					// eslint-disable-next-line no-await-in-loop
					await next();
				} catch (error) {
					reject(error);
					break;
				}

				if (isIterableDone || isRejected) {
					break;
				}
			}
		})();
	});
}

const pMapSkip = Symbol('skip');

async function pathExists(path) {
	try {
		await fs$3.promises.access(path);
		return true;
	} catch {
		return false;
	}
}

const resolvePath = (cwd, sourcePath, destinationPath) => {
	sourcePath = path$5.resolve(cwd, sourcePath);
	destinationPath = path$5.resolve(cwd, destinationPath);

	return {
		sourcePath,
		destinationPath,
	};
};

const validatePathsExist = (sourcePath, destinationPath, suffix = 'Path') => {
	if (!sourcePath || !destinationPath) {
		throw new TypeError(`\`source${suffix}\` and \`destination${suffix}\` required`);
	}
};

const validateSameDirectory = (source, destination) => {
	if (path$5.dirname(source) !== path$5.dirname(destination)) {
		throw new Error('`source` and `destination` must be in the same directory');
	}
};

const _moveFile = async (sourcePath, destinationPath, {overwrite = true, cwd = process$2.cwd(), directoryMode, validateDirectory = false} = {}) => {
	if (cwd) {
		({sourcePath, destinationPath} = resolvePath(cwd, sourcePath, destinationPath));
	}

	if (validateDirectory) {
		validateSameDirectory(sourcePath, destinationPath);
	}

	if (!overwrite && await pathExists(destinationPath)) {
		throw new Error(`The destination file exists: ${destinationPath}`);
	}

	await fs$3.promises.mkdir(path$5.dirname(destinationPath), {
		recursive: true,
		mode: directoryMode,
	});

	try {
		await fs$3.promises.rename(sourcePath, destinationPath);
	} catch (error) {
		if (error.code === 'EXDEV') {
			await fs$3.promises.copyFile(sourcePath, destinationPath);
			await fs$3.promises.unlink(sourcePath);
		} else {
			throw error;
		}
	}
};

async function moveFile(sourcePath, destinationPath, options) {
	validatePathsExist(sourcePath, destinationPath);
	return _moveFile(sourcePath, destinationPath, options);
}

let ProcfsError$1 = class ProcfsError extends Error {
	constructor(code, message, sourceError) {
		super(message);
		this.name = 'ProcfsError';
		this.code = code;
		if (sourceError !== undefined) {
			this.sourceError = sourceError;
		}
	}
};

ProcfsError$1.ERR_PARSING_FAILED = 'EPARSE';
ProcfsError$1.ERR_UNKNOWN = 'EUNKNOWN';
ProcfsError$1.ERR_NOT_FOUND = 'ENOENT';

ProcfsError$1.parsingError = (src, msg) => {
	let e = new ProcfsError$1(ProcfsError$1.ERR_PARSING_FAILED, `Parsing failed: ${msg}`);
	e.sourceText = src;
	return e;
};

ProcfsError$1.generic = err => {
	/* istanbul ignore next should not ever happen */
	if (err instanceof ProcfsError$1) {
		return err;
	}

	switch (err.code) {
		case 'ENOENT':
			return new ProcfsError$1(ProcfsError$1.ERR_NOT_FOUND, 'File not found', err);
		/* istanbul ignore next should not ever happen*/
		default:
			return new ProcfsError$1(ProcfsError$1.ERR_UNKNOWN, `Unknown error: ${err.message}`, err);
	}
};

var procfsError = ProcfsError$1;

const trim = str => str.trim();

class Parsers {}

const parsers$1 = new Parsers();

for (let name of [
	'cgroups',
	'config',
	'cpuinfo',
	'devices',
	'diskstats',
	'filesystems',
	'loadavg',
	'meminfo',
	'partitions',
	'processAutogroup',
	'processCgroups',
	'processCmdline',
	'processEnviron',
	'processes',
	'processExe',
	'processFd',
	'processFdinfo',
	'processFds',
	'processGidMap',
	'processIo',
	'processLimits',
	'processMountinfo',
	'processNetDev',
	'processNetTcp4',
	'processNetTcp6',
	'processNetUdp4',
	'processNetUdp6',
	'processNetUnix',
	'processNetWireless',
	'processStat',
	'processStatm',
	'processStatus',
	'processThreads',
	'processUidMap',
	'stat',
	'swaps',
	'uptime',
]) {
	Object.defineProperty(Parsers.prototype, name, {
		get: function () { // eslint-disable-line object-shorthand
			let value = index.commonjsRequire(`./parsers/${name}`);
			Object.defineProperty(this, name, {value});
			return value;
		},
	});
}

parsers$1.cmdline = trim;
parsers$1.processComm = trim;
parsers$1.processCpuset = trim;
parsers$1.processOomScore = src => parseInt(src);
parsers$1.processTimerslackNs = src => parseInt(src);
parsers$1.version = trim;
parsers$1.processCwd = src => src;
parsers$1.processPersonality = src => parseInt(src, 16);

var parsers_1 = parsers$1;

const {
	readlinkSync,
	readdirSync,
	openSync,
	readSync,
	closeSync,
	readFileSync,
	existsSync,
} = require$$0$1;

const tmpBufMinLen = 4096 * 2;
const tmpBufMaxLen = 4096 * 8;

let tmpBuf = Buffer.allocUnsafeSlow(tmpBufMinLen);

const read$1 = path => {
	const fd = openSync(path, 'r', 0o666);
	let pos = 0;
	let bytesRead;
	let buf = tmpBuf;
	let length = buf.length;
	do {
		bytesRead = readSync(fd, buf, pos, buf.length - pos, null);
		pos += bytesRead;
		if (pos === tmpBuf.length) {
			length = length << 1;
			let newBuf = Buffer.allocUnsafeSlow(length);

			if (length <= tmpBufMaxLen) {
				tmpBuf = newBuf;
			}

			buf.copy(newBuf);
			buf = newBuf;
		}
	} while (bytesRead !== 0);
	closeSync(fd);
	return buf.toString('utf8', 0, pos);
};

const readIdList = path => {
	let ls = readdirSync(path);
	for (let i = 0; i < ls.length; i++) {
		ls[i] = parseInt(ls[i]);
	}
	return ls;
};

const readBuffer$1 = readFileSync;
const exists = existsSync;
const readdir$1 = readdirSync;

const devIdGetMinor$1 = devId => (((devId >> 20) << 8) | (devId & 0xFF));
const devIdGetMajor$1 = devId => ((devId >> 8) & 0xFF);
const devIdFromMajorMinor$1 = (major, minor) => (((minor >> 8) << 20) | ((major & 0xFF) << 8) | (minor & 0xFF));

var utils = {
	read: read$1,
	readLink: readlinkSync,
	readIdList,
	readBuffer: readBuffer$1,
	exists,
	readdir: readdir$1,

	devIdGetMinor: devIdGetMinor$1,
	devIdGetMajor: devIdGetMajor$1,
	devIdFromMajorMinor: devIdFromMajorMinor$1,
};

const ProcfsError = procfsError;
const parsers = parsers_1;
const {
	read,
	readLink,
	readBuffer,
	readdir,
	devIdGetMinor,
	devIdGetMajor,
	devIdFromMajorMinor,
} = utils;

class Procfs {
	constructor(root) {
		if (root === undefined) {
			root = '/proc';
		}
		this.root = root;
		this.rootSlash = `${root}/`;
	}

	processes() {
		try {
			return parsers.processes(readdir(this.root));
		} catch (error) {
			/* istanbul ignore next should not ever happen when procfs exists */
			throw ProcfsError.generic(error);
		}
	}

	processFds(pid) {
		if (pid !== undefined && (!Number.isInteger(pid) || pid <= 0)) {
			throw new TypeError('pid');
		}
		try {
			return parsers.processFds(readdir(`${this.rootSlash}${pid === undefined ? 'self' : pid}/fd`));
		} catch (error) {
			throw ProcfsError.generic(error);
		}
	}

	processThreads(pid) {
		if (pid !== undefined && (!Number.isInteger(pid) || pid <= 0)) {
			throw new TypeError('pid');
		}
		try {
			return parsers.processThreads(readdir(`${this.rootSlash}${pid === undefined ? 'self' : pid}/task`));
		} catch (error) {
			throw ProcfsError.generic(error);
		}
	}

	processFdinfo(fd, pid) {
		if (pid !== undefined && !(Number.isInteger(pid) && pid >= 0)) {
			throw new TypeError('pid');
		}
		if (!Number.isInteger(fd) || fd <= 0) {
			throw new TypeError('fd');
		}
		try {
			return parsers.processFdinfo(read(`${this.rootSlash}${pid === undefined ? 'self' : pid}/fdinfo/${fd}`));
		} catch (error) {
			throw ProcfsError.generic(error);
		}
	}

	processFd(fd, pid) {
		if (pid !== undefined && !(Number.isInteger(pid) && pid >= 0)) {
			throw new TypeError('pid');
		}
		if (!Number.isInteger(fd) || fd <= 0) {
			throw new TypeError('fd');
		}
		try {
			return parsers.processFd(readLink(`${this.rootSlash}${pid === undefined ? 'self' : pid}/fd/${fd}`));
		} catch (error) {
			throw ProcfsError.generic(error);
		}
	}

	config() {
		try {
			return parsers.config(readBuffer(`${this.rootSlash}config.gz`));
		} catch (error) {
			/* istanbul ignore next should not ever happen when procfs exists and kernel properly configured */
			throw ProcfsError.generic(error);
		}
	}
}

Procfs.prototype.devIdGetMinor = devIdGetMinor;
Procfs.prototype.devIdGetMajor = devIdGetMajor;
Procfs.prototype.devIdFromMajorMinor = devIdFromMajorMinor;

for (let [name, path] of [
	['processExe', '/exe'],
	['processCwd', '/cwd'],
]) {
	Procfs.prototype[name] = function (pid) {
		if (pid !== undefined && !(Number.isInteger(pid) && pid >= 0)) {
			throw new TypeError('pid');
		}
		try {
			return parsers[name](readLink(`${this.rootSlash}${pid === undefined ? 'self' : pid}${path}`));
		} catch (error) {
			throw ProcfsError.generic(error);
		}
	};
}

for (let [name, path] of [
	['processMountinfo', '/mountinfo'],
	['processIo', '/io'],
	['processUidMap', '/uid_map'],
	['processGidMap', '/gid_map'],
	['processEnviron', '/environ'],
	['processOomScore', '/oom_score'],
	['processTimerslackNs', '/timerslack_ns'],
	['processCmdline', '/cmdline'],
	['processAutogroup', '/autogroup'],
	['processStatm', '/statm'],
	['processComm', '/comm'],
	['processPersonality', '/personality'],
	['processCgroups', '/cgroup'],
	['processCpuset', '/cpuset'],
	['processLimits', '/limits'],
	['processStat', '/stat'],
	['processStatus', '/status'],
	['processNetDev', '/net/dev'],
	['processNetWireless', '/net/wireless'],
	['processNetUnix', '/net/unix'],
	['processNetTcp4', '/net/tcp'],
	['processNetTcp6', '/net/tcp6'],
	['processNetUdp4', '/net/udp'],
	['processNetUdp6', '/net/udp6'],
]) {
	Procfs.prototype[name] = function (pid) {
		if (pid !== undefined && !(Number.isInteger(pid) && pid >= 0)) {
			throw new TypeError('pid');
		}
		try {
			return parsers[name](read(`${this.rootSlash}${pid === undefined ? 'self' : pid}${path}`));
		} catch (error) {
			throw ProcfsError.generic(error);
		}
	};
}

for (let name of [
	'cpuinfo',
	'loadavg',
	'uptime',
	'version',
	'cmdline',
	'swaps',
	'stat',
	'devices',
	'filesystems',
	'diskstats',
	'partitions',
	'meminfo',
	'cgroups',
]) {
	Procfs.prototype[name] = function () {
		try {
			return parsers[name](read(this.rootSlash + name));
		} catch (error) {
			/* istanbul ignore next should not ever happen when procfs exists */
			throw ProcfsError.generic(error);
		}
	};
}

for (let [name, parser, path] of [
	['netDev', 'processNetDev', 'net/dev'],
	['netWireless', 'processNetWireless', 'net/wireless'],
	['netUnix', 'processNetUnix', 'net/unix'],
	['netTcp4', 'processNetTcp4', 'net/tcp'],
	['netTcp6', 'processNetTcp6', 'net/tcp6'],
	['netUdp4', 'processNetUdp4', 'net/udp'],
	['netUdp6', 'processNetUdp6', 'net/udp6'],
]) {
	Procfs.prototype[name] = function () {
		try {
			return parsers[parser](read(this.rootSlash + path));
		} catch (error) {
			/* istanbul ignore next should not ever happen when procfs exists */
			throw ProcfsError.generic(error);
		}
	};
}

const procfs = new Procfs();
var procfs_1 = {
	procfs,
	Procfs,
	ProcfsError,
};

// Educated guess, values of 16 to 64 seem to be optimal for modern SSD, 8-16 and 64-128 can be a bit slower.
// We should be ok as long as ssdCount <= cpuCount <= ssdCount*16.
// For slower media this is not as important and we rely on OS handling it for us.
const concurrency = os$3.cpus().length * 8;

const pad = number => number < 10 ? '0' + number : number;

const getDeletionDate = date => date.getFullYear()
	+ '-' + pad(date.getMonth() + 1)
	+ '-' + pad(date.getDate())
	+ 'T' + pad(date.getHours())
	+ ':' + pad(date.getMinutes())
	+ ':' + pad(date.getSeconds());

const trash = async (filePath, trashPaths) => {
	const name = crypto.randomUUID();
	const destination = path$5.join(trashPaths.filesPath, name);
	const trashInfoPath = path$5.join(trashPaths.infoPath, `${name}.trashinfo`);

	const trashInfoData = `[Trash Info]\nPath=${filePath.replaceAll(/\s/g, '%20')}\nDeletionDate=${getDeletionDate(new Date())}`;

	await fs$3.promises.writeFile(trashInfoPath, trashInfoData);
	await moveFile(filePath, destination);

	return {
		path: destination,
		info: trashInfoPath,
	};
};

async function linux(paths) {
	const mountPointMap = new Map();

	for (const mountInfo of Object.values(procfs_1.procfs.processMountinfo())) {
		// Filter out irrelevant drives (that start with `/snap`, `/run`, etc).
		if (/^\/(snap|var\/snap|run|sys|proc|dev)($|\/)/.test(mountInfo.mountPoint)) {
			continue;
		}

		// Keep the first one if there are multiple `devId`.
		if (!mountPointMap.has(mountInfo.devId)) {
			mountPointMap.set(mountInfo.devId, mountInfo.mountPoint);
		}
	}

	const trashPathsCache = new Map();

	const getDeviceTrashPaths = async developmentId => {
		let trashPathsPromise = trashPathsCache.get(developmentId);
		if (trashPathsPromise === undefined) {
			trashPathsPromise = (async () => {
				const trashPath = await xdgTrashdir(mountPointMap.get(developmentId));
				const paths = {
					filesPath: path$5.join(trashPath, 'files'),
					infoPath: path$5.join(trashPath, 'info'),
				};
				await fs$3.promises.mkdir(paths.filesPath, {mode: 0o700, recursive: true});
				await fs$3.promises.mkdir(paths.infoPath, {mode: 0o700, recursive: true});
				return paths;
			})();
			trashPathsCache.set(developmentId, trashPathsPromise);
		}

		return trashPathsPromise;
	};

	return pMap(paths, async filePath => {
		const stats = await fs$3.promises.lstat(filePath);
		const trashPaths = await getDeviceTrashPaths(stats.dev);
		return trash(filePath, trashPaths);
	}, {concurrency});
}

exports.default = linux;
