var __node_require__ = require, __node_module__ = module;
/******/ (() => { // webpackBootstrap
/******/ 	var __webpack_modules__ = ({

/***/ 5:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.AliasFS = void 0;
const ProxiedFS_1 = __webpack_require__(105);
class AliasFS extends ProxiedFS_1.ProxiedFS {
    constructor(target, { baseFs, pathUtils }) {
        super(pathUtils);
        this.target = target;
        this.baseFs = baseFs;
    }
    getRealPath() {
        return this.target;
    }
    getBaseFs() {
        return this.baseFs;
    }
    mapFromBase(p) {
        return p;
    }
    mapToBase(p) {
        return p;
    }
}
exports.AliasFS = AliasFS;


/***/ }),

/***/ 472:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CwdFS = void 0;
const NodeFS_1 = __webpack_require__(843);
const ProxiedFS_1 = __webpack_require__(105);
const path_1 = __webpack_require__(905);
class CwdFS extends ProxiedFS_1.ProxiedFS {
    constructor(target, { baseFs = new NodeFS_1.NodeFS() } = {}) {
        super(path_1.ppath);
        this.target = this.pathUtils.normalize(target);
        this.baseFs = baseFs;
    }
    getRealPath() {
        return this.pathUtils.resolve(this.baseFs.getRealPath(), this.target);
    }
    resolve(p) {
        if (this.pathUtils.isAbsolute(p)) {
            return path_1.ppath.normalize(p);
        }
        else {
            return this.baseFs.resolve(path_1.ppath.join(this.target, p));
        }
    }
    mapFromBase(path) {
        return path;
    }
    mapToBase(path) {
        if (this.pathUtils.isAbsolute(path)) {
            return path;
        }
        else {
            return this.pathUtils.join(this.target, path);
        }
    }
}
exports.CwdFS = CwdFS;


/***/ }),

/***/ 498:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.normalizeLineEndings = exports.BasePortableFakeFS = exports.FakeFS = void 0;
const crypto_1 = __webpack_require__(113);
const os_1 = __webpack_require__(37);
const copyPromise_1 = __webpack_require__(142);
const path_1 = __webpack_require__(905);
class FakeFS {
    constructor(pathUtils) {
        this.pathUtils = pathUtils;
    }
    async *genTraversePromise(init, { stableSort = false } = {}) {
        const stack = [init];
        while (stack.length > 0) {
            const p = stack.shift();
            const entry = await this.lstatPromise(p);
            if (entry.isDirectory()) {
                const entries = await this.readdirPromise(p);
                if (stableSort) {
                    for (const entry of entries.sort()) {
                        stack.push(this.pathUtils.join(p, entry));
                    }
                }
                else {
                    throw new Error(`Not supported`);
                }
            }
            else {
                yield p;
            }
        }
    }
    async checksumFilePromise(path, { algorithm = `sha512` } = {}) {
        const fd = await this.openPromise(path, `r`);
        try {
            const CHUNK_SIZE = 65536;
            const chunk = Buffer.allocUnsafeSlow(CHUNK_SIZE);
            const hash = (0, crypto_1.createHash)(algorithm);
            let bytesRead = 0;
            while ((bytesRead = await this.readPromise(fd, chunk, 0, CHUNK_SIZE)) !== 0)
                hash.update(bytesRead === CHUNK_SIZE ? chunk : chunk.slice(0, bytesRead));
            return hash.digest(`hex`);
        }
        finally {
            await this.closePromise(fd);
        }
    }
    async removePromise(p, { recursive = true, maxRetries = 5 } = {}) {
        let stat;
        try {
            stat = await this.lstatPromise(p);
        }
        catch (error) {
            if (error.code === `ENOENT`) {
                return;
            }
            else {
                throw error;
            }
        }
        if (stat.isDirectory()) {
            if (recursive) {
                const entries = await this.readdirPromise(p);
                await Promise.all(entries.map(entry => {
                    return this.removePromise(this.pathUtils.resolve(p, entry));
                }));
            }
            // 5 gives 1s worth of retries at worst
            for (let t = 0; t <= maxRetries; t++) {
                try {
                    await this.rmdirPromise(p);
                    break;
                }
                catch (error) {
                    if (error.code !== `EBUSY` && error.code !== `ENOTEMPTY`) {
                        throw error;
                    }
                    else if (t < maxRetries) {
                        await new Promise(resolve => setTimeout(resolve, t * 100));
                    }
                }
            }
        }
        else {
            await this.unlinkPromise(p);
        }
    }
    removeSync(p, { recursive = true } = {}) {
        let stat;
        try {
            stat = this.lstatSync(p);
        }
        catch (error) {
            if (error.code === `ENOENT`) {
                return;
            }
            else {
                throw error;
            }
        }
        if (stat.isDirectory()) {
            if (recursive)
                for (const entry of this.readdirSync(p))
                    this.removeSync(this.pathUtils.resolve(p, entry));
            this.rmdirSync(p);
        }
        else {
            this.unlinkSync(p);
        }
    }
    async mkdirpPromise(p, { chmod, utimes } = {}) {
        p = this.resolve(p);
        if (p === this.pathUtils.dirname(p))
            return undefined;
        const parts = p.split(this.pathUtils.sep);
        let createdDirectory;
        for (let u = 2; u <= parts.length; ++u) {
            const subPath = parts.slice(0, u).join(this.pathUtils.sep);
            if (!this.existsSync(subPath)) {
                try {
                    await this.mkdirPromise(subPath);
                }
                catch (error) {
                    if (error.code === `EEXIST`) {
                        continue;
                    }
                    else {
                        throw error;
                    }
                }
                createdDirectory !== null && createdDirectory !== void 0 ? createdDirectory : (createdDirectory = subPath);
                if (chmod != null)
                    await this.chmodPromise(subPath, chmod);
                if (utimes != null) {
                    await this.utimesPromise(subPath, utimes[0], utimes[1]);
                }
                else {
                    const parentStat = await this.statPromise(this.pathUtils.dirname(subPath));
                    await this.utimesPromise(subPath, parentStat.atime, parentStat.mtime);
                }
            }
        }
        return createdDirectory;
    }
    mkdirpSync(p, { chmod, utimes } = {}) {
        p = this.resolve(p);
        if (p === this.pathUtils.dirname(p))
            return undefined;
        const parts = p.split(this.pathUtils.sep);
        let createdDirectory;
        for (let u = 2; u <= parts.length; ++u) {
            const subPath = parts.slice(0, u).join(this.pathUtils.sep);
            if (!this.existsSync(subPath)) {
                try {
                    this.mkdirSync(subPath);
                }
                catch (error) {
                    if (error.code === `EEXIST`) {
                        continue;
                    }
                    else {
                        throw error;
                    }
                }
                createdDirectory !== null && createdDirectory !== void 0 ? createdDirectory : (createdDirectory = subPath);
                if (chmod != null)
                    this.chmodSync(subPath, chmod);
                if (utimes != null) {
                    this.utimesSync(subPath, utimes[0], utimes[1]);
                }
                else {
                    const parentStat = this.statSync(this.pathUtils.dirname(subPath));
                    this.utimesSync(subPath, parentStat.atime, parentStat.mtime);
                }
            }
        }
        return createdDirectory;
    }
    async copyPromise(destination, source, { baseFs = this, overwrite = true, stableSort = false, stableTime = false, linkStrategy = null } = {}) {
        return await (0, copyPromise_1.copyPromise)(this, destination, baseFs, source, { overwrite, stableSort, stableTime, linkStrategy });
    }
    copySync(destination, source, { baseFs = this, overwrite = true } = {}) {
        const stat = baseFs.lstatSync(source);
        const exists = this.existsSync(destination);
        if (stat.isDirectory()) {
            this.mkdirpSync(destination);
            const directoryListing = baseFs.readdirSync(source);
            for (const entry of directoryListing) {
                this.copySync(this.pathUtils.join(destination, entry), baseFs.pathUtils.join(source, entry), { baseFs, overwrite });
            }
        }
        else if (stat.isFile()) {
            if (!exists || overwrite) {
                if (exists)
                    this.removeSync(destination);
                const content = baseFs.readFileSync(source);
                this.writeFileSync(destination, content);
            }
        }
        else if (stat.isSymbolicLink()) {
            if (!exists || overwrite) {
                if (exists)
                    this.removeSync(destination);
                const target = baseFs.readlinkSync(source);
                this.symlinkSync((0, path_1.convertPath)(this.pathUtils, target), destination);
            }
        }
        else {
            throw new Error(`Unsupported file type (file: ${source}, mode: 0o${stat.mode.toString(8).padStart(6, `0`)})`);
        }
        const mode = stat.mode & 0o777;
        this.chmodSync(destination, mode);
    }
    async changeFilePromise(p, content, opts = {}) {
        if (Buffer.isBuffer(content)) {
            return this.changeFileBufferPromise(p, content, opts);
        }
        else {
            return this.changeFileTextPromise(p, content, opts);
        }
    }
    async changeFileBufferPromise(p, content, { mode } = {}) {
        let current = Buffer.alloc(0);
        try {
            current = await this.readFilePromise(p);
        }
        catch (error) {
            // ignore errors, no big deal
        }
        if (Buffer.compare(current, content) === 0)
            return;
        await this.writeFilePromise(p, content, { mode });
    }
    async changeFileTextPromise(p, content, { automaticNewlines, mode } = {}) {
        let current = ``;
        try {
            current = await this.readFilePromise(p, `utf8`);
        }
        catch (error) {
            // ignore errors, no big deal
        }
        const normalizedContent = automaticNewlines
            ? normalizeLineEndings(current, content)
            : content;
        if (current === normalizedContent)
            return;
        await this.writeFilePromise(p, normalizedContent, { mode });
    }
    changeFileSync(p, content, opts = {}) {
        if (Buffer.isBuffer(content)) {
            return this.changeFileBufferSync(p, content, opts);
        }
        else {
            return this.changeFileTextSync(p, content, opts);
        }
    }
    changeFileBufferSync(p, content, { mode } = {}) {
        let current = Buffer.alloc(0);
        try {
            current = this.readFileSync(p);
        }
        catch (error) {
            // ignore errors, no big deal
        }
        if (Buffer.compare(current, content) === 0)
            return;
        this.writeFileSync(p, content, { mode });
    }
    changeFileTextSync(p, content, { automaticNewlines = false, mode } = {}) {
        let current = ``;
        try {
            current = this.readFileSync(p, `utf8`);
        }
        catch (error) {
            // ignore errors, no big deal
        }
        const normalizedContent = automaticNewlines
            ? normalizeLineEndings(current, content)
            : content;
        if (current === normalizedContent)
            return;
        this.writeFileSync(p, normalizedContent, { mode });
    }
    async movePromise(fromP, toP) {
        try {
            await this.renamePromise(fromP, toP);
        }
        catch (error) {
            if (error.code === `EXDEV`) {
                await this.copyPromise(toP, fromP);
                await this.removePromise(fromP);
            }
            else {
                throw error;
            }
        }
    }
    moveSync(fromP, toP) {
        try {
            this.renameSync(fromP, toP);
        }
        catch (error) {
            if (error.code === `EXDEV`) {
                this.copySync(toP, fromP);
                this.removeSync(fromP);
            }
            else {
                throw error;
            }
        }
    }
    async lockPromise(affectedPath, callback) {
        const lockPath = `${affectedPath}.flock`;
        const interval = 1000 / 60;
        const startTime = Date.now();
        let fd = null;
        // Even when we detect that a lock file exists, we still look inside to see
        // whether the pid that created it is still alive. It's not foolproof
        // (there are false positive), but there are no false negative and that's
        // all that matters in 99% of the cases.
        const isAlive = async () => {
            let pid;
            try {
                ([pid] = await this.readJsonPromise(lockPath));
            }
            catch (error) {
                // If we can't read the file repeatedly, we assume the process was
                // aborted before even writing finishing writing the payload.
                return Date.now() - startTime < 500;
            }
            try {
                // "As a special case, a signal of 0 can be used to test for the
                // existence of a process" - so we check whether it's alive.
                process.kill(pid, 0);
                return true;
            }
            catch (error) {
                return false;
            }
        };
        while (fd === null) {
            try {
                fd = await this.openPromise(lockPath, `wx`);
            }
            catch (error) {
                if (error.code === `EEXIST`) {
                    if (!await isAlive()) {
                        try {
                            await this.unlinkPromise(lockPath);
                            continue;
                        }
                        catch (error) {
                            // No big deal if we can't remove it. Just fallback to wait for
                            // it to be eventually released by its owner.
                        }
                    }
                    if (Date.now() - startTime < 60 * 1000) {
                        await new Promise(resolve => setTimeout(resolve, interval));
                    }
                    else {
                        throw new Error(`Couldn't acquire a lock in a reasonable time (via ${lockPath})`);
                    }
                }
                else {
                    throw error;
                }
            }
        }
        await this.writePromise(fd, JSON.stringify([process.pid]));
        try {
            return await callback();
        }
        finally {
            try {
                // closePromise needs to come before unlinkPromise otherwise another process can attempt
                // to get the file handle after the unlink but before close resuling in
                // EPERM: operation not permitted, open
                await this.closePromise(fd);
                await this.unlinkPromise(lockPath);
            }
            catch (error) {
                // noop
            }
        }
    }
    async readJsonPromise(p) {
        const content = await this.readFilePromise(p, `utf8`);
        try {
            return JSON.parse(content);
        }
        catch (error) {
            error.message += ` (in ${p})`;
            throw error;
        }
    }
    readJsonSync(p) {
        const content = this.readFileSync(p, `utf8`);
        try {
            return JSON.parse(content);
        }
        catch (error) {
            error.message += ` (in ${p})`;
            throw error;
        }
    }
    async writeJsonPromise(p, data) {
        return await this.writeFilePromise(p, `${JSON.stringify(data, null, 2)}\n`);
    }
    writeJsonSync(p, data) {
        return this.writeFileSync(p, `${JSON.stringify(data, null, 2)}\n`);
    }
    async preserveTimePromise(p, cb) {
        const stat = await this.lstatPromise(p);
        const result = await cb();
        if (typeof result !== `undefined`)
            p = result;
        await this.lutimesPromise(p, stat.atime, stat.mtime);
    }
    async preserveTimeSync(p, cb) {
        const stat = this.lstatSync(p);
        const result = cb();
        if (typeof result !== `undefined`)
            p = result;
        this.lutimesSync(p, stat.atime, stat.mtime);
    }
}
exports.FakeFS = FakeFS;
class BasePortableFakeFS extends FakeFS {
    constructor() {
        super(path_1.ppath);
    }
}
exports.BasePortableFakeFS = BasePortableFakeFS;
function getEndOfLine(content) {
    const matches = content.match(/\r?\n/g);
    if (matches === null)
        return os_1.EOL;
    const crlf = matches.filter(nl => nl === `\r\n`).length;
    const lf = matches.length - crlf;
    return crlf > lf ? `\r\n` : `\n`;
}
function normalizeLineEndings(originalContent, newContent) {
    return newContent.replace(/\r?\n/g, getEndOfLine(originalContent));
}
exports.normalizeLineEndings = normalizeLineEndings;


/***/ }),

/***/ 238:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.JailFS = void 0;
const NodeFS_1 = __webpack_require__(843);
const ProxiedFS_1 = __webpack_require__(105);
const path_1 = __webpack_require__(905);
const JAIL_ROOT = path_1.PortablePath.root;
class JailFS extends ProxiedFS_1.ProxiedFS {
    constructor(target, { baseFs = new NodeFS_1.NodeFS() } = {}) {
        super(path_1.ppath);
        this.target = this.pathUtils.resolve(path_1.PortablePath.root, target);
        this.baseFs = baseFs;
    }
    getRealPath() {
        return this.pathUtils.resolve(this.baseFs.getRealPath(), this.pathUtils.relative(path_1.PortablePath.root, this.target));
    }
    getTarget() {
        return this.target;
    }
    getBaseFs() {
        return this.baseFs;
    }
    mapToBase(p) {
        const normalized = this.pathUtils.normalize(p);
        if (this.pathUtils.isAbsolute(p))
            return this.pathUtils.resolve(this.target, this.pathUtils.relative(JAIL_ROOT, p));
        if (normalized.match(/^\.\.\/?/))
            throw new Error(`Resolving this path (${p}) would escape the jail`);
        return this.pathUtils.resolve(this.target, p);
    }
    mapFromBase(p) {
        return this.pathUtils.resolve(JAIL_ROOT, this.pathUtils.relative(this.target, p));
    }
}
exports.JailFS = JailFS;


/***/ }),

/***/ 130:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.LazyFS = void 0;
const ProxiedFS_1 = __webpack_require__(105);
class LazyFS extends ProxiedFS_1.ProxiedFS {
    constructor(factory, pathUtils) {
        super(pathUtils);
        this.instance = null;
        this.factory = factory;
    }
    get baseFs() {
        if (!this.instance)
            this.instance = this.factory();
        return this.instance;
    }
    set baseFs(value) {
        this.instance = value;
    }
    mapFromBase(p) {
        return p;
    }
    mapToBase(p) {
        return p;
    }
}
exports.LazyFS = LazyFS;


/***/ }),

/***/ 547:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.MountFS = void 0;
const tslib_1 = __webpack_require__(177);
const fs_1 = __webpack_require__(147);
const FakeFS_1 = __webpack_require__(498);
const NodeFS_1 = __webpack_require__(843);
const watchFile_1 = __webpack_require__(126);
const errors = tslib_1.__importStar(__webpack_require__(377));
const path_1 = __webpack_require__(905);
// Only file descriptors prefixed by those values will be forwarded to the MountFS
// instances. Note that the highest MOUNT_MAGIC bit MUST NOT be set, otherwise the
// resulting fd becomes a negative integer, which isn't supposed to happen per
// the unix rules (caused problems w/ Go).
//
// Those values must be synced with packages/yarnpkg-pnp/sources/esm-loader/fspatch.ts
//
const MOUNT_MASK = 0xff000000;
class MountFS extends FakeFS_1.BasePortableFakeFS {
    constructor({ baseFs = new NodeFS_1.NodeFS(), filter = null, magicByte = 0x2a, maxOpenFiles = Infinity, useCache = true, maxAge = 5000, typeCheck = fs_1.constants.S_IFREG, getMountPoint, factoryPromise, factorySync }) {
        if (Math.floor(magicByte) !== magicByte || !(magicByte > 1 && magicByte <= 127))
            throw new Error(`The magic byte must be set to a round value between 1 and 127 included`);
        super();
        this.fdMap = new Map();
        this.nextFd = 3;
        this.isMount = new Set();
        this.notMount = new Set();
        this.realPaths = new Map();
        this.limitOpenFilesTimeout = null;
        this.baseFs = baseFs;
        this.mountInstances = useCache ? new Map() : null;
        this.factoryPromise = factoryPromise;
        this.factorySync = factorySync;
        this.filter = filter;
        this.getMountPoint = getMountPoint;
        this.magic = magicByte << 24;
        this.maxAge = maxAge;
        this.maxOpenFiles = maxOpenFiles;
        this.typeCheck = typeCheck;
    }
    getExtractHint(hints) {
        return this.baseFs.getExtractHint(hints);
    }
    getRealPath() {
        return this.baseFs.getRealPath();
    }
    saveAndClose() {
        var _a;
        (0, watchFile_1.unwatchAllFiles)(this);
        if (this.mountInstances) {
            for (const [path, { childFs }] of this.mountInstances.entries()) {
                (_a = childFs.saveAndClose) === null || _a === void 0 ? void 0 : _a.call(childFs);
                this.mountInstances.delete(path);
            }
        }
    }
    discardAndClose() {
        var _a;
        (0, watchFile_1.unwatchAllFiles)(this);
        if (this.mountInstances) {
            for (const [path, { childFs }] of this.mountInstances.entries()) {
                (_a = childFs.discardAndClose) === null || _a === void 0 ? void 0 : _a.call(childFs);
                this.mountInstances.delete(path);
            }
        }
    }
    resolve(p) {
        return this.baseFs.resolve(p);
    }
    remapFd(mountFs, fd) {
        const remappedFd = this.nextFd++ | this.magic;
        this.fdMap.set(remappedFd, [mountFs, fd]);
        return remappedFd;
    }
    async openPromise(p, flags, mode) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.openPromise(p, flags, mode);
        }, async (mountFs, { subPath }) => {
            return this.remapFd(mountFs, await mountFs.openPromise(subPath, flags, mode));
        });
    }
    openSync(p, flags, mode) {
        return this.makeCallSync(p, () => {
            return this.baseFs.openSync(p, flags, mode);
        }, (mountFs, { subPath }) => {
            return this.remapFd(mountFs, mountFs.openSync(subPath, flags, mode));
        });
    }
    async opendirPromise(p, opts) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.opendirPromise(p, opts);
        }, async (mountFs, { subPath }) => {
            return await mountFs.opendirPromise(subPath, opts);
        }, {
            requireSubpath: false,
        });
    }
    opendirSync(p, opts) {
        return this.makeCallSync(p, () => {
            return this.baseFs.opendirSync(p, opts);
        }, (mountFs, { subPath }) => {
            return mountFs.opendirSync(subPath, opts);
        }, {
            requireSubpath: false,
        });
    }
    async readPromise(fd, buffer, offset, length, position) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return await this.baseFs.readPromise(fd, buffer, offset, length, position);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`read`);
        const [mountFs, realFd] = entry;
        return await mountFs.readPromise(realFd, buffer, offset, length, position);
    }
    readSync(fd, buffer, offset, length, position) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return this.baseFs.readSync(fd, buffer, offset, length, position);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`readSync`);
        const [mountFs, realFd] = entry;
        return mountFs.readSync(realFd, buffer, offset, length, position);
    }
    async writePromise(fd, buffer, offset, length, position) {
        if ((fd & MOUNT_MASK) !== this.magic) {
            if (typeof buffer === `string`) {
                return await this.baseFs.writePromise(fd, buffer, offset);
            }
            else {
                return await this.baseFs.writePromise(fd, buffer, offset, length, position);
            }
        }
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`write`);
        const [mountFs, realFd] = entry;
        if (typeof buffer === `string`) {
            return await mountFs.writePromise(realFd, buffer, offset);
        }
        else {
            return await mountFs.writePromise(realFd, buffer, offset, length, position);
        }
    }
    writeSync(fd, buffer, offset, length, position) {
        if ((fd & MOUNT_MASK) !== this.magic) {
            if (typeof buffer === `string`) {
                return this.baseFs.writeSync(fd, buffer, offset);
            }
            else {
                return this.baseFs.writeSync(fd, buffer, offset, length, position);
            }
        }
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`writeSync`);
        const [mountFs, realFd] = entry;
        if (typeof buffer === `string`) {
            return mountFs.writeSync(realFd, buffer, offset);
        }
        else {
            return mountFs.writeSync(realFd, buffer, offset, length, position);
        }
    }
    async closePromise(fd) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return await this.baseFs.closePromise(fd);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`close`);
        this.fdMap.delete(fd);
        const [mountFs, realFd] = entry;
        return await mountFs.closePromise(realFd);
    }
    closeSync(fd) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return this.baseFs.closeSync(fd);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`closeSync`);
        this.fdMap.delete(fd);
        const [mountFs, realFd] = entry;
        return mountFs.closeSync(realFd);
    }
    createReadStream(p, opts) {
        if (p === null)
            return this.baseFs.createReadStream(p, opts);
        return this.makeCallSync(p, () => {
            return this.baseFs.createReadStream(p, opts);
        }, (mountFs, { archivePath, subPath }) => {
            const stream = mountFs.createReadStream(subPath, opts);
            // This is a very hacky workaround. `MountOpenFS` shouldn't have to work with `NativePath`s.
            // Ref: https://github.com/yarnpkg/berry/pull/3774
            // TODO: think of a better solution
            stream.path = path_1.npath.fromPortablePath(this.pathUtils.join(archivePath, subPath));
            return stream;
        });
    }
    createWriteStream(p, opts) {
        if (p === null)
            return this.baseFs.createWriteStream(p, opts);
        return this.makeCallSync(p, () => {
            return this.baseFs.createWriteStream(p, opts);
        }, (mountFs, { subPath }) => {
            return mountFs.createWriteStream(subPath, opts);
        });
    }
    async realpathPromise(p) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.realpathPromise(p);
        }, async (mountFs, { archivePath, subPath }) => {
            let realArchivePath = this.realPaths.get(archivePath);
            if (typeof realArchivePath === `undefined`) {
                realArchivePath = await this.baseFs.realpathPromise(archivePath);
                this.realPaths.set(archivePath, realArchivePath);
            }
            return this.pathUtils.join(realArchivePath, this.pathUtils.relative(path_1.PortablePath.root, await mountFs.realpathPromise(subPath)));
        });
    }
    realpathSync(p) {
        return this.makeCallSync(p, () => {
            return this.baseFs.realpathSync(p);
        }, (mountFs, { archivePath, subPath }) => {
            let realArchivePath = this.realPaths.get(archivePath);
            if (typeof realArchivePath === `undefined`) {
                realArchivePath = this.baseFs.realpathSync(archivePath);
                this.realPaths.set(archivePath, realArchivePath);
            }
            return this.pathUtils.join(realArchivePath, this.pathUtils.relative(path_1.PortablePath.root, mountFs.realpathSync(subPath)));
        });
    }
    async existsPromise(p) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.existsPromise(p);
        }, async (mountFs, { subPath }) => {
            return await mountFs.existsPromise(subPath);
        });
    }
    existsSync(p) {
        return this.makeCallSync(p, () => {
            return this.baseFs.existsSync(p);
        }, (mountFs, { subPath }) => {
            return mountFs.existsSync(subPath);
        });
    }
    async accessPromise(p, mode) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.accessPromise(p, mode);
        }, async (mountFs, { subPath }) => {
            return await mountFs.accessPromise(subPath, mode);
        });
    }
    accessSync(p, mode) {
        return this.makeCallSync(p, () => {
            return this.baseFs.accessSync(p, mode);
        }, (mountFs, { subPath }) => {
            return mountFs.accessSync(subPath, mode);
        });
    }
    async statPromise(p, opts) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.statPromise(p, opts);
        }, async (mountFs, { subPath }) => {
            return await mountFs.statPromise(subPath, opts);
        });
    }
    statSync(p, opts) {
        return this.makeCallSync(p, () => {
            return this.baseFs.statSync(p, opts);
        }, (mountFs, { subPath }) => {
            return mountFs.statSync(subPath, opts);
        });
    }
    async fstatPromise(fd, opts) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return this.baseFs.fstatPromise(fd, opts);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`fstat`);
        const [mountFs, realFd] = entry;
        return mountFs.fstatPromise(realFd, opts);
    }
    fstatSync(fd, opts) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return this.baseFs.fstatSync(fd, opts);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`fstatSync`);
        const [mountFs, realFd] = entry;
        return mountFs.fstatSync(realFd, opts);
    }
    async lstatPromise(p, opts) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.lstatPromise(p, opts);
        }, async (mountFs, { subPath }) => {
            return await mountFs.lstatPromise(subPath, opts);
        });
    }
    lstatSync(p, opts) {
        return this.makeCallSync(p, () => {
            return this.baseFs.lstatSync(p, opts);
        }, (mountFs, { subPath }) => {
            return mountFs.lstatSync(subPath, opts);
        });
    }
    async fchmodPromise(fd, mask) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return this.baseFs.fchmodPromise(fd, mask);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`fchmod`);
        const [mountFs, realFd] = entry;
        return mountFs.fchmodPromise(realFd, mask);
    }
    fchmodSync(fd, mask) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return this.baseFs.fchmodSync(fd, mask);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`fchmodSync`);
        const [mountFs, realFd] = entry;
        return mountFs.fchmodSync(realFd, mask);
    }
    async chmodPromise(p, mask) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.chmodPromise(p, mask);
        }, async (mountFs, { subPath }) => {
            return await mountFs.chmodPromise(subPath, mask);
        });
    }
    chmodSync(p, mask) {
        return this.makeCallSync(p, () => {
            return this.baseFs.chmodSync(p, mask);
        }, (mountFs, { subPath }) => {
            return mountFs.chmodSync(subPath, mask);
        });
    }
    async fchownPromise(fd, uid, gid) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return this.baseFs.fchownPromise(fd, uid, gid);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`fchown`);
        const [zipFs, realFd] = entry;
        return zipFs.fchownPromise(realFd, uid, gid);
    }
    fchownSync(fd, uid, gid) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return this.baseFs.fchownSync(fd, uid, gid);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`fchownSync`);
        const [zipFs, realFd] = entry;
        return zipFs.fchownSync(realFd, uid, gid);
    }
    async chownPromise(p, uid, gid) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.chownPromise(p, uid, gid);
        }, async (mountFs, { subPath }) => {
            return await mountFs.chownPromise(subPath, uid, gid);
        });
    }
    chownSync(p, uid, gid) {
        return this.makeCallSync(p, () => {
            return this.baseFs.chownSync(p, uid, gid);
        }, (mountFs, { subPath }) => {
            return mountFs.chownSync(subPath, uid, gid);
        });
    }
    async renamePromise(oldP, newP) {
        return await this.makeCallPromise(oldP, async () => {
            return await this.makeCallPromise(newP, async () => {
                return await this.baseFs.renamePromise(oldP, newP);
            }, async () => {
                throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
            });
        }, async (mountFsO, { subPath: subPathO }) => {
            return await this.makeCallPromise(newP, async () => {
                throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
            }, async (mountFsN, { subPath: subPathN }) => {
                if (mountFsO !== mountFsN) {
                    throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
                }
                else {
                    return await mountFsO.renamePromise(subPathO, subPathN);
                }
            });
        });
    }
    renameSync(oldP, newP) {
        return this.makeCallSync(oldP, () => {
            return this.makeCallSync(newP, () => {
                return this.baseFs.renameSync(oldP, newP);
            }, () => {
                throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
            });
        }, (mountFsO, { subPath: subPathO }) => {
            return this.makeCallSync(newP, () => {
                throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
            }, (mountFsN, { subPath: subPathN }) => {
                if (mountFsO !== mountFsN) {
                    throw Object.assign(new Error(`EEXDEV: cross-device link not permitted`), { code: `EEXDEV` });
                }
                else {
                    return mountFsO.renameSync(subPathO, subPathN);
                }
            });
        });
    }
    async copyFilePromise(sourceP, destP, flags = 0) {
        const fallback = async (sourceFs, sourceP, destFs, destP) => {
            if ((flags & fs_1.constants.COPYFILE_FICLONE_FORCE) !== 0)
                throw Object.assign(new Error(`EXDEV: cross-device clone not permitted, copyfile '${sourceP}' -> ${destP}'`), { code: `EXDEV` });
            if ((flags & fs_1.constants.COPYFILE_EXCL) && await this.existsPromise(sourceP))
                throw Object.assign(new Error(`EEXIST: file already exists, copyfile '${sourceP}' -> '${destP}'`), { code: `EEXIST` });
            let content;
            try {
                content = await sourceFs.readFilePromise(sourceP);
            }
            catch (error) {
                throw Object.assign(new Error(`EINVAL: invalid argument, copyfile '${sourceP}' -> '${destP}'`), { code: `EINVAL` });
            }
            await destFs.writeFilePromise(destP, content);
        };
        return await this.makeCallPromise(sourceP, async () => {
            return await this.makeCallPromise(destP, async () => {
                return await this.baseFs.copyFilePromise(sourceP, destP, flags);
            }, async (mountFsD, { subPath: subPathD }) => {
                return await fallback(this.baseFs, sourceP, mountFsD, subPathD);
            });
        }, async (mountFsS, { subPath: subPathS }) => {
            return await this.makeCallPromise(destP, async () => {
                return await fallback(mountFsS, subPathS, this.baseFs, destP);
            }, async (mountFsD, { subPath: subPathD }) => {
                if (mountFsS !== mountFsD) {
                    return await fallback(mountFsS, subPathS, mountFsD, subPathD);
                }
                else {
                    return await mountFsS.copyFilePromise(subPathS, subPathD, flags);
                }
            });
        });
    }
    copyFileSync(sourceP, destP, flags = 0) {
        const fallback = (sourceFs, sourceP, destFs, destP) => {
            if ((flags & fs_1.constants.COPYFILE_FICLONE_FORCE) !== 0)
                throw Object.assign(new Error(`EXDEV: cross-device clone not permitted, copyfile '${sourceP}' -> ${destP}'`), { code: `EXDEV` });
            if ((flags & fs_1.constants.COPYFILE_EXCL) && this.existsSync(sourceP))
                throw Object.assign(new Error(`EEXIST: file already exists, copyfile '${sourceP}' -> '${destP}'`), { code: `EEXIST` });
            let content;
            try {
                content = sourceFs.readFileSync(sourceP);
            }
            catch (error) {
                throw Object.assign(new Error(`EINVAL: invalid argument, copyfile '${sourceP}' -> '${destP}'`), { code: `EINVAL` });
            }
            destFs.writeFileSync(destP, content);
        };
        return this.makeCallSync(sourceP, () => {
            return this.makeCallSync(destP, () => {
                return this.baseFs.copyFileSync(sourceP, destP, flags);
            }, (mountFsD, { subPath: subPathD }) => {
                return fallback(this.baseFs, sourceP, mountFsD, subPathD);
            });
        }, (mountFsS, { subPath: subPathS }) => {
            return this.makeCallSync(destP, () => {
                return fallback(mountFsS, subPathS, this.baseFs, destP);
            }, (mountFsD, { subPath: subPathD }) => {
                if (mountFsS !== mountFsD) {
                    return fallback(mountFsS, subPathS, mountFsD, subPathD);
                }
                else {
                    return mountFsS.copyFileSync(subPathS, subPathD, flags);
                }
            });
        });
    }
    async appendFilePromise(p, content, opts) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.appendFilePromise(p, content, opts);
        }, async (mountFs, { subPath }) => {
            return await mountFs.appendFilePromise(subPath, content, opts);
        });
    }
    appendFileSync(p, content, opts) {
        return this.makeCallSync(p, () => {
            return this.baseFs.appendFileSync(p, content, opts);
        }, (mountFs, { subPath }) => {
            return mountFs.appendFileSync(subPath, content, opts);
        });
    }
    async writeFilePromise(p, content, opts) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.writeFilePromise(p, content, opts);
        }, async (mountFs, { subPath }) => {
            return await mountFs.writeFilePromise(subPath, content, opts);
        });
    }
    writeFileSync(p, content, opts) {
        return this.makeCallSync(p, () => {
            return this.baseFs.writeFileSync(p, content, opts);
        }, (mountFs, { subPath }) => {
            return mountFs.writeFileSync(subPath, content, opts);
        });
    }
    async unlinkPromise(p) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.unlinkPromise(p);
        }, async (mountFs, { subPath }) => {
            return await mountFs.unlinkPromise(subPath);
        });
    }
    unlinkSync(p) {
        return this.makeCallSync(p, () => {
            return this.baseFs.unlinkSync(p);
        }, (mountFs, { subPath }) => {
            return mountFs.unlinkSync(subPath);
        });
    }
    async utimesPromise(p, atime, mtime) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.utimesPromise(p, atime, mtime);
        }, async (mountFs, { subPath }) => {
            return await mountFs.utimesPromise(subPath, atime, mtime);
        });
    }
    utimesSync(p, atime, mtime) {
        return this.makeCallSync(p, () => {
            return this.baseFs.utimesSync(p, atime, mtime);
        }, (mountFs, { subPath }) => {
            return mountFs.utimesSync(subPath, atime, mtime);
        });
    }
    async lutimesPromise(p, atime, mtime) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.lutimesPromise(p, atime, mtime);
        }, async (mountFs, { subPath }) => {
            return await mountFs.lutimesPromise(subPath, atime, mtime);
        });
    }
    lutimesSync(p, atime, mtime) {
        return this.makeCallSync(p, () => {
            return this.baseFs.lutimesSync(p, atime, mtime);
        }, (mountFs, { subPath }) => {
            return mountFs.lutimesSync(subPath, atime, mtime);
        });
    }
    async mkdirPromise(p, opts) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.mkdirPromise(p, opts);
        }, async (mountFs, { subPath }) => {
            return await mountFs.mkdirPromise(subPath, opts);
        });
    }
    mkdirSync(p, opts) {
        return this.makeCallSync(p, () => {
            return this.baseFs.mkdirSync(p, opts);
        }, (mountFs, { subPath }) => {
            return mountFs.mkdirSync(subPath, opts);
        });
    }
    async rmdirPromise(p, opts) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.rmdirPromise(p, opts);
        }, async (mountFs, { subPath }) => {
            return await mountFs.rmdirPromise(subPath, opts);
        });
    }
    rmdirSync(p, opts) {
        return this.makeCallSync(p, () => {
            return this.baseFs.rmdirSync(p, opts);
        }, (mountFs, { subPath }) => {
            return mountFs.rmdirSync(subPath, opts);
        });
    }
    async linkPromise(existingP, newP) {
        return await this.makeCallPromise(newP, async () => {
            return await this.baseFs.linkPromise(existingP, newP);
        }, async (mountFs, { subPath }) => {
            return await mountFs.linkPromise(existingP, subPath);
        });
    }
    linkSync(existingP, newP) {
        return this.makeCallSync(newP, () => {
            return this.baseFs.linkSync(existingP, newP);
        }, (mountFs, { subPath }) => {
            return mountFs.linkSync(existingP, subPath);
        });
    }
    async symlinkPromise(target, p, type) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.symlinkPromise(target, p, type);
        }, async (mountFs, { subPath }) => {
            return await mountFs.symlinkPromise(target, subPath);
        });
    }
    symlinkSync(target, p, type) {
        return this.makeCallSync(p, () => {
            return this.baseFs.symlinkSync(target, p, type);
        }, (mountFs, { subPath }) => {
            return mountFs.symlinkSync(target, subPath);
        });
    }
    async readFilePromise(p, encoding) {
        return this.makeCallPromise(p, async () => {
            return await this.baseFs.readFilePromise(p, encoding);
        }, async (mountFs, { subPath }) => {
            return await mountFs.readFilePromise(subPath, encoding);
        });
    }
    readFileSync(p, encoding) {
        return this.makeCallSync(p, () => {
            return this.baseFs.readFileSync(p, encoding);
        }, (mountFs, { subPath }) => {
            return mountFs.readFileSync(subPath, encoding);
        });
    }
    async readdirPromise(p, opts) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.readdirPromise(p, opts);
        }, async (mountFs, { subPath }) => {
            return await mountFs.readdirPromise(subPath, opts);
        }, {
            requireSubpath: false,
        });
    }
    readdirSync(p, opts) {
        return this.makeCallSync(p, () => {
            return this.baseFs.readdirSync(p, opts);
        }, (mountFs, { subPath }) => {
            return mountFs.readdirSync(subPath, opts);
        }, {
            requireSubpath: false,
        });
    }
    async readlinkPromise(p) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.readlinkPromise(p);
        }, async (mountFs, { subPath }) => {
            return await mountFs.readlinkPromise(subPath);
        });
    }
    readlinkSync(p) {
        return this.makeCallSync(p, () => {
            return this.baseFs.readlinkSync(p);
        }, (mountFs, { subPath }) => {
            return mountFs.readlinkSync(subPath);
        });
    }
    async truncatePromise(p, len) {
        return await this.makeCallPromise(p, async () => {
            return await this.baseFs.truncatePromise(p, len);
        }, async (mountFs, { subPath }) => {
            return await mountFs.truncatePromise(subPath, len);
        });
    }
    truncateSync(p, len) {
        return this.makeCallSync(p, () => {
            return this.baseFs.truncateSync(p, len);
        }, (mountFs, { subPath }) => {
            return mountFs.truncateSync(subPath, len);
        });
    }
    async ftruncatePromise(fd, len) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return this.baseFs.ftruncatePromise(fd, len);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`ftruncate`);
        const [mountFs, realFd] = entry;
        return mountFs.ftruncatePromise(realFd, len);
    }
    ftruncateSync(fd, len) {
        if ((fd & MOUNT_MASK) !== this.magic)
            return this.baseFs.ftruncateSync(fd, len);
        const entry = this.fdMap.get(fd);
        if (typeof entry === `undefined`)
            throw errors.EBADF(`ftruncateSync`);
        const [mountFs, realFd] = entry;
        return mountFs.ftruncateSync(realFd, len);
    }
    watch(p, a, b) {
        return this.makeCallSync(p, () => {
            return this.baseFs.watch(p, 
            // @ts-expect-error
            a, b);
        }, (mountFs, { subPath }) => {
            return mountFs.watch(subPath, 
            // @ts-expect-error
            a, b);
        });
    }
    watchFile(p, a, b) {
        return this.makeCallSync(p, () => {
            return this.baseFs.watchFile(p, 
            // @ts-expect-error
            a, b);
        }, () => {
            return (0, watchFile_1.watchFile)(this, p, a, b);
        });
    }
    unwatchFile(p, cb) {
        return this.makeCallSync(p, () => {
            return this.baseFs.unwatchFile(p, cb);
        }, () => {
            return (0, watchFile_1.unwatchFile)(this, p, cb);
        });
    }
    async makeCallPromise(p, discard, accept, { requireSubpath = true } = {}) {
        if (typeof p !== `string`)
            return await discard();
        const normalizedP = this.resolve(p);
        const mountInfo = this.findMount(normalizedP);
        if (!mountInfo)
            return await discard();
        if (requireSubpath && mountInfo.subPath === `/`)
            return await discard();
        return await this.getMountPromise(mountInfo.archivePath, async (mountFs) => await accept(mountFs, mountInfo));
    }
    makeCallSync(p, discard, accept, { requireSubpath = true } = {}) {
        if (typeof p !== `string`)
            return discard();
        const normalizedP = this.resolve(p);
        const mountInfo = this.findMount(normalizedP);
        if (!mountInfo)
            return discard();
        if (requireSubpath && mountInfo.subPath === `/`)
            return discard();
        return this.getMountSync(mountInfo.archivePath, mountFs => accept(mountFs, mountInfo));
    }
    findMount(p) {
        if (this.filter && !this.filter.test(p))
            return null;
        let filePath = ``;
        while (true) {
            const pathPartWithArchive = p.substring(filePath.length);
            const mountPoint = this.getMountPoint(pathPartWithArchive, filePath);
            if (!mountPoint)
                return null;
            filePath = this.pathUtils.join(filePath, mountPoint);
            if (!this.isMount.has(filePath)) {
                if (this.notMount.has(filePath))
                    continue;
                try {
                    if (this.typeCheck !== null && (this.baseFs.lstatSync(filePath).mode & fs_1.constants.S_IFMT) !== this.typeCheck) {
                        this.notMount.add(filePath);
                        continue;
                    }
                }
                catch {
                    return null;
                }
                this.isMount.add(filePath);
            }
            return {
                archivePath: filePath,
                subPath: this.pathUtils.join(path_1.PortablePath.root, p.substring(filePath.length)),
            };
        }
    }
    limitOpenFiles(max) {
        var _a, _b, _c;
        if (this.mountInstances === null)
            return;
        const now = Date.now();
        let nextExpiresAt = now + this.maxAge;
        let closeCount = max === null ? 0 : this.mountInstances.size - max;
        for (const [path, { childFs, expiresAt, refCount }] of this.mountInstances.entries()) {
            if (refCount !== 0 || ((_a = childFs.hasOpenFileHandles) === null || _a === void 0 ? void 0 : _a.call(childFs))) {
                continue;
            }
            else if (now >= expiresAt) {
                (_b = childFs.saveAndClose) === null || _b === void 0 ? void 0 : _b.call(childFs);
                this.mountInstances.delete(path);
                closeCount -= 1;
                continue;
            }
            else if (max === null || closeCount <= 0) {
                nextExpiresAt = expiresAt;
                break;
            }
            (_c = childFs.saveAndClose) === null || _c === void 0 ? void 0 : _c.call(childFs);
            this.mountInstances.delete(path);
            closeCount -= 1;
        }
        if (this.limitOpenFilesTimeout === null && ((max === null && this.mountInstances.size > 0) || max !== null) && isFinite(nextExpiresAt)) {
            this.limitOpenFilesTimeout = setTimeout(() => {
                this.limitOpenFilesTimeout = null;
                this.limitOpenFiles(null);
            }, nextExpiresAt - now).unref();
        }
    }
    async getMountPromise(p, accept) {
        var _a;
        if (this.mountInstances) {
            let cachedMountFs = this.mountInstances.get(p);
            if (!cachedMountFs) {
                const createFsInstance = await this.factoryPromise(this.baseFs, p);
                // We need to recheck because concurrent getMountPromise calls may
                // have instantiated the mount archive while we were waiting
                cachedMountFs = this.mountInstances.get(p);
                if (!cachedMountFs) {
                    cachedMountFs = {
                        childFs: createFsInstance(),
                        expiresAt: 0,
                        refCount: 0,
                    };
                }
            }
            // Removing then re-adding the field allows us to easily implement
            // a basic LRU garbage collection strategy
            this.mountInstances.delete(p);
            this.limitOpenFiles(this.maxOpenFiles - 1);
            this.mountInstances.set(p, cachedMountFs);
            cachedMountFs.expiresAt = Date.now() + this.maxAge;
            cachedMountFs.refCount += 1;
            try {
                return await accept(cachedMountFs.childFs);
            }
            finally {
                cachedMountFs.refCount -= 1;
            }
        }
        else {
            const mountFs = (await this.factoryPromise(this.baseFs, p))();
            try {
                return await accept(mountFs);
            }
            finally {
                (_a = mountFs.saveAndClose) === null || _a === void 0 ? void 0 : _a.call(mountFs);
            }
        }
    }
    getMountSync(p, accept) {
        var _a;
        if (this.mountInstances) {
            let cachedMountFs = this.mountInstances.get(p);
            if (!cachedMountFs) {
                cachedMountFs = {
                    childFs: this.factorySync(this.baseFs, p),
                    expiresAt: 0,
                    refCount: 0,
                };
            }
            // Removing then re-adding the field allows us to easily implement
            // a basic LRU garbage collection strategy
            this.mountInstances.delete(p);
            this.limitOpenFiles(this.maxOpenFiles - 1);
            this.mountInstances.set(p, cachedMountFs);
            cachedMountFs.expiresAt = Date.now() + this.maxAge;
            return accept(cachedMountFs.childFs);
        }
        else {
            const childFs = this.factorySync(this.baseFs, p);
            try {
                return accept(childFs);
            }
            finally {
                (_a = childFs.saveAndClose) === null || _a === void 0 ? void 0 : _a.call(childFs);
            }
        }
    }
}
exports.MountFS = MountFS;


/***/ }),

/***/ 904:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NoFS = void 0;
const FakeFS_1 = __webpack_require__(498);
const path_1 = __webpack_require__(905);
const makeError = () => Object.assign(new Error(`ENOSYS: unsupported filesystem access`), { code: `ENOSYS` });
class NoFS extends FakeFS_1.FakeFS {
    constructor() {
        super(path_1.ppath);
    }
    getExtractHint() {
        throw makeError();
    }
    getRealPath() {
        throw makeError();
    }
    resolve() {
        throw makeError();
    }
    async openPromise() {
        throw makeError();
    }
    openSync() {
        throw makeError();
    }
    async opendirPromise() {
        throw makeError();
    }
    opendirSync() {
        throw makeError();
    }
    async readPromise() {
        throw makeError();
    }
    readSync() {
        throw makeError();
    }
    async writePromise() {
        throw makeError();
    }
    writeSync() {
        throw makeError();
    }
    async closePromise() {
        throw makeError();
    }
    closeSync() {
        throw makeError();
    }
    createWriteStream() {
        throw makeError();
    }
    createReadStream() {
        throw makeError();
    }
    async realpathPromise() {
        throw makeError();
    }
    realpathSync() {
        throw makeError();
    }
    async readdirPromise() {
        throw makeError();
    }
    readdirSync() {
        throw makeError();
    }
    async existsPromise(p) {
        throw makeError();
    }
    existsSync(p) {
        throw makeError();
    }
    async accessPromise() {
        throw makeError();
    }
    accessSync() {
        throw makeError();
    }
    async statPromise() {
        throw makeError();
    }
    statSync() {
        throw makeError();
    }
    async fstatPromise(fd) {
        throw makeError();
    }
    fstatSync(fd) {
        throw makeError();
    }
    async lstatPromise(p) {
        throw makeError();
    }
    lstatSync(p) {
        throw makeError();
    }
    async fchmodPromise() {
        throw makeError();
    }
    fchmodSync() {
        throw makeError();
    }
    async chmodPromise() {
        throw makeError();
    }
    chmodSync() {
        throw makeError();
    }
    async fchownPromise() {
        throw makeError();
    }
    fchownSync() {
        throw makeError();
    }
    async chownPromise() {
        throw makeError();
    }
    chownSync() {
        throw makeError();
    }
    async mkdirPromise() {
        throw makeError();
    }
    mkdirSync() {
        throw makeError();
    }
    async rmdirPromise() {
        throw makeError();
    }
    rmdirSync() {
        throw makeError();
    }
    async linkPromise() {
        throw makeError();
    }
    linkSync() {
        throw makeError();
    }
    async symlinkPromise() {
        throw makeError();
    }
    symlinkSync() {
        throw makeError();
    }
    async renamePromise() {
        throw makeError();
    }
    renameSync() {
        throw makeError();
    }
    async copyFilePromise() {
        throw makeError();
    }
    copyFileSync() {
        throw makeError();
    }
    async appendFilePromise() {
        throw makeError();
    }
    appendFileSync() {
        throw makeError();
    }
    async writeFilePromise() {
        throw makeError();
    }
    writeFileSync() {
        throw makeError();
    }
    async unlinkPromise() {
        throw makeError();
    }
    unlinkSync() {
        throw makeError();
    }
    async utimesPromise() {
        throw makeError();
    }
    utimesSync() {
        throw makeError();
    }
    async lutimesPromise() {
        throw makeError();
    }
    lutimesSync() {
        throw makeError();
    }
    async readFilePromise() {
        throw makeError();
    }
    readFileSync() {
        throw makeError();
    }
    async readlinkPromise() {
        throw makeError();
    }
    readlinkSync() {
        throw makeError();
    }
    async truncatePromise() {
        throw makeError();
    }
    truncateSync() {
        throw makeError();
    }
    async ftruncatePromise(fd, len) {
        throw makeError();
    }
    ftruncateSync(fd, len) {
        throw makeError();
    }
    watch() {
        throw makeError();
    }
    watchFile() {
        throw makeError();
    }
    unwatchFile() {
        throw makeError();
    }
}
NoFS.instance = new NoFS();
exports.NoFS = NoFS;


/***/ }),

/***/ 843:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NodeFS = void 0;
const tslib_1 = __webpack_require__(177);
const fs_1 = tslib_1.__importDefault(__webpack_require__(147));
const FakeFS_1 = __webpack_require__(498);
const path_1 = __webpack_require__(905);
class NodeFS extends FakeFS_1.BasePortableFakeFS {
    constructor(realFs = fs_1.default) {
        super();
        this.realFs = realFs;
    }
    getExtractHint() {
        return false;
    }
    getRealPath() {
        return path_1.PortablePath.root;
    }
    resolve(p) {
        return path_1.ppath.resolve(p);
    }
    async openPromise(p, flags, mode) {
        return await new Promise((resolve, reject) => {
            this.realFs.open(path_1.npath.fromPortablePath(p), flags, mode, this.makeCallback(resolve, reject));
        });
    }
    openSync(p, flags, mode) {
        return this.realFs.openSync(path_1.npath.fromPortablePath(p), flags, mode);
    }
    async opendirPromise(p, opts) {
        return await new Promise((resolve, reject) => {
            if (typeof opts !== `undefined`) {
                this.realFs.opendir(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
            }
            else {
                this.realFs.opendir(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
            }
        }).then(dir => {
            return Object.defineProperty(dir, `path`, { value: p, configurable: true, writable: true });
        });
    }
    opendirSync(p, opts) {
        const dir = typeof opts !== `undefined`
            ? this.realFs.opendirSync(path_1.npath.fromPortablePath(p), opts)
            : this.realFs.opendirSync(path_1.npath.fromPortablePath(p));
        return Object.defineProperty(dir, `path`, { value: p, configurable: true, writable: true });
    }
    async readPromise(fd, buffer, offset = 0, length = 0, position = -1) {
        return await new Promise((resolve, reject) => {
            this.realFs.read(fd, buffer, offset, length, position, (error, bytesRead) => {
                if (error) {
                    reject(error);
                }
                else {
                    resolve(bytesRead);
                }
            });
        });
    }
    readSync(fd, buffer, offset, length, position) {
        return this.realFs.readSync(fd, buffer, offset, length, position);
    }
    async writePromise(fd, buffer, offset, length, position) {
        return await new Promise((resolve, reject) => {
            if (typeof buffer === `string`) {
                return this.realFs.write(fd, buffer, offset, this.makeCallback(resolve, reject));
            }
            else {
                return this.realFs.write(fd, buffer, offset, length, position, this.makeCallback(resolve, reject));
            }
        });
    }
    writeSync(fd, buffer, offset, length, position) {
        if (typeof buffer === `string`) {
            return this.realFs.writeSync(fd, buffer, offset);
        }
        else {
            return this.realFs.writeSync(fd, buffer, offset, length, position);
        }
    }
    async closePromise(fd) {
        await new Promise((resolve, reject) => {
            this.realFs.close(fd, this.makeCallback(resolve, reject));
        });
    }
    closeSync(fd) {
        this.realFs.closeSync(fd);
    }
    createReadStream(p, opts) {
        const realPath = (p !== null ? path_1.npath.fromPortablePath(p) : p);
        return this.realFs.createReadStream(realPath, opts);
    }
    createWriteStream(p, opts) {
        const realPath = (p !== null ? path_1.npath.fromPortablePath(p) : p);
        return this.realFs.createWriteStream(realPath, opts);
    }
    async realpathPromise(p) {
        return await new Promise((resolve, reject) => {
            this.realFs.realpath(path_1.npath.fromPortablePath(p), {}, this.makeCallback(resolve, reject));
        }).then(path => {
            return path_1.npath.toPortablePath(path);
        });
    }
    realpathSync(p) {
        return path_1.npath.toPortablePath(this.realFs.realpathSync(path_1.npath.fromPortablePath(p), {}));
    }
    async existsPromise(p) {
        return await new Promise(resolve => {
            this.realFs.exists(path_1.npath.fromPortablePath(p), resolve);
        });
    }
    accessSync(p, mode) {
        return this.realFs.accessSync(path_1.npath.fromPortablePath(p), mode);
    }
    async accessPromise(p, mode) {
        return await new Promise((resolve, reject) => {
            this.realFs.access(path_1.npath.fromPortablePath(p), mode, this.makeCallback(resolve, reject));
        });
    }
    existsSync(p) {
        return this.realFs.existsSync(path_1.npath.fromPortablePath(p));
    }
    async statPromise(p, opts) {
        return await new Promise((resolve, reject) => {
            if (opts) {
                this.realFs.stat(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
            }
            else {
                this.realFs.stat(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
            }
        });
    }
    statSync(p, opts) {
        if (opts) {
            return this.realFs.statSync(path_1.npath.fromPortablePath(p), opts);
        }
        else {
            return this.realFs.statSync(path_1.npath.fromPortablePath(p));
        }
    }
    async fstatPromise(fd, opts) {
        return await new Promise((resolve, reject) => {
            if (opts) {
                this.realFs.fstat(fd, opts, this.makeCallback(resolve, reject));
            }
            else {
                this.realFs.fstat(fd, this.makeCallback(resolve, reject));
            }
        });
    }
    fstatSync(fd, opts) {
        if (opts) {
            return this.realFs.fstatSync(fd, opts);
        }
        else {
            return this.realFs.fstatSync(fd);
        }
    }
    async lstatPromise(p, opts) {
        return await new Promise((resolve, reject) => {
            if (opts) {
                this.realFs.lstat(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
            }
            else {
                this.realFs.lstat(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
            }
        });
    }
    lstatSync(p, opts) {
        if (opts) {
            return this.realFs.lstatSync(path_1.npath.fromPortablePath(p), opts);
        }
        else {
            return this.realFs.lstatSync(path_1.npath.fromPortablePath(p));
        }
    }
    async fchmodPromise(fd, mask) {
        return await new Promise((resolve, reject) => {
            this.realFs.fchmod(fd, mask, this.makeCallback(resolve, reject));
        });
    }
    fchmodSync(fd, mask) {
        return this.realFs.fchmodSync(fd, mask);
    }
    async chmodPromise(p, mask) {
        return await new Promise((resolve, reject) => {
            this.realFs.chmod(path_1.npath.fromPortablePath(p), mask, this.makeCallback(resolve, reject));
        });
    }
    chmodSync(p, mask) {
        return this.realFs.chmodSync(path_1.npath.fromPortablePath(p), mask);
    }
    async fchownPromise(fd, uid, gid) {
        return await new Promise((resolve, reject) => {
            this.realFs.fchown(fd, uid, gid, this.makeCallback(resolve, reject));
        });
    }
    fchownSync(fd, uid, gid) {
        return this.realFs.fchownSync(fd, uid, gid);
    }
    async chownPromise(p, uid, gid) {
        return await new Promise((resolve, reject) => {
            this.realFs.chown(path_1.npath.fromPortablePath(p), uid, gid, this.makeCallback(resolve, reject));
        });
    }
    chownSync(p, uid, gid) {
        return this.realFs.chownSync(path_1.npath.fromPortablePath(p), uid, gid);
    }
    async renamePromise(oldP, newP) {
        return await new Promise((resolve, reject) => {
            this.realFs.rename(path_1.npath.fromPortablePath(oldP), path_1.npath.fromPortablePath(newP), this.makeCallback(resolve, reject));
        });
    }
    renameSync(oldP, newP) {
        return this.realFs.renameSync(path_1.npath.fromPortablePath(oldP), path_1.npath.fromPortablePath(newP));
    }
    async copyFilePromise(sourceP, destP, flags = 0) {
        return await new Promise((resolve, reject) => {
            this.realFs.copyFile(path_1.npath.fromPortablePath(sourceP), path_1.npath.fromPortablePath(destP), flags, this.makeCallback(resolve, reject));
        });
    }
    copyFileSync(sourceP, destP, flags = 0) {
        return this.realFs.copyFileSync(path_1.npath.fromPortablePath(sourceP), path_1.npath.fromPortablePath(destP), flags);
    }
    async appendFilePromise(p, content, opts) {
        return await new Promise((resolve, reject) => {
            const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
            if (opts) {
                this.realFs.appendFile(fsNativePath, content, opts, this.makeCallback(resolve, reject));
            }
            else {
                this.realFs.appendFile(fsNativePath, content, this.makeCallback(resolve, reject));
            }
        });
    }
    appendFileSync(p, content, opts) {
        const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
        if (opts) {
            this.realFs.appendFileSync(fsNativePath, content, opts);
        }
        else {
            this.realFs.appendFileSync(fsNativePath, content);
        }
    }
    async writeFilePromise(p, content, opts) {
        return await new Promise((resolve, reject) => {
            const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
            if (opts) {
                this.realFs.writeFile(fsNativePath, content, opts, this.makeCallback(resolve, reject));
            }
            else {
                this.realFs.writeFile(fsNativePath, content, this.makeCallback(resolve, reject));
            }
        });
    }
    writeFileSync(p, content, opts) {
        const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
        if (opts) {
            this.realFs.writeFileSync(fsNativePath, content, opts);
        }
        else {
            this.realFs.writeFileSync(fsNativePath, content);
        }
    }
    async unlinkPromise(p) {
        return await new Promise((resolve, reject) => {
            this.realFs.unlink(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
        });
    }
    unlinkSync(p) {
        return this.realFs.unlinkSync(path_1.npath.fromPortablePath(p));
    }
    async utimesPromise(p, atime, mtime) {
        return await new Promise((resolve, reject) => {
            this.realFs.utimes(path_1.npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject));
        });
    }
    utimesSync(p, atime, mtime) {
        this.realFs.utimesSync(path_1.npath.fromPortablePath(p), atime, mtime);
    }
    async lutimesPromise(p, atime, mtime) {
        return await new Promise((resolve, reject) => {
            this.realFs.lutimes(path_1.npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject));
        });
    }
    lutimesSync(p, atime, mtime) {
        this.realFs.lutimesSync(path_1.npath.fromPortablePath(p), atime, mtime);
    }
    async mkdirPromise(p, opts) {
        return await new Promise((resolve, reject) => {
            this.realFs.mkdir(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
        });
    }
    mkdirSync(p, opts) {
        return this.realFs.mkdirSync(path_1.npath.fromPortablePath(p), opts);
    }
    async rmdirPromise(p, opts) {
        return await new Promise((resolve, reject) => {
            // TODO: always pass opts when min node version is 12.10+
            if (opts) {
                this.realFs.rmdir(path_1.npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));
            }
            else {
                this.realFs.rmdir(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
            }
        });
    }
    rmdirSync(p, opts) {
        return this.realFs.rmdirSync(path_1.npath.fromPortablePath(p), opts);
    }
    async linkPromise(existingP, newP) {
        return await new Promise((resolve, reject) => {
            this.realFs.link(path_1.npath.fromPortablePath(existingP), path_1.npath.fromPortablePath(newP), this.makeCallback(resolve, reject));
        });
    }
    linkSync(existingP, newP) {
        return this.realFs.linkSync(path_1.npath.fromPortablePath(existingP), path_1.npath.fromPortablePath(newP));
    }
    async symlinkPromise(target, p, type) {
        return await new Promise((resolve, reject) => {
            this.realFs.symlink(path_1.npath.fromPortablePath(target.replace(/\/+$/, ``)), path_1.npath.fromPortablePath(p), type, this.makeCallback(resolve, reject));
        });
    }
    symlinkSync(target, p, type) {
        return this.realFs.symlinkSync(path_1.npath.fromPortablePath(target.replace(/\/+$/, ``)), path_1.npath.fromPortablePath(p), type);
    }
    async readFilePromise(p, encoding) {
        return await new Promise((resolve, reject) => {
            const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
            this.realFs.readFile(fsNativePath, encoding, this.makeCallback(resolve, reject));
        });
    }
    readFileSync(p, encoding) {
        const fsNativePath = typeof p === `string` ? path_1.npath.fromPortablePath(p) : p;
        return this.realFs.readFileSync(fsNativePath, encoding);
    }
    async readdirPromise(p, opts) {
        return await new Promise((resolve, reject) => {
            if (opts === null || opts === void 0 ? void 0 : opts.withFileTypes) {
                this.realFs.readdir(path_1.npath.fromPortablePath(p), { withFileTypes: true }, this.makeCallback(resolve, reject));
            }
            else {
                this.realFs.readdir(path_1.npath.fromPortablePath(p), this.makeCallback(value => resolve(value), reject));
            }
        });
    }
    readdirSync(p, opts) {
        if (opts === null || opts === void 0 ? void 0 : opts.withFileTypes) {
            return this.realFs.readdirSync(path_1.npath.fromPortablePath(p), { withFileTypes: true });
        }
        else {
            return this.realFs.readdirSync(path_1.npath.fromPortablePath(p));
        }
    }
    async readlinkPromise(p) {
        return await new Promise((resolve, reject) => {
            this.realFs.readlink(path_1.npath.fromPortablePath(p), this.makeCallback(resolve, reject));
        }).then(path => {
            return path_1.npath.toPortablePath(path);
        });
    }
    readlinkSync(p) {
        return path_1.npath.toPortablePath(this.realFs.readlinkSync(path_1.npath.fromPortablePath(p)));
    }
    async truncatePromise(p, len) {
        return await new Promise((resolve, reject) => {
            this.realFs.truncate(path_1.npath.fromPortablePath(p), len, this.makeCallback(resolve, reject));
        });
    }
    truncateSync(p, len) {
        return this.realFs.truncateSync(path_1.npath.fromPortablePath(p), len);
    }
    async ftruncatePromise(fd, len) {
        return await new Promise((resolve, reject) => {
            this.realFs.ftruncate(fd, len, this.makeCallback(resolve, reject));
        });
    }
    ftruncateSync(fd, len) {
        return this.realFs.ftruncateSync(fd, len);
    }
    watch(p, a, b) {
        return this.realFs.watch(path_1.npath.fromPortablePath(p), 
        // @ts-expect-error
        a, b);
    }
    watchFile(p, a, b) {
        return this.realFs.watchFile(path_1.npath.fromPortablePath(p), 
        // @ts-expect-error
        a, b);
    }
    unwatchFile(p, cb) {
        return this.realFs.unwatchFile(path_1.npath.fromPortablePath(p), cb);
    }
    makeCallback(resolve, reject) {
        return (err, result) => {
            if (err) {
                reject(err);
            }
            else {
                resolve(result);
            }
        };
    }
}
exports.NodeFS = NodeFS;


/***/ }),

/***/ 732:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.NodePathFS = void 0;
const url_1 = __webpack_require__(310);
const util_1 = __webpack_require__(837);
const ProxiedFS_1 = __webpack_require__(105);
const path_1 = __webpack_require__(905);
/**
 * Adds support for file URLs and Buffers to the wrapped `baseFs`, but *not* inside the typings.
 *
 * Only exists for compatibility with Node's behavior.
 *
 * Automatically wraps all FS instances passed to `patchFs` & `extendFs`.
 *
 * Don't use it!
 */
class NodePathFS extends ProxiedFS_1.ProxiedFS {
    constructor(baseFs) {
        super(path_1.npath);
        this.baseFs = baseFs;
    }
    mapFromBase(path) {
        return path;
    }
    mapToBase(path) {
        if (typeof path === `string`)
            return path;
        if (path instanceof url_1.URL)
            return (0, url_1.fileURLToPath)(path);
        if (Buffer.isBuffer(path)) {
            const str = path.toString();
            if (Buffer.byteLength(str) !== path.byteLength)
                throw new Error(`Non-utf8 buffers are not supported at the moment. Please upvote the following issue if you encounter this error: https://github.com/yarnpkg/berry/issues/4942`);
            return str;
        }
        throw new Error(`Unsupported path type: ${(0, util_1.inspect)(path)}`);
    }
}
exports.NodePathFS = NodePathFS;


/***/ }),

/***/ 103:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.PosixFS = void 0;
const ProxiedFS_1 = __webpack_require__(105);
const path_1 = __webpack_require__(905);
class PosixFS extends ProxiedFS_1.ProxiedFS {
    constructor(baseFs) {
        super(path_1.npath);
        this.baseFs = baseFs;
    }
    mapFromBase(path) {
        return path_1.npath.fromPortablePath(path);
    }
    mapToBase(path) {
        return path_1.npath.toPortablePath(path);
    }
}
exports.PosixFS = PosixFS;


/***/ }),

/***/ 105:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ProxiedFS = void 0;
const FakeFS_1 = __webpack_require__(498);
class ProxiedFS extends FakeFS_1.FakeFS {
    getExtractHint(hints) {
        return this.baseFs.getExtractHint(hints);
    }
    resolve(path) {
        return this.mapFromBase(this.baseFs.resolve(this.mapToBase(path)));
    }
    getRealPath() {
        return this.mapFromBase(this.baseFs.getRealPath());
    }
    async openPromise(p, flags, mode) {
        return this.baseFs.openPromise(this.mapToBase(p), flags, mode);
    }
    openSync(p, flags, mode) {
        return this.baseFs.openSync(this.mapToBase(p), flags, mode);
    }
    async opendirPromise(p, opts) {
        return Object.assign(await this.baseFs.opendirPromise(this.mapToBase(p), opts), { path: p });
    }
    opendirSync(p, opts) {
        return Object.assign(this.baseFs.opendirSync(this.mapToBase(p), opts), { path: p });
    }
    async readPromise(fd, buffer, offset, length, position) {
        return await this.baseFs.readPromise(fd, buffer, offset, length, position);
    }
    readSync(fd, buffer, offset, length, position) {
        return this.baseFs.readSync(fd, buffer, offset, length, position);
    }
    async writePromise(fd, buffer, offset, length, position) {
        if (typeof buffer === `string`) {
            return await this.baseFs.writePromise(fd, buffer, offset);
        }
        else {
            return await this.baseFs.writePromise(fd, buffer, offset, length, position);
        }
    }
    writeSync(fd, buffer, offset, length, position) {
        if (typeof buffer === `string`) {
            return this.baseFs.writeSync(fd, buffer, offset);
        }
        else {
            return this.baseFs.writeSync(fd, buffer, offset, length, position);
        }
    }
    async closePromise(fd) {
        return this.baseFs.closePromise(fd);
    }
    closeSync(fd) {
        this.baseFs.closeSync(fd);
    }
    createReadStream(p, opts) {
        return this.baseFs.createReadStream(p !== null ? this.mapToBase(p) : p, opts);
    }
    createWriteStream(p, opts) {
        return this.baseFs.createWriteStream(p !== null ? this.mapToBase(p) : p, opts);
    }
    async realpathPromise(p) {
        return this.mapFromBase(await this.baseFs.realpathPromise(this.mapToBase(p)));
    }
    realpathSync(p) {
        return this.mapFromBase(this.baseFs.realpathSync(this.mapToBase(p)));
    }
    async existsPromise(p) {
        return this.baseFs.existsPromise(this.mapToBase(p));
    }
    existsSync(p) {
        return this.baseFs.existsSync(this.mapToBase(p));
    }
    accessSync(p, mode) {
        return this.baseFs.accessSync(this.mapToBase(p), mode);
    }
    async accessPromise(p, mode) {
        return this.baseFs.accessPromise(this.mapToBase(p), mode);
    }
    async statPromise(p, opts) {
        return this.baseFs.statPromise(this.mapToBase(p), opts);
    }
    statSync(p, opts) {
        return this.baseFs.statSync(this.mapToBase(p), opts);
    }
    async fstatPromise(fd, opts) {
        return this.baseFs.fstatPromise(fd, opts);
    }
    fstatSync(fd, opts) {
        return this.baseFs.fstatSync(fd, opts);
    }
    lstatPromise(p, opts) {
        return this.baseFs.lstatPromise(this.mapToBase(p), opts);
    }
    lstatSync(p, opts) {
        return this.baseFs.lstatSync(this.mapToBase(p), opts);
    }
    async fchmodPromise(fd, mask) {
        return this.baseFs.fchmodPromise(fd, mask);
    }
    fchmodSync(fd, mask) {
        return this.baseFs.fchmodSync(fd, mask);
    }
    async chmodPromise(p, mask) {
        return this.baseFs.chmodPromise(this.mapToBase(p), mask);
    }
    chmodSync(p, mask) {
        return this.baseFs.chmodSync(this.mapToBase(p), mask);
    }
    async fchownPromise(fd, uid, gid) {
        return this.baseFs.fchownPromise(fd, uid, gid);
    }
    fchownSync(fd, uid, gid) {
        return this.baseFs.fchownSync(fd, uid, gid);
    }
    async chownPromise(p, uid, gid) {
        return this.baseFs.chownPromise(this.mapToBase(p), uid, gid);
    }
    chownSync(p, uid, gid) {
        return this.baseFs.chownSync(this.mapToBase(p), uid, gid);
    }
    async renamePromise(oldP, newP) {
        return this.baseFs.renamePromise(this.mapToBase(oldP), this.mapToBase(newP));
    }
    renameSync(oldP, newP) {
        return this.baseFs.renameSync(this.mapToBase(oldP), this.mapToBase(newP));
    }
    async copyFilePromise(sourceP, destP, flags = 0) {
        return this.baseFs.copyFilePromise(this.mapToBase(sourceP), this.mapToBase(destP), flags);
    }
    copyFileSync(sourceP, destP, flags = 0) {
        return this.baseFs.copyFileSync(this.mapToBase(sourceP), this.mapToBase(destP), flags);
    }
    async appendFilePromise(p, content, opts) {
        return this.baseFs.appendFilePromise(this.fsMapToBase(p), content, opts);
    }
    appendFileSync(p, content, opts) {
        return this.baseFs.appendFileSync(this.fsMapToBase(p), content, opts);
    }
    async writeFilePromise(p, content, opts) {
        return this.baseFs.writeFilePromise(this.fsMapToBase(p), content, opts);
    }
    writeFileSync(p, content, opts) {
        return this.baseFs.writeFileSync(this.fsMapToBase(p), content, opts);
    }
    async unlinkPromise(p) {
        return this.baseFs.unlinkPromise(this.mapToBase(p));
    }
    unlinkSync(p) {
        return this.baseFs.unlinkSync(this.mapToBase(p));
    }
    async utimesPromise(p, atime, mtime) {
        return this.baseFs.utimesPromise(this.mapToBase(p), atime, mtime);
    }
    utimesSync(p, atime, mtime) {
        return this.baseFs.utimesSync(this.mapToBase(p), atime, mtime);
    }
    async lutimesPromise(p, atime, mtime) {
        return this.baseFs.lutimesPromise(this.mapToBase(p), atime, mtime);
    }
    lutimesSync(p, atime, mtime) {
        return this.baseFs.lutimesSync(this.mapToBase(p), atime, mtime);
    }
    async mkdirPromise(p, opts) {
        return this.baseFs.mkdirPromise(this.mapToBase(p), opts);
    }
    mkdirSync(p, opts) {
        return this.baseFs.mkdirSync(this.mapToBase(p), opts);
    }
    async rmdirPromise(p, opts) {
        return this.baseFs.rmdirPromise(this.mapToBase(p), opts);
    }
    rmdirSync(p, opts) {
        return this.baseFs.rmdirSync(this.mapToBase(p), opts);
    }
    async linkPromise(existingP, newP) {
        return this.baseFs.linkPromise(this.mapToBase(existingP), this.mapToBase(newP));
    }
    linkSync(existingP, newP) {
        return this.baseFs.linkSync(this.mapToBase(existingP), this.mapToBase(newP));
    }
    async symlinkPromise(target, p, type) {
        const mappedP = this.mapToBase(p);
        if (this.pathUtils.isAbsolute(target))
            return this.baseFs.symlinkPromise(this.mapToBase(target), mappedP, type);
        const mappedAbsoluteTarget = this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(p), target));
        const mappedTarget = this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(mappedP), mappedAbsoluteTarget);
        return this.baseFs.symlinkPromise(mappedTarget, mappedP, type);
    }
    symlinkSync(target, p, type) {
        const mappedP = this.mapToBase(p);
        if (this.pathUtils.isAbsolute(target))
            return this.baseFs.symlinkSync(this.mapToBase(target), mappedP, type);
        const mappedAbsoluteTarget = this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(p), target));
        const mappedTarget = this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(mappedP), mappedAbsoluteTarget);
        return this.baseFs.symlinkSync(mappedTarget, mappedP, type);
    }
    async readFilePromise(p, encoding) {
        return this.baseFs.readFilePromise(this.fsMapToBase(p), encoding);
    }
    readFileSync(p, encoding) {
        return this.baseFs.readFileSync(this.fsMapToBase(p), encoding);
    }
    async readdirPromise(p, opts) {
        return this.baseFs.readdirPromise(this.mapToBase(p), opts);
    }
    readdirSync(p, opts) {
        return this.baseFs.readdirSync(this.mapToBase(p), opts);
    }
    async readlinkPromise(p) {
        return this.mapFromBase(await this.baseFs.readlinkPromise(this.mapToBase(p)));
    }
    readlinkSync(p) {
        return this.mapFromBase(this.baseFs.readlinkSync(this.mapToBase(p)));
    }
    async truncatePromise(p, len) {
        return this.baseFs.truncatePromise(this.mapToBase(p), len);
    }
    truncateSync(p, len) {
        return this.baseFs.truncateSync(this.mapToBase(p), len);
    }
    async ftruncatePromise(fd, len) {
        return this.baseFs.ftruncatePromise(fd, len);
    }
    ftruncateSync(fd, len) {
        return this.baseFs.ftruncateSync(fd, len);
    }
    watch(p, a, b) {
        return this.baseFs.watch(this.mapToBase(p), 
        // @ts-expect-error
        a, b);
    }
    watchFile(p, a, b) {
        return this.baseFs.watchFile(this.mapToBase(p), 
        // @ts-expect-error
        a, b);
    }
    unwatchFile(p, cb) {
        return this.baseFs.unwatchFile(this.mapToBase(p), cb);
    }
    fsMapToBase(p) {
        if (typeof p === `number`) {
            return p;
        }
        else {
            return this.mapToBase(p);
        }
    }
}
exports.ProxiedFS = ProxiedFS;


/***/ }),

/***/ 735:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.VirtualFS = void 0;
const NodeFS_1 = __webpack_require__(843);
const ProxiedFS_1 = __webpack_require__(105);
const path_1 = __webpack_require__(905);
const NUMBER_REGEXP = /^[0-9]+$/;
// $0: full path
// $1: virtual folder
// $2: virtual segment
// $3: hash
// $4: depth
// $5: subpath
const VIRTUAL_REGEXP = /^(\/(?:[^/]+\/)*?(?:\$\$virtual|__virtual__))((?:\/((?:[^/]+-)?[a-f0-9]+)(?:\/([^/]+))?)?((?:\/.*)?))$/;
const VALID_COMPONENT = /^([^/]+-)?[a-f0-9]+$/;
class VirtualFS extends ProxiedFS_1.ProxiedFS {
    static makeVirtualPath(base, component, to) {
        if (path_1.ppath.basename(base) !== `__virtual__`)
            throw new Error(`Assertion failed: Virtual folders must be named "__virtual__"`);
        if (!path_1.ppath.basename(component).match(VALID_COMPONENT))
            throw new Error(`Assertion failed: Virtual components must be ended by an hexadecimal hash`);
        // Obtains the relative distance between the virtual path and its actual target
        const target = path_1.ppath.relative(path_1.ppath.dirname(base), to);
        const segments = target.split(`/`);
        // Counts how many levels we need to go back to start applying the rest of the path
        let depth = 0;
        while (depth < segments.length && segments[depth] === `..`)
            depth += 1;
        const finalSegments = segments.slice(depth);
        const fullVirtualPath = path_1.ppath.join(base, component, String(depth), ...finalSegments);
        return fullVirtualPath;
    }
    static resolveVirtual(p) {
        const match = p.match(VIRTUAL_REGEXP);
        if (!match || (!match[3] && match[5]))
            return p;
        const target = path_1.ppath.dirname(match[1]);
        if (!match[3] || !match[4])
            return target;
        const isnum = NUMBER_REGEXP.test(match[4]);
        if (!isnum)
            return p;
        const depth = Number(match[4]);
        const backstep = `../`.repeat(depth);
        const subpath = (match[5] || `.`);
        return VirtualFS.resolveVirtual(path_1.ppath.join(target, backstep, subpath));
    }
    constructor({ baseFs = new NodeFS_1.NodeFS() } = {}) {
        super(path_1.ppath);
        this.baseFs = baseFs;
    }
    getExtractHint(hints) {
        return this.baseFs.getExtractHint(hints);
    }
    getRealPath() {
        return this.baseFs.getRealPath();
    }
    realpathSync(p) {
        const match = p.match(VIRTUAL_REGEXP);
        if (!match)
            return this.baseFs.realpathSync(p);
        if (!match[5])
            return p;
        const realpath = this.baseFs.realpathSync(this.mapToBase(p));
        return VirtualFS.makeVirtualPath(match[1], match[3], realpath);
    }
    async realpathPromise(p) {
        const match = p.match(VIRTUAL_REGEXP);
        if (!match)
            return await this.baseFs.realpathPromise(p);
        if (!match[5])
            return p;
        const realpath = await this.baseFs.realpathPromise(this.mapToBase(p));
        return VirtualFS.makeVirtualPath(match[1], match[3], realpath);
    }
    mapToBase(p) {
        if (p === ``)
            return p;
        if (this.pathUtils.isAbsolute(p))
            return VirtualFS.resolveVirtual(p);
        const resolvedRoot = VirtualFS.resolveVirtual(this.baseFs.resolve(path_1.PortablePath.dot));
        const resolvedP = VirtualFS.resolveVirtual(this.baseFs.resolve(p));
        return path_1.ppath.relative(resolvedRoot, resolvedP) || path_1.PortablePath.dot;
    }
    mapFromBase(p) {
        return p;
    }
}
exports.VirtualFS = VirtualFS;


/***/ }),

/***/ 142:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.copyPromise = exports.setupCopyIndex = void 0;
const tslib_1 = __webpack_require__(177);
const constants = tslib_1.__importStar(__webpack_require__(78));
const path_1 = __webpack_require__(905);
const defaultTime = new Date(constants.SAFE_TIME * 1000);
const defaultTimeMs = defaultTime.getTime();
async function setupCopyIndex(destinationFs, linkStrategy) {
    const hexCharacters = `0123456789abcdef`;
    await destinationFs.mkdirPromise(linkStrategy.indexPath, { recursive: true });
    const promises = [];
    for (const l1 of hexCharacters)
        for (const l2 of hexCharacters)
            promises.push(destinationFs.mkdirPromise(destinationFs.pathUtils.join(linkStrategy.indexPath, `${l1}${l2}`), { recursive: true }));
    await Promise.all(promises);
    return linkStrategy.indexPath;
}
exports.setupCopyIndex = setupCopyIndex;
async function copyPromise(destinationFs, destination, sourceFs, source, opts) {
    const normalizedDestination = destinationFs.pathUtils.normalize(destination);
    const normalizedSource = sourceFs.pathUtils.normalize(source);
    const prelayout = [];
    const postlayout = [];
    const { atime, mtime } = opts.stableTime
        ? { atime: defaultTime, mtime: defaultTime }
        : await sourceFs.lstatPromise(normalizedSource);
    await destinationFs.mkdirpPromise(destinationFs.pathUtils.dirname(destination), { utimes: [atime, mtime] });
    await copyImpl(prelayout, postlayout, destinationFs, normalizedDestination, sourceFs, normalizedSource, { ...opts, didParentExist: true });
    for (const operation of prelayout)
        await operation();
    await Promise.all(postlayout.map(operation => {
        return operation();
    }));
}
exports.copyPromise = copyPromise;
async function copyImpl(prelayout, postlayout, destinationFs, destination, sourceFs, source, opts) {
    var _a, _b, _c;
    const destinationStat = opts.didParentExist ? await maybeLStat(destinationFs, destination) : null;
    const sourceStat = await sourceFs.lstatPromise(source);
    const { atime, mtime } = opts.stableTime
        ? { atime: defaultTime, mtime: defaultTime }
        : sourceStat;
    let updated;
    switch (true) {
        case sourceStat.isDirectory():
            {
                updated = await copyFolder(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
            }
            break;
        case sourceStat.isFile():
            {
                updated = await copyFile(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
            }
            break;
        case sourceStat.isSymbolicLink():
            {
                updated = await copySymlink(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
            }
            break;
        default:
            {
                throw new Error(`Unsupported file type (${sourceStat.mode})`);
            }
            break;
    }
    // We aren't allowed to modify the destination if we work with the index,
    // since otherwise we'd accidentally propagate the changes to all projects.
    if (((_a = opts.linkStrategy) === null || _a === void 0 ? void 0 : _a.type) !== `HardlinkFromIndex` || !sourceStat.isFile()) {
        if (updated || ((_b = destinationStat === null || destinationStat === void 0 ? void 0 : destinationStat.mtime) === null || _b === void 0 ? void 0 : _b.getTime()) !== mtime.getTime() || ((_c = destinationStat === null || destinationStat === void 0 ? void 0 : destinationStat.atime) === null || _c === void 0 ? void 0 : _c.getTime()) !== atime.getTime()) {
            postlayout.push(() => destinationFs.lutimesPromise(destination, atime, mtime));
            updated = true;
        }
        if (destinationStat === null || (destinationStat.mode & 0o777) !== (sourceStat.mode & 0o777)) {
            postlayout.push(() => destinationFs.chmodPromise(destination, sourceStat.mode & 0o777));
            updated = true;
        }
    }
    return updated;
}
async function maybeLStat(baseFs, p) {
    try {
        return await baseFs.lstatPromise(p);
    }
    catch (e) {
        return null;
    }
}
async function copyFolder(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
    if (destinationStat !== null && !destinationStat.isDirectory()) {
        if (opts.overwrite) {
            prelayout.push(async () => destinationFs.removePromise(destination));
            destinationStat = null;
        }
        else {
            return false;
        }
    }
    let updated = false;
    if (destinationStat === null) {
        prelayout.push(async () => {
            try {
                await destinationFs.mkdirPromise(destination, { mode: sourceStat.mode });
            }
            catch (err) {
                if (err.code !== `EEXIST`) {
                    throw err;
                }
            }
        });
        updated = true;
    }
    const entries = await sourceFs.readdirPromise(source);
    const nextOpts = opts.didParentExist && !destinationStat ? { ...opts, didParentExist: false } : opts;
    if (opts.stableSort) {
        for (const entry of entries.sort()) {
            if (await copyImpl(prelayout, postlayout, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), nextOpts)) {
                updated = true;
            }
        }
    }
    else {
        const entriesUpdateStatus = await Promise.all(entries.map(async (entry) => {
            await copyImpl(prelayout, postlayout, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), nextOpts);
        }));
        if (entriesUpdateStatus.some(status => status)) {
            updated = true;
        }
    }
    return updated;
}
async function copyFileViaIndex(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts, linkStrategy) {
    const sourceHash = await sourceFs.checksumFilePromise(source, { algorithm: `sha1` });
    const indexPath = destinationFs.pathUtils.join(linkStrategy.indexPath, sourceHash.slice(0, 2), `${sourceHash}.dat`);
    let AtomicBehavior;
    (function (AtomicBehavior) {
        AtomicBehavior[AtomicBehavior["Lock"] = 0] = "Lock";
        AtomicBehavior[AtomicBehavior["Rename"] = 1] = "Rename";
    })(AtomicBehavior || (AtomicBehavior = {}));
    let atomicBehavior = AtomicBehavior.Rename;
    let indexStat = await maybeLStat(destinationFs, indexPath);
    if (destinationStat) {
        const isDestinationHardlinkedFromIndex = indexStat && destinationStat.dev === indexStat.dev && destinationStat.ino === indexStat.ino;
        const isIndexModified = (indexStat === null || indexStat === void 0 ? void 0 : indexStat.mtimeMs) !== defaultTimeMs;
        if (isDestinationHardlinkedFromIndex) {
            // If the index is modified, we will want to repair it. However, the
            // default logic ensuring atomicity (creating a file in a temporary
            // place before atomically moving it into its final location) won't
            // work: we'd lose all the existing hardlinks.
            //
            // To avoid that, when repairing a file, we fallback to the slow but
            // safer `lockPromise`-based mutex, which will prevent multiple
            // processes to modify the file without impacting their inode.
            //
            // Give that the repair mechanism should be very rarely needed in
            // situation where performance is critical, it should be ok.
            //
            if (isIndexModified && linkStrategy.autoRepair) {
                atomicBehavior = AtomicBehavior.Lock;
                indexStat = null;
            }
        }
        if (!isDestinationHardlinkedFromIndex) {
            if (opts.overwrite) {
                prelayout.push(async () => destinationFs.removePromise(destination));
                destinationStat = null;
            }
            else {
                return false;
            }
        }
    }
    const tempPath = !indexStat && atomicBehavior === AtomicBehavior.Rename
        ? `${indexPath}.${Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, `0`)}`
        : null;
    let tempPathCleaned = false;
    prelayout.push(async () => {
        if (!indexStat) {
            if (atomicBehavior === AtomicBehavior.Lock) {
                await destinationFs.lockPromise(indexPath, async () => {
                    const content = await sourceFs.readFilePromise(source);
                    await destinationFs.writeFilePromise(indexPath, content);
                });
            }
            if (atomicBehavior === AtomicBehavior.Rename && tempPath) {
                const content = await sourceFs.readFilePromise(source);
                await destinationFs.writeFilePromise(tempPath, content);
                // We use `linkPromise` rather than `renamePromise` because the later
                // overwrites the destination if it already exists; usually this
                // wouldn't be a problem, but since we care about preserving the
                // hardlink identity of the destination, we can't do that.
                //
                // So instead we create a hardlink of the source file (which will
                // fail with EEXIST if the destination already exists), and we remove
                // the source in the postlayout steps.
                //
                try {
                    await destinationFs.linkPromise(tempPath, indexPath);
                }
                catch (err) {
                    if (err.code === `EEXIST`) {
                        tempPathCleaned = true;
                        await destinationFs.unlinkPromise(tempPath);
                    }
                    else {
                        throw err;
                    }
                }
            }
        }
        if (!destinationStat) {
            await destinationFs.linkPromise(indexPath, destination);
        }
    });
    postlayout.push(async () => {
        if (!indexStat)
            await destinationFs.lutimesPromise(indexPath, defaultTime, defaultTime);
        if (tempPath && !tempPathCleaned) {
            await destinationFs.unlinkPromise(tempPath);
        }
    });
    return false;
}
async function copyFileDirect(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
    if (destinationStat !== null) {
        if (opts.overwrite) {
            prelayout.push(async () => destinationFs.removePromise(destination));
            destinationStat = null;
        }
        else {
            return false;
        }
    }
    // TODO: Add support for file cloning, by adding a flag inside the FakeFS
    // instances to detect which "namespace" they're part of (for example, the
    // NodeFS and the ZipFS would be different namespaces since you can't clone
    // from one disk to the other; on the other hand, a CwdFS would share the
    // namespace from its base FS and thus would support cloning).
    prelayout.push(async () => {
        const content = await sourceFs.readFilePromise(source);
        await destinationFs.writeFilePromise(destination, content);
    });
    return true;
}
async function copyFile(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
    var _a;
    if (((_a = opts.linkStrategy) === null || _a === void 0 ? void 0 : _a.type) === `HardlinkFromIndex`) {
        return copyFileViaIndex(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts, opts.linkStrategy);
    }
    else {
        return copyFileDirect(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);
    }
}
async function copySymlink(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {
    if (destinationStat !== null) {
        if (opts.overwrite) {
            prelayout.push(async () => destinationFs.removePromise(destination));
            destinationStat = null;
        }
        else {
            return false;
        }
    }
    prelayout.push(async () => {
        await destinationFs.symlinkPromise((0, path_1.convertPath)(destinationFs.pathUtils, await sourceFs.readlinkPromise(source)), destination);
    });
    return true;
}


/***/ }),

/***/ 109:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.opendir = exports.CustomDir = void 0;
const tslib_1 = __webpack_require__(177);
const errors = tslib_1.__importStar(__webpack_require__(377));
class CustomDir {
    constructor(path, nextDirent, opts = {}) {
        this.path = path;
        this.nextDirent = nextDirent;
        this.opts = opts;
        this.closed = false;
    }
    throwIfClosed() {
        if (this.closed) {
            throw errors.ERR_DIR_CLOSED();
        }
    }
    async *[Symbol.asyncIterator]() {
        try {
            let dirent;
            // eslint-disable-next-line no-cond-assign
            while ((dirent = await this.read()) !== null) {
                yield dirent;
            }
        }
        finally {
            await this.close();
        }
    }
    read(cb) {
        const dirent = this.readSync();
        if (typeof cb !== `undefined`)
            return cb(null, dirent);
        return Promise.resolve(dirent);
    }
    readSync() {
        this.throwIfClosed();
        return this.nextDirent();
    }
    close(cb) {
        this.closeSync();
        if (typeof cb !== `undefined`)
            return cb(null);
        return Promise.resolve();
    }
    closeSync() {
        var _a, _b;
        this.throwIfClosed();
        (_b = (_a = this.opts).onClose) === null || _b === void 0 ? void 0 : _b.call(_a);
        this.closed = true;
    }
}
exports.CustomDir = CustomDir;
function opendir(fakeFs, path, entries, opts) {
    const nextDirent = () => {
        const filename = entries.shift();
        if (typeof filename === `undefined`)
            return null;
        return Object.assign(fakeFs.statSync(fakeFs.pathUtils.join(path, filename)), {
            name: filename,
        });
    };
    return new CustomDir(path, nextDirent, opts);
}
exports.opendir = opendir;


/***/ }),

/***/ 126:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.unwatchAllFiles = exports.unwatchFile = exports.watchFile = void 0;
const CustomStatWatcher_1 = __webpack_require__(75);
const statWatchersByFakeFS = new WeakMap();
function watchFile(fakeFs, path, a, b) {
    let bigint;
    let persistent;
    let interval;
    let listener;
    switch (typeof a) {
        case `function`:
            {
                bigint = false;
                persistent = true;
                interval = 5007;
                listener = a;
            }
            break;
        default:
            {
                ({
                    bigint = false,
                    persistent = true,
                    interval = 5007,
                } = a);
                listener = b;
            }
            break;
    }
    let statWatchers = statWatchersByFakeFS.get(fakeFs);
    if (typeof statWatchers === `undefined`)
        statWatchersByFakeFS.set(fakeFs, statWatchers = new Map());
    let statWatcher = statWatchers.get(path);
    if (typeof statWatcher === `undefined`) {
        statWatcher = CustomStatWatcher_1.CustomStatWatcher.create(fakeFs, path, { bigint });
        statWatchers.set(path, statWatcher);
    }
    statWatcher.registerChangeListener(listener, { persistent, interval });
    return statWatcher;
}
exports.watchFile = watchFile;
function unwatchFile(fakeFs, path, cb) {
    const statWatchers = statWatchersByFakeFS.get(fakeFs);
    if (typeof statWatchers === `undefined`)
        return;
    const statWatcher = statWatchers.get(path);
    if (typeof statWatcher === `undefined`)
        return;
    if (typeof cb === `undefined`)
        statWatcher.unregisterAllChangeListeners();
    else
        statWatcher.unregisterChangeListener(cb);
    if (!statWatcher.hasChangeListeners()) {
        statWatcher.stop();
        statWatchers.delete(path);
    }
}
exports.unwatchFile = unwatchFile;
function unwatchAllFiles(fakeFs) {
    const statWatchers = statWatchersByFakeFS.get(fakeFs);
    if (typeof statWatchers === `undefined`)
        return;
    for (const path of statWatchers.keys()) {
        unwatchFile(fakeFs, path);
    }
}
exports.unwatchAllFiles = unwatchAllFiles;


/***/ }),

/***/ 75:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.CustomStatWatcher = exports.assertStatus = exports.Status = exports.Event = void 0;
const tslib_1 = __webpack_require__(177);
const events_1 = __webpack_require__(361);
const statUtils = tslib_1.__importStar(__webpack_require__(64));
var Event;
(function (Event) {
    Event["Change"] = "change";
    Event["Stop"] = "stop";
})(Event = exports.Event || (exports.Event = {}));
var Status;
(function (Status) {
    Status["Ready"] = "ready";
    Status["Running"] = "running";
    Status["Stopped"] = "stopped";
})(Status = exports.Status || (exports.Status = {}));
function assertStatus(current, expected) {
    if (current !== expected) {
        throw new Error(`Invalid StatWatcher status: expected '${expected}', got '${current}'`);
    }
}
exports.assertStatus = assertStatus;
class CustomStatWatcher extends events_1.EventEmitter {
    static create(fakeFs, path, opts) {
        const statWatcher = new CustomStatWatcher(fakeFs, path, opts);
        statWatcher.start();
        return statWatcher;
    }
    constructor(fakeFs, path, { bigint = false } = {}) {
        super();
        this.status = Status.Ready;
        this.changeListeners = new Map();
        this.startTimeout = null;
        this.fakeFs = fakeFs;
        this.path = path;
        this.bigint = bigint;
        this.lastStats = this.stat();
    }
    start() {
        assertStatus(this.status, Status.Ready);
        this.status = Status.Running;
        // Node allows other listeners to be registered up to 3 milliseconds
        // after the watcher has been started, so that's what we're doing too
        this.startTimeout = setTimeout(() => {
            this.startTimeout = null;
            // Per the Node FS docs:
            // "When an fs.watchFile operation results in an ENOENT error,
            // it will invoke the listener once, with all the fields zeroed
            // (or, for dates, the Unix Epoch)."
            if (!this.fakeFs.existsSync(this.path)) {
                this.emit(Event.Change, this.lastStats, this.lastStats);
            }
        }, 3);
    }
    stop() {
        assertStatus(this.status, Status.Running);
        this.status = Status.Stopped;
        if (this.startTimeout !== null) {
            clearTimeout(this.startTimeout);
            this.startTimeout = null;
        }
        this.emit(Event.Stop);
    }
    stat() {
        try {
            return this.fakeFs.statSync(this.path, { bigint: this.bigint });
        }
        catch (error) {
            // From observation, all errors seem to be mostly ignored by Node.
            // Checked with ENOENT, ENOTDIR, EPERM
            const statInstance = this.bigint
                ? new statUtils.BigIntStatsEntry()
                : new statUtils.StatEntry();
            return statUtils.clearStats(statInstance);
        }
    }
    /**
     * Creates an interval whose callback compares the current stats with the previous stats and notifies all listeners in case of changes.
     *
     * @param opts.persistent Decides whether the interval should be immediately unref-ed.
     */
    makeInterval(opts) {
        const interval = setInterval(() => {
            const currentStats = this.stat();
            const previousStats = this.lastStats;
            if (statUtils.areStatsEqual(currentStats, previousStats))
                return;
            this.lastStats = currentStats;
            this.emit(Event.Change, currentStats, previousStats);
        }, opts.interval);
        return opts.persistent ? interval : interval.unref();
    }
    /**
     * Registers a listener and assigns it an interval.
     */
    registerChangeListener(listener, opts) {
        this.addListener(Event.Change, listener);
        this.changeListeners.set(listener, this.makeInterval(opts));
    }
    /**
     * Unregisters the listener and clears the assigned interval.
     */
    unregisterChangeListener(listener) {
        this.removeListener(Event.Change, listener);
        const interval = this.changeListeners.get(listener);
        if (typeof interval !== `undefined`)
            clearInterval(interval);
        this.changeListeners.delete(listener);
    }
    /**
     * Unregisters all listeners and clears all assigned intervals.
     */
    unregisterAllChangeListeners() {
        for (const listener of this.changeListeners.keys()) {
            this.unregisterChangeListener(listener);
        }
    }
    hasChangeListeners() {
        return this.changeListeners.size > 0;
    }
    /**
     * Refs all stored intervals.
     */
    ref() {
        for (const interval of this.changeListeners.values())
            interval.ref();
        return this;
    }
    /**
     * Unrefs all stored intervals.
     */
    unref() {
        for (const interval of this.changeListeners.values())
            interval.unref();
        return this;
    }
}
exports.CustomStatWatcher = CustomStatWatcher;


/***/ }),

/***/ 78:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.SAFE_TIME = exports.S_IFLNK = exports.S_IFREG = exports.S_IFDIR = exports.S_IFMT = void 0;
exports.S_IFMT = 0o170000;
exports.S_IFDIR = 0o040000;
exports.S_IFREG = 0o100000;
exports.S_IFLNK = 0o120000;
/**
 * Unix timestamp for `1984-06-22T21:50:00.000Z`
 *
 * It needs to be after 1980-01-01 because that's what Zip supports, and it
 * needs to have a slight offset to account for different timezones (because
 * zip assumes that all times are local to whoever writes the file, which is
 * really silly).
 */
exports.SAFE_TIME = 456789000;


/***/ }),

/***/ 377:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ERR_DIR_CLOSED = exports.EOPNOTSUPP = exports.ENOTEMPTY = exports.EROFS = exports.EEXIST = exports.EISDIR = exports.ENOTDIR = exports.ENOENT = exports.EBADF = exports.EINVAL = exports.ENOSYS = exports.EBUSY = void 0;
function makeError(code, message) {
    return Object.assign(new Error(`${code}: ${message}`), { code });
}
function EBUSY(message) {
    return makeError(`EBUSY`, message);
}
exports.EBUSY = EBUSY;
function ENOSYS(message, reason) {
    return makeError(`ENOSYS`, `${message}, ${reason}`);
}
exports.ENOSYS = ENOSYS;
function EINVAL(reason) {
    return makeError(`EINVAL`, `invalid argument, ${reason}`);
}
exports.EINVAL = EINVAL;
function EBADF(reason) {
    return makeError(`EBADF`, `bad file descriptor, ${reason}`);
}
exports.EBADF = EBADF;
function ENOENT(reason) {
    return makeError(`ENOENT`, `no such file or directory, ${reason}`);
}
exports.ENOENT = ENOENT;
function ENOTDIR(reason) {
    return makeError(`ENOTDIR`, `not a directory, ${reason}`);
}
exports.ENOTDIR = ENOTDIR;
function EISDIR(reason) {
    return makeError(`EISDIR`, `illegal operation on a directory, ${reason}`);
}
exports.EISDIR = EISDIR;
function EEXIST(reason) {
    return makeError(`EEXIST`, `file already exists, ${reason}`);
}
exports.EEXIST = EEXIST;
function EROFS(reason) {
    return makeError(`EROFS`, `read-only filesystem, ${reason}`);
}
exports.EROFS = EROFS;
function ENOTEMPTY(reason) {
    return makeError(`ENOTEMPTY`, `directory not empty, ${reason}`);
}
exports.ENOTEMPTY = ENOTEMPTY;
function EOPNOTSUPP(reason) {
    return makeError(`EOPNOTSUPP`, `operation not supported, ${reason}`);
}
exports.EOPNOTSUPP = EOPNOTSUPP;
// ------------------------------------------------------------------------
function ERR_DIR_CLOSED() {
    return makeError(`ERR_DIR_CLOSED`, `Directory handle was closed`);
}
exports.ERR_DIR_CLOSED = ERR_DIR_CLOSED;


/***/ }),

/***/ 382:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.xfs = exports.extendFs = exports.patchFs = exports.VirtualFS = exports.ProxiedFS = exports.PosixFS = exports.NodeFS = exports.NoFS = exports.MountFS = exports.LazyFS = exports.JailFS = exports.CwdFS = exports.BasePortableFakeFS = exports.FakeFS = exports.AliasFS = exports.toFilename = exports.ppath = exports.npath = exports.Filename = exports.PortablePath = exports.normalizeLineEndings = exports.unwatchAllFiles = exports.unwatchFile = exports.watchFile = exports.CustomDir = exports.opendir = exports.setupCopyIndex = exports.statUtils = exports.errors = exports.constants = void 0;
const tslib_1 = __webpack_require__(177);
const constants = tslib_1.__importStar(__webpack_require__(78));
exports.constants = constants;
const errors = tslib_1.__importStar(__webpack_require__(377));
exports.errors = errors;
const statUtils = tslib_1.__importStar(__webpack_require__(64));
exports.statUtils = statUtils;
var copyPromise_1 = __webpack_require__(142);
Object.defineProperty(exports, "setupCopyIndex", ({ enumerable: true, get: function () { return copyPromise_1.setupCopyIndex; } }));
var opendir_1 = __webpack_require__(109);
Object.defineProperty(exports, "opendir", ({ enumerable: true, get: function () { return opendir_1.opendir; } }));
Object.defineProperty(exports, "CustomDir", ({ enumerable: true, get: function () { return opendir_1.CustomDir; } }));
var watchFile_1 = __webpack_require__(126);
Object.defineProperty(exports, "watchFile", ({ enumerable: true, get: function () { return watchFile_1.watchFile; } }));
Object.defineProperty(exports, "unwatchFile", ({ enumerable: true, get: function () { return watchFile_1.unwatchFile; } }));
Object.defineProperty(exports, "unwatchAllFiles", ({ enumerable: true, get: function () { return watchFile_1.unwatchAllFiles; } }));
var FakeFS_1 = __webpack_require__(498);
Object.defineProperty(exports, "normalizeLineEndings", ({ enumerable: true, get: function () { return FakeFS_1.normalizeLineEndings; } }));
var path_1 = __webpack_require__(905);
Object.defineProperty(exports, "PortablePath", ({ enumerable: true, get: function () { return path_1.PortablePath; } }));
Object.defineProperty(exports, "Filename", ({ enumerable: true, get: function () { return path_1.Filename; } }));
var path_2 = __webpack_require__(905);
Object.defineProperty(exports, "npath", ({ enumerable: true, get: function () { return path_2.npath; } }));
Object.defineProperty(exports, "ppath", ({ enumerable: true, get: function () { return path_2.ppath; } }));
Object.defineProperty(exports, "toFilename", ({ enumerable: true, get: function () { return path_2.toFilename; } }));
var AliasFS_1 = __webpack_require__(5);
Object.defineProperty(exports, "AliasFS", ({ enumerable: true, get: function () { return AliasFS_1.AliasFS; } }));
var FakeFS_2 = __webpack_require__(498);
Object.defineProperty(exports, "FakeFS", ({ enumerable: true, get: function () { return FakeFS_2.FakeFS; } }));
Object.defineProperty(exports, "BasePortableFakeFS", ({ enumerable: true, get: function () { return FakeFS_2.BasePortableFakeFS; } }));
var CwdFS_1 = __webpack_require__(472);
Object.defineProperty(exports, "CwdFS", ({ enumerable: true, get: function () { return CwdFS_1.CwdFS; } }));
var JailFS_1 = __webpack_require__(238);
Object.defineProperty(exports, "JailFS", ({ enumerable: true, get: function () { return JailFS_1.JailFS; } }));
var LazyFS_1 = __webpack_require__(130);
Object.defineProperty(exports, "LazyFS", ({ enumerable: true, get: function () { return LazyFS_1.LazyFS; } }));
var MountFS_1 = __webpack_require__(547);
Object.defineProperty(exports, "MountFS", ({ enumerable: true, get: function () { return MountFS_1.MountFS; } }));
var NoFS_1 = __webpack_require__(904);
Object.defineProperty(exports, "NoFS", ({ enumerable: true, get: function () { return NoFS_1.NoFS; } }));
var NodeFS_1 = __webpack_require__(843);
Object.defineProperty(exports, "NodeFS", ({ enumerable: true, get: function () { return NodeFS_1.NodeFS; } }));
var PosixFS_1 = __webpack_require__(103);
Object.defineProperty(exports, "PosixFS", ({ enumerable: true, get: function () { return PosixFS_1.PosixFS; } }));
var ProxiedFS_1 = __webpack_require__(105);
Object.defineProperty(exports, "ProxiedFS", ({ enumerable: true, get: function () { return ProxiedFS_1.ProxiedFS; } }));
var VirtualFS_1 = __webpack_require__(735);
Object.defineProperty(exports, "VirtualFS", ({ enumerable: true, get: function () { return VirtualFS_1.VirtualFS; } }));
var patchFs_1 = __webpack_require__(781);
Object.defineProperty(exports, "patchFs", ({ enumerable: true, get: function () { return patchFs_1.patchFs; } }));
Object.defineProperty(exports, "extendFs", ({ enumerable: true, get: function () { return patchFs_1.extendFs; } }));
var xfs_1 = __webpack_require__(743);
Object.defineProperty(exports, "xfs", ({ enumerable: true, get: function () { return xfs_1.xfs; } }));


/***/ }),

/***/ 893:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

var _a, _b, _c, _d;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.FileHandle = void 0;
const readline_1 = __webpack_require__(521);
const kBaseFs = Symbol(`kBaseFs`);
const kFd = Symbol(`kFd`);
const kClosePromise = Symbol(`kClosePromise`);
const kCloseResolve = Symbol(`kCloseResolve`);
const kCloseReject = Symbol(`kCloseReject`);
const kRefs = Symbol(`kRefs`);
const kRef = Symbol(`kRef`);
const kUnref = Symbol(`kUnref`);
class FileHandle {
    constructor(fd, baseFs) {
        this[_a] = 1;
        this[_b] = undefined;
        this[_c] = undefined;
        this[_d] = undefined;
        this[kBaseFs] = baseFs;
        this[kFd] = fd;
    }
    get fd() {
        return this[kFd];
    }
    async appendFile(data, options) {
        var _e;
        try {
            this[kRef](this.appendFile);
            const encoding = (_e = (typeof options === `string` ? options : options === null || options === void 0 ? void 0 : options.encoding)) !== null && _e !== void 0 ? _e : undefined;
            return await this[kBaseFs].appendFilePromise(this.fd, data, encoding ? { encoding } : undefined);
        }
        finally {
            this[kUnref]();
        }
    }
    async chown(uid, gid) {
        try {
            this[kRef](this.chown);
            return await this[kBaseFs].fchownPromise(this.fd, uid, gid);
        }
        finally {
            this[kUnref]();
        }
    }
    async chmod(mode) {
        try {
            this[kRef](this.chmod);
            return await this[kBaseFs].fchmodPromise(this.fd, mode);
        }
        finally {
            this[kUnref]();
        }
    }
    createReadStream(options) {
        return this[kBaseFs].createReadStream(null, { ...options, fd: this.fd });
    }
    createWriteStream(options) {
        return this[kBaseFs].createWriteStream(null, { ...options, fd: this.fd });
    }
    // FIXME: Missing FakeFS version
    datasync() {
        throw new Error(`Method not implemented.`);
    }
    // FIXME: Missing FakeFS version
    sync() {
        throw new Error(`Method not implemented.`);
    }
    async read(bufferOrOptions, offset, length, position) {
        var _e, _f, _g;
        try {
            this[kRef](this.read);
            let buffer;
            if (!Buffer.isBuffer(bufferOrOptions)) {
                bufferOrOptions !== null && bufferOrOptions !== void 0 ? bufferOrOptions : (bufferOrOptions = {});
                buffer = (_e = bufferOrOptions.buffer) !== null && _e !== void 0 ? _e : Buffer.alloc(16384);
                offset = bufferOrOptions.offset || 0;
                length = (_f = bufferOrOptions.length) !== null && _f !== void 0 ? _f : buffer.byteLength;
                position = (_g = bufferOrOptions.position) !== null && _g !== void 0 ? _g : null;
            }
            else {
                buffer = bufferOrOptions;
            }
            offset !== null && offset !== void 0 ? offset : (offset = 0);
            length !== null && length !== void 0 ? length : (length = 0);
            if (length === 0) {
                return {
                    bytesRead: length,
                    buffer,
                };
            }
            const bytesRead = await this[kBaseFs].readPromise(this.fd, buffer, offset, length, position);
            return {
                bytesRead,
                buffer,
            };
        }
        finally {
            this[kUnref]();
        }
    }
    async readFile(options) {
        var _e;
        try {
            this[kRef](this.readFile);
            const encoding = (_e = (typeof options === `string` ? options : options === null || options === void 0 ? void 0 : options.encoding)) !== null && _e !== void 0 ? _e : undefined;
            return await this[kBaseFs].readFilePromise(this.fd, encoding);
        }
        finally {
            this[kUnref]();
        }
    }
    readLines(options) {
        return (0, readline_1.createInterface)({
            input: this.createReadStream(options),
            crlfDelay: Infinity,
        });
    }
    async stat(opts) {
        try {
            this[kRef](this.stat);
            return await this[kBaseFs].fstatPromise(this.fd, opts);
        }
        finally {
            this[kUnref]();
        }
    }
    async truncate(len) {
        try {
            this[kRef](this.truncate);
            return await this[kBaseFs].ftruncatePromise(this.fd, len);
        }
        finally {
            this[kUnref]();
        }
    }
    // FIXME: Missing FakeFS version
    utimes(atime, mtime) {
        throw new Error(`Method not implemented.`);
    }
    async writeFile(data, options) {
        var _e;
        try {
            this[kRef](this.writeFile);
            const encoding = (_e = (typeof options === `string` ? options : options === null || options === void 0 ? void 0 : options.encoding)) !== null && _e !== void 0 ? _e : undefined;
            await this[kBaseFs].writeFilePromise(this.fd, data, encoding);
        }
        finally {
            this[kUnref]();
        }
    }
    async write(...args) {
        try {
            this[kRef](this.write);
            if (ArrayBuffer.isView(args[0])) {
                const [buffer, offset, length, position] = args;
                const bytesWritten = await this[kBaseFs].writePromise(this.fd, buffer, offset !== null && offset !== void 0 ? offset : undefined, length !== null && length !== void 0 ? length : undefined, position !== null && position !== void 0 ? position : undefined);
                return { bytesWritten, buffer };
            }
            else {
                const [data, position, encoding] = args;
                // @ts-expect-error - FIXME: Types/implementation need to be updated in FakeFS
                const bytesWritten = await this[kBaseFs].writePromise(this.fd, data, position, encoding);
                return { bytesWritten, buffer: data };
            }
        }
        finally {
            this[kUnref]();
        }
    }
    // TODO: Use writev from FakeFS when that is implemented
    async writev(buffers, position) {
        try {
            this[kRef](this.writev);
            let bytesWritten = 0;
            if (typeof position !== `undefined`) {
                for (const buffer of buffers) {
                    const writeResult = await this.write(buffer, undefined, undefined, position);
                    bytesWritten += writeResult.bytesWritten;
                    position += writeResult.bytesWritten;
                }
            }
            else {
                for (const buffer of buffers) {
                    const writeResult = await this.write(buffer);
                    bytesWritten += writeResult.bytesWritten;
                }
            }
            return {
                buffers,
                bytesWritten,
            };
        }
        finally {
            this[kUnref]();
        }
    }
    // FIXME: Missing FakeFS version
    readv(buffers, position) {
        throw new Error(`Method not implemented.`);
    }
    close() {
        if (this[kFd] === -1)
            return Promise.resolve();
        if (this[kClosePromise])
            return this[kClosePromise];
        this[kRefs]--;
        if (this[kRefs] === 0) {
            const fd = this[kFd];
            this[kFd] = -1;
            this[kClosePromise] = this[kBaseFs].closePromise(fd).finally(() => {
                this[kClosePromise] = undefined;
            });
        }
        else {
            this[kClosePromise] =
                new Promise((resolve, reject) => {
                    this[kCloseResolve] = resolve;
                    this[kCloseReject] = reject;
                }).finally(() => {
                    this[kClosePromise] = undefined;
                    this[kCloseReject] = undefined;
                    this[kCloseResolve] = undefined;
                });
        }
        return this[kClosePromise];
    }
    [(_a = kRefs, _b = kClosePromise, _c = kCloseResolve, _d = kCloseReject, kRef)](caller) {
        if (this[kFd] === -1) {
            const err = new Error(`file closed`);
            err.code = `EBADF`;
            err.syscall = caller.name;
            throw err;
        }
        this[kRefs]++;
    }
    [kUnref]() {
        this[kRefs]--;
        if (this[kRefs] === 0) {
            const fd = this[kFd];
            this[kFd] = -1;
            this[kBaseFs].closePromise(fd).then(this[kCloseResolve], this[kCloseReject]);
        }
    }
}
exports.FileHandle = FileHandle;


/***/ }),

/***/ 781:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.extendFs = exports.patchFs = void 0;
const util_1 = __webpack_require__(837);
const NodePathFS_1 = __webpack_require__(732);
const FileHandle_1 = __webpack_require__(893);
const SYNC_IMPLEMENTATIONS = new Set([
    `accessSync`,
    `appendFileSync`,
    `createReadStream`,
    `createWriteStream`,
    `chmodSync`,
    `fchmodSync`,
    `chownSync`,
    `fchownSync`,
    `closeSync`,
    `copyFileSync`,
    `linkSync`,
    `lstatSync`,
    `fstatSync`,
    `lutimesSync`,
    `mkdirSync`,
    `openSync`,
    `opendirSync`,
    `readlinkSync`,
    `readFileSync`,
    `readdirSync`,
    `readlinkSync`,
    `realpathSync`,
    `renameSync`,
    `rmdirSync`,
    `statSync`,
    `symlinkSync`,
    `truncateSync`,
    `ftruncateSync`,
    `unlinkSync`,
    `unwatchFile`,
    `utimesSync`,
    `watch`,
    `watchFile`,
    `writeFileSync`,
    `writeSync`,
]);
const ASYNC_IMPLEMENTATIONS = new Set([
    `accessPromise`,
    `appendFilePromise`,
    `fchmodPromise`,
    `chmodPromise`,
    `fchownPromise`,
    `chownPromise`,
    `closePromise`,
    `copyFilePromise`,
    `linkPromise`,
    `fstatPromise`,
    `lstatPromise`,
    `lutimesPromise`,
    `mkdirPromise`,
    `openPromise`,
    `opendirPromise`,
    `readdirPromise`,
    `realpathPromise`,
    `readFilePromise`,
    `readdirPromise`,
    `readlinkPromise`,
    `renamePromise`,
    `rmdirPromise`,
    `statPromise`,
    `symlinkPromise`,
    `truncatePromise`,
    `ftruncatePromise`,
    `unlinkPromise`,
    `utimesPromise`,
    `writeFilePromise`,
    `writeSync`,
]);
//#endregion
function patchFs(patchedFs, fakeFs) {
    // We wrap the `fakeFs` with a `NodePathFS` to add support for all path types supported by Node
    fakeFs = new NodePathFS_1.NodePathFS(fakeFs);
    const setupFn = (target, name, replacement) => {
        const orig = target[name];
        target[name] = replacement;
        // Preserve any util.promisify implementations
        if (typeof (orig === null || orig === void 0 ? void 0 : orig[util_1.promisify.custom]) !== `undefined`) {
            replacement[util_1.promisify.custom] = orig[util_1.promisify.custom];
        }
    };
    /** Callback implementations */
    {
        setupFn(patchedFs, `exists`, (p, ...args) => {
            const hasCallback = typeof args[args.length - 1] === `function`;
            const callback = hasCallback ? args.pop() : () => { };
            process.nextTick(() => {
                fakeFs.existsPromise(p).then(exists => {
                    callback(exists);
                }, () => {
                    callback(false);
                });
            });
        });
        // Adapted from https://github.com/nodejs/node/blob/e5c1fd7a2a1801fd75bdde23b260488e85453eb2/lib/fs.js#L603-L667
        setupFn(patchedFs, `read`, (...args) => {
            let [fd, buffer, offset, length, position, callback] = args;
            if (args.length <= 3) {
                // Assume fs.read(fd, options, callback)
                let options = {};
                if (args.length < 3) {
                    // This is fs.read(fd, callback)
                    callback = args[1];
                }
                else {
                    // This is fs.read(fd, {}, callback)
                    options = args[1];
                    callback = args[2];
                }
                ({
                    buffer = Buffer.alloc(16384),
                    offset = 0,
                    length = buffer.byteLength,
                    position,
                } = options);
            }
            if (offset == null)
                offset = 0;
            length |= 0;
            if (length === 0) {
                process.nextTick(() => {
                    callback(null, 0, buffer);
                });
                return;
            }
            if (position == null)
                position = -1;
            process.nextTick(() => {
                fakeFs.readPromise(fd, buffer, offset, length, position).then(bytesRead => {
                    callback(null, bytesRead, buffer);
                }, error => {
                    // https://github.com/nodejs/node/blob/1317252dfe8824fd9cfee125d2aaa94004db2f3b/lib/fs.js#L655-L658
                    // Known issue: bytesRead could theoretically be > than 0, but we currently always return 0
                    callback(error, 0, buffer);
                });
            });
        });
        for (const fnName of ASYNC_IMPLEMENTATIONS) {
            const origName = fnName.replace(/Promise$/, ``);
            if (typeof patchedFs[origName] === `undefined`)
                continue;
            const fakeImpl = fakeFs[fnName];
            if (typeof fakeImpl === `undefined`)
                continue;
            const wrapper = (...args) => {
                const hasCallback = typeof args[args.length - 1] === `function`;
                const callback = hasCallback ? args.pop() : () => { };
                process.nextTick(() => {
                    fakeImpl.apply(fakeFs, args).then((result) => {
                        callback(null, result);
                    }, (error) => {
                        callback(error);
                    });
                });
            };
            setupFn(patchedFs, origName, wrapper);
        }
        patchedFs.realpath.native = patchedFs.realpath;
    }
    /** Sync implementations */
    {
        setupFn(patchedFs, `existsSync`, (p) => {
            try {
                return fakeFs.existsSync(p);
            }
            catch (error) {
                return false;
            }
        });
        // Adapted from https://github.com/nodejs/node/blob/e5c1fd7a2a1801fd75bdde23b260488e85453eb2/lib/fs.js#L684-L725
        setupFn(patchedFs, `readSync`, (...args) => {
            let [fd, buffer, offset, length, position] = args;
            if (args.length <= 3) {
                // Assume fs.read(fd, buffer, options)
                const options = args[2] || {};
                ({ offset = 0, length = buffer.byteLength, position } = options);
            }
            if (offset == null)
                offset = 0;
            length |= 0;
            if (length === 0)
                return 0;
            if (position == null)
                position = -1;
            return fakeFs.readSync(fd, buffer, offset, length, position);
        });
        for (const fnName of SYNC_IMPLEMENTATIONS) {
            const origName = fnName;
            if (typeof patchedFs[origName] === `undefined`)
                continue;
            const fakeImpl = fakeFs[fnName];
            if (typeof fakeImpl === `undefined`)
                continue;
            setupFn(patchedFs, origName, fakeImpl.bind(fakeFs));
        }
        patchedFs.realpathSync.native = patchedFs.realpathSync;
    }
    /** Promise implementations */
    {
        // `fs.promises` is a getter that returns a reference to require(`fs/promises`),
        // so we can just patch `fs.promises` and both will be updated
        const patchedFsPromises = patchedFs.promises;
        // `fs.promises.exists` doesn't exist
        for (const fnName of ASYNC_IMPLEMENTATIONS) {
            const origName = fnName.replace(/Promise$/, ``);
            if (typeof patchedFsPromises[origName] === `undefined`)
                continue;
            const fakeImpl = fakeFs[fnName];
            if (typeof fakeImpl === `undefined`)
                continue;
            // Open is a bit particular with fs.promises: it returns a file handle
            // instance instead of the traditional file descriptor number
            if (fnName === `open`)
                continue;
            setupFn(patchedFsPromises, origName, (pathLike, ...args) => {
                if (pathLike instanceof FileHandle_1.FileHandle) {
                    return pathLike[origName].apply(pathLike, args);
                }
                else {
                    return fakeImpl.call(fakeFs, pathLike, ...args);
                }
            });
        }
        setupFn(patchedFsPromises, `open`, async (...args) => {
            // @ts-expect-error
            const fd = await fakeFs.openPromise(...args);
            return new FileHandle_1.FileHandle(fd, fakeFs);
        });
        // `fs.promises.realpath` doesn't have a `native` property
    }
    /** util.promisify implementations */
    {
        // TODO add promisified `fs.readv` and `fs.writev`, once they are implemented
        // Override the promisified versions of `fs.read` and `fs.write` to return an object as per
        // https://github.com/nodejs/node/blob/dc79f3f37caf6f25b8efee4623bec31e2c20f595/lib/fs.js#L559-L560
        // and
        // https://github.com/nodejs/node/blob/dc79f3f37caf6f25b8efee4623bec31e2c20f595/lib/fs.js#L690-L691
        // and
        // https://github.com/nodejs/node/blob/ba684805b6c0eded76e5cd89ee00328ac7a59365/lib/internal/util.js#L293
        // @ts-expect-error
        patchedFs.read[util_1.promisify.custom] = async (fd, buffer, ...args) => {
            const res = fakeFs.readPromise(fd, buffer, ...args);
            return { bytesRead: await res, buffer };
        };
        // @ts-expect-error
        patchedFs.write[util_1.promisify.custom] = async (fd, buffer, ...args) => {
            const res = fakeFs.writePromise(fd, buffer, ...args);
            return { bytesWritten: await res, buffer };
        };
    }
}
exports.patchFs = patchFs;
function extendFs(realFs, fakeFs) {
    const patchedFs = Object.create(realFs);
    patchFs(patchedFs, fakeFs);
    return patchedFs;
}
exports.extendFs = extendFs;


/***/ }),

/***/ 905:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.toFilename = exports.convertPath = exports.ppath = exports.npath = exports.Filename = exports.PortablePath = void 0;
const tslib_1 = __webpack_require__(177);
const path_1 = tslib_1.__importDefault(__webpack_require__(17));
var PathType;
(function (PathType) {
    PathType[PathType["File"] = 0] = "File";
    PathType[PathType["Portable"] = 1] = "Portable";
    PathType[PathType["Native"] = 2] = "Native";
})(PathType || (PathType = {}));
exports.PortablePath = {
    root: `/`,
    dot: `.`,
    parent: `..`,
};
exports.Filename = {
    home: `~`,
    nodeModules: `node_modules`,
    manifest: `package.json`,
    lockfile: `yarn.lock`,
    virtual: `__virtual__`,
    /**
     * @deprecated
     */
    pnpJs: `.pnp.js`,
    pnpCjs: `.pnp.cjs`,
    pnpData: `.pnp.data.json`,
    pnpEsmLoader: `.pnp.loader.mjs`,
    rc: `.yarnrc.yml`,
};
exports.npath = Object.create(path_1.default);
exports.ppath = Object.create(path_1.default.posix);
exports.npath.cwd = () => process.cwd();
exports.ppath.cwd = () => toPortablePath(process.cwd());
exports.ppath.resolve = (...segments) => {
    if (segments.length > 0 && exports.ppath.isAbsolute(segments[0])) {
        return path_1.default.posix.resolve(...segments);
    }
    else {
        return path_1.default.posix.resolve(exports.ppath.cwd(), ...segments);
    }
};
const contains = function (pathUtils, from, to) {
    from = pathUtils.normalize(from);
    to = pathUtils.normalize(to);
    if (from === to)
        return `.`;
    if (!from.endsWith(pathUtils.sep))
        from = (from + pathUtils.sep);
    if (to.startsWith(from)) {
        return to.slice(from.length);
    }
    else {
        return null;
    }
};
exports.npath.fromPortablePath = fromPortablePath;
exports.npath.toPortablePath = toPortablePath;
exports.npath.contains = (from, to) => contains(exports.npath, from, to);
exports.ppath.contains = (from, to) => contains(exports.ppath, from, to);
const WINDOWS_PATH_REGEXP = /^([a-zA-Z]:.*)$/;
const UNC_WINDOWS_PATH_REGEXP = /^\/\/(\.\/)?(.*)$/;
const PORTABLE_PATH_REGEXP = /^\/([a-zA-Z]:.*)$/;
const UNC_PORTABLE_PATH_REGEXP = /^\/unc\/(\.dot\/)?(.*)$/;
// Path should look like "/N:/berry/scripts/plugin-pack.js"
// And transform to "N:\berry\scripts\plugin-pack.js"
function fromPortablePath(p) {
    if (process.platform !== `win32`)
        return p;
    let portablePathMatch, uncPortablePathMatch;
    if ((portablePathMatch = p.match(PORTABLE_PATH_REGEXP)))
        p = portablePathMatch[1];
    else if ((uncPortablePathMatch = p.match(UNC_PORTABLE_PATH_REGEXP)))
        p = `\\\\${uncPortablePathMatch[1] ? `.\\` : ``}${uncPortablePathMatch[2]}`;
    else
        return p;
    return p.replace(/\//g, `\\`);
}
// Path should look like "N:/berry/scripts/plugin-pack.js"
// And transform to "/N:/berry/scripts/plugin-pack.js"
function toPortablePath(p) {
    if (process.platform !== `win32`)
        return p;
    p = p.replace(/\\/g, `/`);
    let windowsPathMatch, uncWindowsPathMatch;
    if ((windowsPathMatch = p.match(WINDOWS_PATH_REGEXP)))
        p = `/${windowsPathMatch[1]}`;
    else if ((uncWindowsPathMatch = p.match(UNC_WINDOWS_PATH_REGEXP)))
        p = `/unc/${uncWindowsPathMatch[1] ? `.dot/` : ``}${uncWindowsPathMatch[2]}`;
    return p;
}
function convertPath(targetPathUtils, sourcePath) {
    return (targetPathUtils === exports.npath ? fromPortablePath(sourcePath) : toPortablePath(sourcePath));
}
exports.convertPath = convertPath;
function toFilename(filename) {
    if (exports.npath.parse(filename).dir !== `` || exports.ppath.parse(filename).dir !== ``)
        throw new Error(`Invalid filename: "${filename}"`);
    return filename;
}
exports.toFilename = toFilename;


/***/ }),

/***/ 64:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.areStatsEqual = exports.convertToBigIntStats = exports.clearStats = exports.makeEmptyStats = exports.makeDefaultStats = exports.BigIntStatsEntry = exports.StatEntry = exports.DirEntry = exports.DEFAULT_MODE = void 0;
const tslib_1 = __webpack_require__(177);
const nodeUtils = tslib_1.__importStar(__webpack_require__(837));
const constants_1 = __webpack_require__(78);
exports.DEFAULT_MODE = constants_1.S_IFREG | 0o644;
class DirEntry {
    constructor() {
        this.name = ``;
        this.mode = 0;
    }
    isBlockDevice() {
        return false;
    }
    isCharacterDevice() {
        return false;
    }
    isDirectory() {
        return (this.mode & constants_1.S_IFMT) === constants_1.S_IFDIR;
    }
    isFIFO() {
        return false;
    }
    isFile() {
        return (this.mode & constants_1.S_IFMT) === constants_1.S_IFREG;
    }
    isSocket() {
        return false;
    }
    isSymbolicLink() {
        return (this.mode & constants_1.S_IFMT) === constants_1.S_IFLNK;
    }
}
exports.DirEntry = DirEntry;
class StatEntry {
    constructor() {
        this.uid = 0;
        this.gid = 0;
        this.size = 0;
        this.blksize = 0;
        this.atimeMs = 0;
        this.mtimeMs = 0;
        this.ctimeMs = 0;
        this.birthtimeMs = 0;
        this.atime = new Date(0);
        this.mtime = new Date(0);
        this.ctime = new Date(0);
        this.birthtime = new Date(0);
        this.dev = 0;
        this.ino = 0;
        this.mode = exports.DEFAULT_MODE;
        this.nlink = 1;
        this.rdev = 0;
        this.blocks = 1;
    }
    isBlockDevice() {
        return false;
    }
    isCharacterDevice() {
        return false;
    }
    isDirectory() {
        return (this.mode & constants_1.S_IFMT) === constants_1.S_IFDIR;
    }
    isFIFO() {
        return false;
    }
    isFile() {
        return (this.mode & constants_1.S_IFMT) === constants_1.S_IFREG;
    }
    isSocket() {
        return false;
    }
    isSymbolicLink() {
        return (this.mode & constants_1.S_IFMT) === constants_1.S_IFLNK;
    }
}
exports.StatEntry = StatEntry;
class BigIntStatsEntry {
    constructor() {
        this.uid = BigInt(0);
        this.gid = BigInt(0);
        this.size = BigInt(0);
        this.blksize = BigInt(0);
        this.atimeMs = BigInt(0);
        this.mtimeMs = BigInt(0);
        this.ctimeMs = BigInt(0);
        this.birthtimeMs = BigInt(0);
        this.atimeNs = BigInt(0);
        this.mtimeNs = BigInt(0);
        this.ctimeNs = BigInt(0);
        this.birthtimeNs = BigInt(0);
        this.atime = new Date(0);
        this.mtime = new Date(0);
        this.ctime = new Date(0);
        this.birthtime = new Date(0);
        this.dev = BigInt(0);
        this.ino = BigInt(0);
        this.mode = BigInt(exports.DEFAULT_MODE);
        this.nlink = BigInt(1);
        this.rdev = BigInt(0);
        this.blocks = BigInt(1);
    }
    isBlockDevice() {
        return false;
    }
    isCharacterDevice() {
        return false;
    }
    isDirectory() {
        return (this.mode & BigInt(constants_1.S_IFMT)) === BigInt(constants_1.S_IFDIR);
    }
    isFIFO() {
        return false;
    }
    isFile() {
        return (this.mode & BigInt(constants_1.S_IFMT)) === BigInt(constants_1.S_IFREG);
    }
    isSocket() {
        return false;
    }
    isSymbolicLink() {
        return (this.mode & BigInt(constants_1.S_IFMT)) === BigInt(constants_1.S_IFLNK);
    }
}
exports.BigIntStatsEntry = BigIntStatsEntry;
function makeDefaultStats() {
    return new StatEntry();
}
exports.makeDefaultStats = makeDefaultStats;
function makeEmptyStats() {
    return clearStats(makeDefaultStats());
}
exports.makeEmptyStats = makeEmptyStats;
/**
 * Mutates the provided stats object to zero it out then returns it for convenience
 */
function clearStats(stats) {
    for (const key in stats) {
        if (Object.prototype.hasOwnProperty.call(stats, key)) {
            const element = stats[key];
            if (typeof element === `number`) {
                // @ts-expect-error Typescript can't tell that stats[key] is a number
                stats[key] = 0;
            }
            else if (typeof element === `bigint`) {
                // @ts-expect-error Typescript can't tell that stats[key] is a bigint
                stats[key] = BigInt(0);
            }
            else if (nodeUtils.types.isDate(element)) {
                // @ts-expect-error Typescript can't tell that stats[key] is a bigint
                stats[key] = new Date(0);
            }
        }
    }
    return stats;
}
exports.clearStats = clearStats;
function convertToBigIntStats(stats) {
    const bigintStats = new BigIntStatsEntry();
    for (const key in stats) {
        if (Object.prototype.hasOwnProperty.call(stats, key)) {
            const element = stats[key];
            if (typeof element === `number`) {
                // @ts-expect-error Typescript isn't able to tell this is valid
                bigintStats[key] = BigInt(element);
            }
            else if (nodeUtils.types.isDate(element)) {
                // @ts-expect-error Typescript isn't able to tell this is valid
                bigintStats[key] = new Date(element);
            }
        }
    }
    bigintStats.atimeNs = bigintStats.atimeMs * BigInt(1e6);
    bigintStats.mtimeNs = bigintStats.mtimeMs * BigInt(1e6);
    bigintStats.ctimeNs = bigintStats.ctimeMs * BigInt(1e6);
    bigintStats.birthtimeNs = bigintStats.birthtimeMs * BigInt(1e6);
    return bigintStats;
}
exports.convertToBigIntStats = convertToBigIntStats;
function areStatsEqual(a, b) {
    if (a.atimeMs !== b.atimeMs)
        return false;
    if (a.birthtimeMs !== b.birthtimeMs)
        return false;
    if (a.blksize !== b.blksize)
        return false;
    if (a.blocks !== b.blocks)
        return false;
    if (a.ctimeMs !== b.ctimeMs)
        return false;
    if (a.dev !== b.dev)
        return false;
    if (a.gid !== b.gid)
        return false;
    if (a.ino !== b.ino)
        return false;
    if (a.isBlockDevice() !== b.isBlockDevice())
        return false;
    if (a.isCharacterDevice() !== b.isCharacterDevice())
        return false;
    if (a.isDirectory() !== b.isDirectory())
        return false;
    if (a.isFIFO() !== b.isFIFO())
        return false;
    if (a.isFile() !== b.isFile())
        return false;
    if (a.isSocket() !== b.isSocket())
        return false;
    if (a.isSymbolicLink() !== b.isSymbolicLink())
        return false;
    if (a.mode !== b.mode)
        return false;
    if (a.mtimeMs !== b.mtimeMs)
        return false;
    if (a.nlink !== b.nlink)
        return false;
    if (a.rdev !== b.rdev)
        return false;
    if (a.size !== b.size)
        return false;
    if (a.uid !== b.uid)
        return false;
    const aN = a;
    const bN = b;
    if (aN.atimeNs !== bN.atimeNs)
        return false;
    if (aN.mtimeNs !== bN.mtimeNs)
        return false;
    if (aN.ctimeNs !== bN.ctimeNs)
        return false;
    if (aN.birthtimeNs !== bN.birthtimeNs)
        return false;
    return true;
}
exports.areStatsEqual = areStatsEqual;


/***/ }),

/***/ 743:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.xfs = void 0;
const tslib_1 = __webpack_require__(177);
const os_1 = tslib_1.__importDefault(__webpack_require__(37));
const NodeFS_1 = __webpack_require__(843);
const path_1 = __webpack_require__(905);
function getTempName(prefix) {
    const hash = Math.ceil(Math.random() * 0x100000000).toString(16).padStart(8, `0`);
    return `${prefix}${hash}`;
}
const tmpdirs = new Set();
let tmpEnv = null;
function initTmpEnv() {
    if (tmpEnv)
        return tmpEnv;
    const tmpdir = path_1.npath.toPortablePath(os_1.default.tmpdir());
    const realTmpdir = exports.xfs.realpathSync(tmpdir);
    process.once(`exit`, () => {
        exports.xfs.rmtempSync();
    });
    return tmpEnv = {
        tmpdir,
        realTmpdir,
    };
}
exports.xfs = Object.assign(new NodeFS_1.NodeFS(), {
    detachTemp(p) {
        tmpdirs.delete(p);
    },
    mktempSync(cb) {
        const { tmpdir, realTmpdir } = initTmpEnv();
        while (true) {
            const name = getTempName(`xfs-`);
            try {
                this.mkdirSync(path_1.ppath.join(tmpdir, name));
            }
            catch (error) {
                if (error.code === `EEXIST`) {
                    continue;
                }
                else {
                    throw error;
                }
            }
            const realP = path_1.ppath.join(realTmpdir, name);
            tmpdirs.add(realP);
            if (typeof cb === `undefined`)
                return realP;
            try {
                return cb(realP);
            }
            finally {
                if (tmpdirs.has(realP)) {
                    tmpdirs.delete(realP);
                    try {
                        this.removeSync(realP);
                    }
                    catch {
                        // Too bad if there's an error
                    }
                }
            }
        }
    },
    async mktempPromise(cb) {
        const { tmpdir, realTmpdir } = initTmpEnv();
        while (true) {
            const name = getTempName(`xfs-`);
            try {
                await this.mkdirPromise(path_1.ppath.join(tmpdir, name));
            }
            catch (error) {
                if (error.code === `EEXIST`) {
                    continue;
                }
                else {
                    throw error;
                }
            }
            const realP = path_1.ppath.join(realTmpdir, name);
            tmpdirs.add(realP);
            if (typeof cb === `undefined`)
                return realP;
            try {
                return await cb(realP);
            }
            finally {
                if (tmpdirs.has(realP)) {
                    tmpdirs.delete(realP);
                    try {
                        await this.removePromise(realP);
                    }
                    catch {
                        // Too bad if there's an error
                    }
                }
            }
        }
    },
    async rmtempPromise() {
        await Promise.all(Array.from(tmpdirs.values()).map(async (p) => {
            try {
                await exports.xfs.removePromise(p, { maxRetries: 0 });
                tmpdirs.delete(p);
            }
            catch {
                // Too bad if there's an error
            }
        }));
    },
    rmtempSync() {
        for (const p of tmpdirs) {
            try {
                exports.xfs.removeSync(p);
                tmpdirs.delete(p);
            }
            catch {
                // Too bad if there's an error
            }
        }
    },
});


/***/ }),

/***/ 177:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "__assign": () => (/* binding */ __assign),
/* harmony export */   "__asyncDelegator": () => (/* binding */ __asyncDelegator),
/* harmony export */   "__asyncGenerator": () => (/* binding */ __asyncGenerator),
/* harmony export */   "__asyncValues": () => (/* binding */ __asyncValues),
/* harmony export */   "__await": () => (/* binding */ __await),
/* harmony export */   "__awaiter": () => (/* binding */ __awaiter),
/* harmony export */   "__classPrivateFieldGet": () => (/* binding */ __classPrivateFieldGet),
/* harmony export */   "__classPrivateFieldIn": () => (/* binding */ __classPrivateFieldIn),
/* harmony export */   "__classPrivateFieldSet": () => (/* binding */ __classPrivateFieldSet),
/* harmony export */   "__createBinding": () => (/* binding */ __createBinding),
/* harmony export */   "__decorate": () => (/* binding */ __decorate),
/* harmony export */   "__esDecorate": () => (/* binding */ __esDecorate),
/* harmony export */   "__exportStar": () => (/* binding */ __exportStar),
/* harmony export */   "__extends": () => (/* binding */ __extends),
/* harmony export */   "__generator": () => (/* binding */ __generator),
/* harmony export */   "__importDefault": () => (/* binding */ __importDefault),
/* harmony export */   "__importStar": () => (/* binding */ __importStar),
/* harmony export */   "__makeTemplateObject": () => (/* binding */ __makeTemplateObject),
/* harmony export */   "__metadata": () => (/* binding */ __metadata),
/* harmony export */   "__param": () => (/* binding */ __param),
/* harmony export */   "__propKey": () => (/* binding */ __propKey),
/* harmony export */   "__read": () => (/* binding */ __read),
/* harmony export */   "__rest": () => (/* binding */ __rest),
/* harmony export */   "__runInitializers": () => (/* binding */ __runInitializers),
/* harmony export */   "__setFunctionName": () => (/* binding */ __setFunctionName),
/* harmony export */   "__spread": () => (/* binding */ __spread),
/* harmony export */   "__spreadArray": () => (/* binding */ __spreadArray),
/* harmony export */   "__spreadArrays": () => (/* binding */ __spreadArrays),
/* harmony export */   "__values": () => (/* binding */ __values)
/* harmony export */ });
/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

function __extends(d, b) {
    if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var __assign = function() {
    __assign = Object.assign || function __assign(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
    }
    return __assign.apply(this, arguments);
}

function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

function __decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}

function __param(paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
}

function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.push(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.push(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};

function __runInitializers(thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};

function __propKey(x) {
    return typeof x === "symbol" ? x : "".concat(x);
};

function __setFunctionName(f, name, prefix) {
    if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
    return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};

function __metadata(metadataKey, metadataValue) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
}

var __createBinding = Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
});

function __exportStar(m, o) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}

function __values(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}

function __read(o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
}

/** @deprecated */
function __spread() {
    for (var ar = [], i = 0; i < arguments.length; i++)
        ar = ar.concat(__read(arguments[i]));
    return ar;
}

/** @deprecated */
function __spreadArrays() {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
}

function __spreadArray(to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
}

function __await(v) {
    return this instanceof __await ? (this.v = v, this) : new __await(v);
}

function __asyncGenerator(thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}

function __asyncDelegator(o) {
    var i, p;
    return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}

function __asyncValues(o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}

function __makeTemplateObject(cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};

var __setModuleDefault = Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
};

function __importStar(mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
}

function __importDefault(mod) {
    return (mod && mod.__esModule) ? mod : { default: mod };
}

function __classPrivateFieldGet(receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}

function __classPrivateFieldSet(receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}

function __classPrivateFieldIn(state, receiver) {
    if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
    return typeof state === "function" ? receiver === state : state.has(receiver);
}


/***/ }),

/***/ 154:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ZipFS = exports.LibzipError = exports.makeEmptyArchive = exports.DEFAULT_COMPRESSION_LEVEL = void 0;
const tslib_1 = __webpack_require__(240);
const fslib_1 = __webpack_require__(382);
const fslib_2 = __webpack_require__(382);
const fslib_3 = __webpack_require__(382);
const fslib_4 = __webpack_require__(382);
const fslib_5 = __webpack_require__(382);
const fslib_6 = __webpack_require__(382);
const fs_1 = __webpack_require__(147);
const stream_1 = __webpack_require__(955);
const util_1 = __webpack_require__(837);
const zlib_1 = tslib_1.__importDefault(__webpack_require__(796));
const instance_1 = __webpack_require__(309);
exports.DEFAULT_COMPRESSION_LEVEL = `mixed`;
function toUnixTimestamp(time) {
    if (typeof time === `string` && String(+time) === time)
        return +time;
    if (typeof time === `number` && Number.isFinite(time)) {
        if (time < 0) {
            return Date.now() / 1000;
        }
        else {
            return time;
        }
    }
    // convert to 123.456 UNIX timestamp
    if (util_1.types.isDate(time))
        return time.getTime() / 1000;
    throw new Error(`Invalid time`);
}
function makeEmptyArchive() {
    return Buffer.from([
        0x50, 0x4B, 0x05, 0x06,
        0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00,
        0x00, 0x00,
    ]);
}
exports.makeEmptyArchive = makeEmptyArchive;
class LibzipError extends Error {
    constructor(message, code) {
        super(message);
        this.name = `Libzip Error`;
        this.code = code;
    }
}
exports.LibzipError = LibzipError;
class ZipFS extends fslib_1.BasePortableFakeFS {
    constructor(source, opts = {}) {
        super();
        this.listings = new Map();
        this.entries = new Map();
        /**
         * A cache of indices mapped to file sources.
         * Populated by `setFileSource` calls.
         * Required for supporting read after write.
         */
        this.fileSources = new Map();
        this.fds = new Map();
        this.nextFd = 0;
        this.ready = false;
        this.readOnly = false;
        const pathOptions = opts;
        this.level = typeof pathOptions.level !== `undefined`
            ? pathOptions.level
            : exports.DEFAULT_COMPRESSION_LEVEL;
        source !== null && source !== void 0 ? source : (source = makeEmptyArchive());
        if (typeof source === `string`) {
            const { baseFs = new fslib_2.NodeFS() } = pathOptions;
            this.baseFs = baseFs;
            this.path = source;
        }
        else {
            this.path = null;
            this.baseFs = null;
        }
        if (opts.stats) {
            this.stats = opts.stats;
        }
        else {
            if (typeof source === `string`) {
                try {
                    this.stats = this.baseFs.statSync(source);
                }
                catch (error) {
                    if (error.code === `ENOENT` && pathOptions.create) {
                        this.stats = fslib_5.statUtils.makeDefaultStats();
                    }
                    else {
                        throw error;
                    }
                }
            }
            else {
                this.stats = fslib_5.statUtils.makeDefaultStats();
            }
        }
        this.libzip = (0, instance_1.getInstance)();
        const errPtr = this.libzip.malloc(4);
        try {
            let flags = 0;
            if (opts.readOnly) {
                flags |= this.libzip.ZIP_RDONLY;
                this.readOnly = true;
            }
            if (typeof source === `string`)
                source = pathOptions.create
                    ? makeEmptyArchive()
                    : this.baseFs.readFileSync(source);
            const lzSource = this.allocateUnattachedSource(source);
            try {
                this.zip = this.libzip.openFromSource(lzSource, flags, errPtr);
                this.lzSource = lzSource;
            }
            catch (error) {
                this.libzip.source.free(lzSource);
                throw error;
            }
            if (this.zip === 0) {
                const error = this.libzip.struct.errorS();
                this.libzip.error.initWithCode(error, this.libzip.getValue(errPtr, `i32`));
                throw this.makeLibzipError(error);
            }
        }
        finally {
            this.libzip.free(errPtr);
        }
        this.listings.set(fslib_6.PortablePath.root, new Set());
        const entryCount = this.libzip.getNumEntries(this.zip, 0);
        for (let t = 0; t < entryCount; ++t) {
            const raw = this.libzip.getName(this.zip, t, 0);
            if (fslib_6.ppath.isAbsolute(raw))
                continue;
            const p = fslib_6.ppath.resolve(fslib_6.PortablePath.root, raw);
            this.registerEntry(p, t);
            // If the raw path is a directory, register it
            // to prevent empty folder being skipped
            if (raw.endsWith(`/`)) {
                this.registerListing(p);
            }
        }
        this.symlinkCount = this.libzip.ext.countSymlinks(this.zip);
        if (this.symlinkCount === -1)
            throw this.makeLibzipError(this.libzip.getError(this.zip));
        this.ready = true;
    }
    makeLibzipError(error) {
        const errorCode = this.libzip.struct.errorCodeZip(error);
        const strerror = this.libzip.error.strerror(error);
        const libzipError = new LibzipError(strerror, this.libzip.errors[errorCode]);
        // This error should never come up because of the file source cache
        if (errorCode === this.libzip.errors.ZIP_ER_CHANGED)
            throw new Error(`Assertion failed: Unexpected libzip error: ${libzipError.message}`);
        return libzipError;
    }
    getExtractHint(hints) {
        for (const fileName of this.entries.keys()) {
            const ext = this.pathUtils.extname(fileName);
            if (hints.relevantExtensions.has(ext)) {
                return true;
            }
        }
        return false;
    }
    getAllFiles() {
        return Array.from(this.entries.keys());
    }
    getRealPath() {
        if (!this.path)
            throw new Error(`ZipFS don't have real paths when loaded from a buffer`);
        return this.path;
    }
    prepareClose() {
        if (!this.ready)
            throw fslib_5.errors.EBUSY(`archive closed, close`);
        (0, fslib_4.unwatchAllFiles)(this);
    }
    getBufferAndClose() {
        this.prepareClose();
        // zip_source_open on an unlink-after-write empty archive fails with "Entry has been deleted"
        if (this.entries.size === 0) {
            this.discardAndClose();
            return makeEmptyArchive();
        }
        try {
            // Prevent close from cleaning up the source
            this.libzip.source.keep(this.lzSource);
            // Close the zip archive
            if (this.libzip.close(this.zip) === -1)
                throw this.makeLibzipError(this.libzip.getError(this.zip));
            // Open the source for reading
            if (this.libzip.source.open(this.lzSource) === -1)
                throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
            // Move to the end of source
            if (this.libzip.source.seek(this.lzSource, 0, 0, this.libzip.SEEK_END) === -1)
                throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
            // Get the size of source
            const size = this.libzip.source.tell(this.lzSource);
            if (size === -1)
                throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
            // Move to the start of source
            if (this.libzip.source.seek(this.lzSource, 0, 0, this.libzip.SEEK_SET) === -1)
                throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
            const buffer = this.libzip.malloc(size);
            if (!buffer)
                throw new Error(`Couldn't allocate enough memory`);
            try {
                const rc = this.libzip.source.read(this.lzSource, buffer, size);
                if (rc === -1)
                    throw this.makeLibzipError(this.libzip.source.error(this.lzSource));
                else if (rc < size)
                    throw new Error(`Incomplete read`);
                else if (rc > size)
                    throw new Error(`Overread`);
                const memory = this.libzip.HEAPU8.subarray(buffer, buffer + size);
                return Buffer.from(memory);
            }
            finally {
                this.libzip.free(buffer);
            }
        }
        finally {
            this.libzip.source.close(this.lzSource);
            this.libzip.source.free(this.lzSource);
            this.ready = false;
        }
    }
    discardAndClose() {
        this.prepareClose();
        this.libzip.discard(this.zip);
        this.ready = false;
    }
    saveAndClose() {
        if (!this.path || !this.baseFs)
            throw new Error(`ZipFS cannot be saved and must be discarded when loaded from a buffer`);
        if (this.readOnly) {
            this.discardAndClose();
            return;
        }
        const newMode = this.baseFs.existsSync(this.path) || this.stats.mode === fslib_5.statUtils.DEFAULT_MODE
            ? undefined
            : this.stats.mode;
        this.baseFs.writeFileSync(this.path, this.getBufferAndClose(), { mode: newMode });
        this.ready = false;
    }
    resolve(p) {
        return fslib_6.ppath.resolve(fslib_6.PortablePath.root, p);
    }
    async openPromise(p, flags, mode) {
        return this.openSync(p, flags, mode);
    }
    openSync(p, flags, mode) {
        const fd = this.nextFd++;
        this.fds.set(fd, { cursor: 0, p });
        return fd;
    }
    hasOpenFileHandles() {
        return !!this.fds.size;
    }
    async opendirPromise(p, opts) {
        return this.opendirSync(p, opts);
    }
    opendirSync(p, opts = {}) {
        const resolvedP = this.resolveFilename(`opendir '${p}'`, p);
        if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOENT(`opendir '${p}'`);
        const directoryListing = this.listings.get(resolvedP);
        if (!directoryListing)
            throw fslib_5.errors.ENOTDIR(`opendir '${p}'`);
        const entries = [...directoryListing];
        const fd = this.openSync(resolvedP, `r`);
        const onClose = () => {
            this.closeSync(fd);
        };
        return (0, fslib_3.opendir)(this, resolvedP, entries, { onClose });
    }
    async readPromise(fd, buffer, offset, length, position) {
        return this.readSync(fd, buffer, offset, length, position);
    }
    readSync(fd, buffer, offset = 0, length = buffer.byteLength, position = -1) {
        const entry = this.fds.get(fd);
        if (typeof entry === `undefined`)
            throw fslib_5.errors.EBADF(`read`);
        const realPosition = position === -1 || position === null
            ? entry.cursor
            : position;
        const source = this.readFileSync(entry.p);
        source.copy(buffer, offset, realPosition, realPosition + length);
        const bytesRead = Math.max(0, Math.min(source.length - realPosition, length));
        if (position === -1 || position === null)
            entry.cursor += bytesRead;
        return bytesRead;
    }
    async writePromise(fd, buffer, offset, length, position) {
        if (typeof buffer === `string`) {
            return this.writeSync(fd, buffer, position);
        }
        else {
            return this.writeSync(fd, buffer, offset, length, position);
        }
    }
    writeSync(fd, buffer, offset, length, position) {
        const entry = this.fds.get(fd);
        if (typeof entry === `undefined`)
            throw fslib_5.errors.EBADF(`read`);
        throw new Error(`Unimplemented`);
    }
    async closePromise(fd) {
        return this.closeSync(fd);
    }
    closeSync(fd) {
        const entry = this.fds.get(fd);
        if (typeof entry === `undefined`)
            throw fslib_5.errors.EBADF(`read`);
        this.fds.delete(fd);
    }
    createReadStream(p, { encoding } = {}) {
        if (p === null)
            throw new Error(`Unimplemented`);
        const fd = this.openSync(p, `r`);
        const stream = Object.assign(new stream_1.PassThrough({
            emitClose: true,
            autoDestroy: true,
            destroy: (error, callback) => {
                clearImmediate(immediate);
                this.closeSync(fd);
                callback(error);
            },
        }), {
            close() {
                stream.destroy();
            },
            bytesRead: 0,
            path: p,
            // "This property is `true` if the underlying file has not been opened yet"
            pending: false,
        });
        const immediate = setImmediate(async () => {
            try {
                const data = await this.readFilePromise(p, encoding);
                stream.bytesRead = data.length;
                stream.end(data);
            }
            catch (error) {
                stream.destroy(error);
            }
        });
        return stream;
    }
    createWriteStream(p, { encoding } = {}) {
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`open '${p}'`);
        if (p === null)
            throw new Error(`Unimplemented`);
        const chunks = [];
        const fd = this.openSync(p, `w`);
        const stream = Object.assign(new stream_1.PassThrough({
            autoDestroy: true,
            emitClose: true,
            destroy: (error, callback) => {
                try {
                    if (error) {
                        callback(error);
                    }
                    else {
                        this.writeFileSync(p, Buffer.concat(chunks), encoding);
                        callback(null);
                    }
                }
                catch (err) {
                    callback(err);
                }
                finally {
                    this.closeSync(fd);
                }
            },
        }), {
            close() {
                stream.destroy();
            },
            bytesWritten: 0,
            path: p,
            // "This property is `true` if the underlying file has not been opened yet"
            pending: false,
        });
        stream.on(`data`, chunk => {
            const chunkBuffer = Buffer.from(chunk);
            stream.bytesWritten += chunkBuffer.length;
            chunks.push(chunkBuffer);
        });
        return stream;
    }
    async realpathPromise(p) {
        return this.realpathSync(p);
    }
    realpathSync(p) {
        const resolvedP = this.resolveFilename(`lstat '${p}'`, p);
        if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOENT(`lstat '${p}'`);
        return resolvedP;
    }
    async existsPromise(p) {
        return this.existsSync(p);
    }
    existsSync(p) {
        if (!this.ready)
            throw fslib_5.errors.EBUSY(`archive closed, existsSync '${p}'`);
        if (this.symlinkCount === 0) {
            const resolvedP = fslib_6.ppath.resolve(fslib_6.PortablePath.root, p);
            return this.entries.has(resolvedP) || this.listings.has(resolvedP);
        }
        let resolvedP;
        try {
            resolvedP = this.resolveFilename(`stat '${p}'`, p, undefined, false);
        }
        catch (error) {
            return false;
        }
        if (resolvedP === undefined)
            return false;
        return this.entries.has(resolvedP) || this.listings.has(resolvedP);
    }
    async accessPromise(p, mode) {
        return this.accessSync(p, mode);
    }
    accessSync(p, mode = fs_1.constants.F_OK) {
        const resolvedP = this.resolveFilename(`access '${p}'`, p);
        if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOENT(`access '${p}'`);
        if (this.readOnly && (mode & fs_1.constants.W_OK)) {
            throw fslib_5.errors.EROFS(`access '${p}'`);
        }
    }
    async statPromise(p, opts = { bigint: false }) {
        if (opts.bigint)
            return this.statSync(p, { bigint: true });
        return this.statSync(p);
    }
    statSync(p, opts = { bigint: false, throwIfNoEntry: true }) {
        const resolvedP = this.resolveFilename(`stat '${p}'`, p, undefined, opts.throwIfNoEntry);
        if (resolvedP === undefined)
            return undefined;
        if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) {
            if (opts.throwIfNoEntry === false)
                return undefined;
            throw fslib_5.errors.ENOENT(`stat '${p}'`);
        }
        if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOTDIR(`stat '${p}'`);
        return this.statImpl(`stat '${p}'`, resolvedP, opts);
    }
    async fstatPromise(fd, opts) {
        return this.fstatSync(fd, opts);
    }
    fstatSync(fd, opts) {
        const entry = this.fds.get(fd);
        if (typeof entry === `undefined`)
            throw fslib_5.errors.EBADF(`fstatSync`);
        const { p } = entry;
        const resolvedP = this.resolveFilename(`stat '${p}'`, p);
        if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOENT(`stat '${p}'`);
        if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOTDIR(`stat '${p}'`);
        return this.statImpl(`fstat '${p}'`, resolvedP, opts);
    }
    async lstatPromise(p, opts = { bigint: false }) {
        if (opts.bigint)
            return this.lstatSync(p, { bigint: true });
        return this.lstatSync(p);
    }
    lstatSync(p, opts = { bigint: false, throwIfNoEntry: true }) {
        const resolvedP = this.resolveFilename(`lstat '${p}'`, p, false, opts.throwIfNoEntry);
        if (resolvedP === undefined)
            return undefined;
        if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP)) {
            if (opts.throwIfNoEntry === false)
                return undefined;
            throw fslib_5.errors.ENOENT(`lstat '${p}'`);
        }
        if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOTDIR(`lstat '${p}'`);
        return this.statImpl(`lstat '${p}'`, resolvedP, opts);
    }
    statImpl(reason, p, opts = {}) {
        const entry = this.entries.get(p);
        // File, or explicit directory
        if (typeof entry !== `undefined`) {
            const stat = this.libzip.struct.statS();
            const rc = this.libzip.statIndex(this.zip, entry, 0, 0, stat);
            if (rc === -1)
                throw this.makeLibzipError(this.libzip.getError(this.zip));
            const uid = this.stats.uid;
            const gid = this.stats.gid;
            const size = (this.libzip.struct.statSize(stat) >>> 0);
            const blksize = 512;
            const blocks = Math.ceil(size / blksize);
            const mtimeMs = (this.libzip.struct.statMtime(stat) >>> 0) * 1000;
            const atimeMs = mtimeMs;
            const birthtimeMs = mtimeMs;
            const ctimeMs = mtimeMs;
            const atime = new Date(atimeMs);
            const birthtime = new Date(birthtimeMs);
            const ctime = new Date(ctimeMs);
            const mtime = new Date(mtimeMs);
            const type = this.listings.has(p)
                ? fs_1.constants.S_IFDIR
                : this.isSymbolicLink(entry)
                    ? fs_1.constants.S_IFLNK
                    : fs_1.constants.S_IFREG;
            const defaultMode = type === fs_1.constants.S_IFDIR
                ? 0o755
                : 0o644;
            const mode = type | (this.getUnixMode(entry, defaultMode) & 0o777);
            const crc = this.libzip.struct.statCrc(stat);
            const statInstance = Object.assign(new fslib_5.statUtils.StatEntry(), { uid, gid, size, blksize, blocks, atime, birthtime, ctime, mtime, atimeMs, birthtimeMs, ctimeMs, mtimeMs, mode, crc });
            return opts.bigint === true ? fslib_5.statUtils.convertToBigIntStats(statInstance) : statInstance;
        }
        // Implicit directory
        if (this.listings.has(p)) {
            const uid = this.stats.uid;
            const gid = this.stats.gid;
            const size = 0;
            const blksize = 512;
            const blocks = 0;
            const atimeMs = this.stats.mtimeMs;
            const birthtimeMs = this.stats.mtimeMs;
            const ctimeMs = this.stats.mtimeMs;
            const mtimeMs = this.stats.mtimeMs;
            const atime = new Date(atimeMs);
            const birthtime = new Date(birthtimeMs);
            const ctime = new Date(ctimeMs);
            const mtime = new Date(mtimeMs);
            const mode = fs_1.constants.S_IFDIR | 0o755;
            const crc = 0;
            const statInstance = Object.assign(new fslib_5.statUtils.StatEntry(), { uid, gid, size, blksize, blocks, atime, birthtime, ctime, mtime, atimeMs, birthtimeMs, ctimeMs, mtimeMs, mode, crc });
            return opts.bigint === true ? fslib_5.statUtils.convertToBigIntStats(statInstance) : statInstance;
        }
        throw new Error(`Unreachable`);
    }
    getUnixMode(index, defaultMode) {
        const rc = this.libzip.file.getExternalAttributes(this.zip, index, 0, 0, this.libzip.uint08S, this.libzip.uint32S);
        if (rc === -1)
            throw this.makeLibzipError(this.libzip.getError(this.zip));
        const opsys = this.libzip.getValue(this.libzip.uint08S, `i8`) >>> 0;
        if (opsys !== this.libzip.ZIP_OPSYS_UNIX)
            return defaultMode;
        return this.libzip.getValue(this.libzip.uint32S, `i32`) >>> 16;
    }
    registerListing(p) {
        const existingListing = this.listings.get(p);
        if (existingListing)
            return existingListing;
        const parentListing = this.registerListing(fslib_6.ppath.dirname(p));
        parentListing.add(fslib_6.ppath.basename(p));
        const newListing = new Set();
        this.listings.set(p, newListing);
        return newListing;
    }
    registerEntry(p, index) {
        const parentListing = this.registerListing(fslib_6.ppath.dirname(p));
        parentListing.add(fslib_6.ppath.basename(p));
        this.entries.set(p, index);
    }
    unregisterListing(p) {
        this.listings.delete(p);
        const parentListing = this.listings.get(fslib_6.ppath.dirname(p));
        parentListing === null || parentListing === void 0 ? void 0 : parentListing.delete(fslib_6.ppath.basename(p));
    }
    unregisterEntry(p) {
        this.unregisterListing(p);
        const entry = this.entries.get(p);
        this.entries.delete(p);
        if (typeof entry === `undefined`)
            return;
        this.fileSources.delete(entry);
        if (this.isSymbolicLink(entry)) {
            this.symlinkCount--;
        }
    }
    deleteEntry(p, index) {
        this.unregisterEntry(p);
        const rc = this.libzip.delete(this.zip, index);
        if (rc === -1) {
            throw this.makeLibzipError(this.libzip.getError(this.zip));
        }
    }
    resolveFilename(reason, p, resolveLastComponent = true, throwIfNoEntry = true) {
        if (!this.ready)
            throw fslib_5.errors.EBUSY(`archive closed, ${reason}`);
        let resolvedP = fslib_6.ppath.resolve(fslib_6.PortablePath.root, p);
        if (resolvedP === `/`)
            return fslib_6.PortablePath.root;
        const fileIndex = this.entries.get(resolvedP);
        if (resolveLastComponent && fileIndex !== undefined) {
            if (this.symlinkCount !== 0 && this.isSymbolicLink(fileIndex)) {
                const target = this.getFileSource(fileIndex).toString();
                return this.resolveFilename(reason, fslib_6.ppath.resolve(fslib_6.ppath.dirname(resolvedP), target), true, throwIfNoEntry);
            }
            else {
                return resolvedP;
            }
        }
        while (true) {
            const parentP = this.resolveFilename(reason, fslib_6.ppath.dirname(resolvedP), true, throwIfNoEntry);
            if (parentP === undefined)
                return parentP;
            const isDir = this.listings.has(parentP);
            const doesExist = this.entries.has(parentP);
            if (!isDir && !doesExist) {
                if (throwIfNoEntry === false)
                    return undefined;
                throw fslib_5.errors.ENOENT(reason);
            }
            if (!isDir)
                throw fslib_5.errors.ENOTDIR(reason);
            resolvedP = fslib_6.ppath.resolve(parentP, fslib_6.ppath.basename(resolvedP));
            if (!resolveLastComponent || this.symlinkCount === 0)
                break;
            const index = this.libzip.name.locate(this.zip, resolvedP.slice(1), 0);
            if (index === -1)
                break;
            if (this.isSymbolicLink(index)) {
                const target = this.getFileSource(index).toString();
                resolvedP = fslib_6.ppath.resolve(fslib_6.ppath.dirname(resolvedP), target);
            }
            else {
                break;
            }
        }
        return resolvedP;
    }
    allocateBuffer(content) {
        if (!Buffer.isBuffer(content))
            content = Buffer.from(content);
        const buffer = this.libzip.malloc(content.byteLength);
        if (!buffer)
            throw new Error(`Couldn't allocate enough memory`);
        // Copy the file into the Emscripten heap
        const heap = new Uint8Array(this.libzip.HEAPU8.buffer, buffer, content.byteLength);
        heap.set(content);
        return { buffer, byteLength: content.byteLength };
    }
    allocateUnattachedSource(content) {
        const error = this.libzip.struct.errorS();
        const { buffer, byteLength } = this.allocateBuffer(content);
        const source = this.libzip.source.fromUnattachedBuffer(buffer, byteLength, 0, 1, error);
        if (source === 0) {
            this.libzip.free(error);
            throw this.makeLibzipError(error);
        }
        return source;
    }
    allocateSource(content) {
        const { buffer, byteLength } = this.allocateBuffer(content);
        const source = this.libzip.source.fromBuffer(this.zip, buffer, byteLength, 0, 1);
        if (source === 0) {
            this.libzip.free(buffer);
            throw this.makeLibzipError(this.libzip.getError(this.zip));
        }
        return source;
    }
    setFileSource(p, content) {
        const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content);
        const target = fslib_6.ppath.relative(fslib_6.PortablePath.root, p);
        const lzSource = this.allocateSource(content);
        try {
            const newIndex = this.libzip.file.add(this.zip, target, lzSource, this.libzip.ZIP_FL_OVERWRITE);
            if (newIndex === -1)
                throw this.makeLibzipError(this.libzip.getError(this.zip));
            if (this.level !== `mixed`) {
                // Use store for level 0, and deflate for 1..9
                const method = this.level === 0
                    ? this.libzip.ZIP_CM_STORE
                    : this.libzip.ZIP_CM_DEFLATE;
                const rc = this.libzip.file.setCompression(this.zip, newIndex, 0, method, this.level);
                if (rc === -1) {
                    throw this.makeLibzipError(this.libzip.getError(this.zip));
                }
            }
            this.fileSources.set(newIndex, buffer);
            return newIndex;
        }
        catch (error) {
            this.libzip.source.free(lzSource);
            throw error;
        }
    }
    isSymbolicLink(index) {
        if (this.symlinkCount === 0)
            return false;
        const attrs = this.libzip.file.getExternalAttributes(this.zip, index, 0, 0, this.libzip.uint08S, this.libzip.uint32S);
        if (attrs === -1)
            throw this.makeLibzipError(this.libzip.getError(this.zip));
        const opsys = this.libzip.getValue(this.libzip.uint08S, `i8`) >>> 0;
        if (opsys !== this.libzip.ZIP_OPSYS_UNIX)
            return false;
        const attributes = this.libzip.getValue(this.libzip.uint32S, `i32`) >>> 16;
        return (attributes & fs_1.constants.S_IFMT) === fs_1.constants.S_IFLNK;
    }
    getFileSource(index, opts = { asyncDecompress: false }) {
        const cachedFileSource = this.fileSources.get(index);
        if (typeof cachedFileSource !== `undefined`)
            return cachedFileSource;
        const stat = this.libzip.struct.statS();
        const rc = this.libzip.statIndex(this.zip, index, 0, 0, stat);
        if (rc === -1)
            throw this.makeLibzipError(this.libzip.getError(this.zip));
        const size = this.libzip.struct.statCompSize(stat);
        const compressionMethod = this.libzip.struct.statCompMethod(stat);
        const buffer = this.libzip.malloc(size);
        try {
            const file = this.libzip.fopenIndex(this.zip, index, 0, this.libzip.ZIP_FL_COMPRESSED);
            if (file === 0)
                throw this.makeLibzipError(this.libzip.getError(this.zip));
            try {
                const rc = this.libzip.fread(file, buffer, size, 0);
                if (rc === -1)
                    throw this.makeLibzipError(this.libzip.file.getError(file));
                else if (rc < size)
                    throw new Error(`Incomplete read`);
                else if (rc > size)
                    throw new Error(`Overread`);
                const memory = this.libzip.HEAPU8.subarray(buffer, buffer + size);
                const data = Buffer.from(memory);
                if (compressionMethod === 0) {
                    this.fileSources.set(index, data);
                    return data;
                }
                else if (opts.asyncDecompress) {
                    return new Promise((resolve, reject) => {
                        zlib_1.default.inflateRaw(data, (error, result) => {
                            if (error) {
                                reject(error);
                            }
                            else {
                                this.fileSources.set(index, result);
                                resolve(result);
                            }
                        });
                    });
                }
                else {
                    const decompressedData = zlib_1.default.inflateRawSync(data);
                    this.fileSources.set(index, decompressedData);
                    return decompressedData;
                }
            }
            finally {
                this.libzip.fclose(file);
            }
        }
        finally {
            this.libzip.free(buffer);
        }
    }
    async fchmodPromise(fd, mask) {
        return this.chmodPromise(this.fdToPath(fd, `fchmod`), mask);
    }
    fchmodSync(fd, mask) {
        return this.chmodSync(this.fdToPath(fd, `fchmodSync`), mask);
    }
    async chmodPromise(p, mask) {
        return this.chmodSync(p, mask);
    }
    chmodSync(p, mask) {
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`chmod '${p}'`);
        // We don't allow to make the extracted entries group-writable
        mask &= 0o755;
        const resolvedP = this.resolveFilename(`chmod '${p}'`, p, false);
        const entry = this.entries.get(resolvedP);
        if (typeof entry === `undefined`)
            throw new Error(`Assertion failed: The entry should have been registered (${resolvedP})`);
        const oldMod = this.getUnixMode(entry, fs_1.constants.S_IFREG | 0o000);
        const newMod = oldMod & (~0o777) | mask;
        const rc = this.libzip.file.setExternalAttributes(this.zip, entry, 0, 0, this.libzip.ZIP_OPSYS_UNIX, newMod << 16);
        if (rc === -1) {
            throw this.makeLibzipError(this.libzip.getError(this.zip));
        }
    }
    async fchownPromise(fd, uid, gid) {
        return this.chownPromise(this.fdToPath(fd, `fchown`), uid, gid);
    }
    fchownSync(fd, uid, gid) {
        return this.chownSync(this.fdToPath(fd, `fchownSync`), uid, gid);
    }
    async chownPromise(p, uid, gid) {
        return this.chownSync(p, uid, gid);
    }
    chownSync(p, uid, gid) {
        throw new Error(`Unimplemented`);
    }
    async renamePromise(oldP, newP) {
        return this.renameSync(oldP, newP);
    }
    renameSync(oldP, newP) {
        throw new Error(`Unimplemented`);
    }
    async copyFilePromise(sourceP, destP, flags) {
        const { indexSource, indexDest, resolvedDestP } = this.prepareCopyFile(sourceP, destP, flags);
        const source = await this.getFileSource(indexSource, { asyncDecompress: true });
        const newIndex = this.setFileSource(resolvedDestP, source);
        if (newIndex !== indexDest) {
            this.registerEntry(resolvedDestP, newIndex);
        }
    }
    copyFileSync(sourceP, destP, flags = 0) {
        const { indexSource, indexDest, resolvedDestP } = this.prepareCopyFile(sourceP, destP, flags);
        const source = this.getFileSource(indexSource);
        const newIndex = this.setFileSource(resolvedDestP, source);
        if (newIndex !== indexDest) {
            this.registerEntry(resolvedDestP, newIndex);
        }
    }
    prepareCopyFile(sourceP, destP, flags = 0) {
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`copyfile '${sourceP} -> '${destP}'`);
        if ((flags & fs_1.constants.COPYFILE_FICLONE_FORCE) !== 0)
            throw fslib_5.errors.ENOSYS(`unsupported clone operation`, `copyfile '${sourceP}' -> ${destP}'`);
        const resolvedSourceP = this.resolveFilename(`copyfile '${sourceP} -> ${destP}'`, sourceP);
        const indexSource = this.entries.get(resolvedSourceP);
        if (typeof indexSource === `undefined`)
            throw fslib_5.errors.EINVAL(`copyfile '${sourceP}' -> '${destP}'`);
        const resolvedDestP = this.resolveFilename(`copyfile '${sourceP}' -> ${destP}'`, destP);
        const indexDest = this.entries.get(resolvedDestP);
        if ((flags & (fs_1.constants.COPYFILE_EXCL | fs_1.constants.COPYFILE_FICLONE_FORCE)) !== 0 && typeof indexDest !== `undefined`)
            throw fslib_5.errors.EEXIST(`copyfile '${sourceP}' -> '${destP}'`);
        return {
            indexSource,
            resolvedDestP,
            indexDest,
        };
    }
    async appendFilePromise(p, content, opts) {
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`open '${p}'`);
        if (typeof opts === `undefined`)
            opts = { flag: `a` };
        else if (typeof opts === `string`)
            opts = { flag: `a`, encoding: opts };
        else if (typeof opts.flag === `undefined`)
            opts = { flag: `a`, ...opts };
        return this.writeFilePromise(p, content, opts);
    }
    appendFileSync(p, content, opts = {}) {
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`open '${p}'`);
        if (typeof opts === `undefined`)
            opts = { flag: `a` };
        else if (typeof opts === `string`)
            opts = { flag: `a`, encoding: opts };
        else if (typeof opts.flag === `undefined`)
            opts = { flag: `a`, ...opts };
        return this.writeFileSync(p, content, opts);
    }
    fdToPath(fd, reason) {
        var _a;
        const path = (_a = this.fds.get(fd)) === null || _a === void 0 ? void 0 : _a.p;
        if (typeof path === `undefined`)
            throw fslib_5.errors.EBADF(reason);
        return path;
    }
    async writeFilePromise(p, content, opts) {
        const { encoding, mode, index, resolvedP } = this.prepareWriteFile(p, opts);
        if (index !== undefined && typeof opts === `object` && opts.flag && opts.flag.includes(`a`))
            content = Buffer.concat([await this.getFileSource(index, { asyncDecompress: true }), Buffer.from(content)]);
        if (encoding !== null)
            // @ts-expect-error: toString ignores unneeded arguments
            content = content.toString(encoding);
        const newIndex = this.setFileSource(resolvedP, content);
        if (newIndex !== index)
            this.registerEntry(resolvedP, newIndex);
        if (mode !== null) {
            await this.chmodPromise(resolvedP, mode);
        }
    }
    writeFileSync(p, content, opts) {
        const { encoding, mode, index, resolvedP } = this.prepareWriteFile(p, opts);
        if (index !== undefined && typeof opts === `object` && opts.flag && opts.flag.includes(`a`))
            content = Buffer.concat([this.getFileSource(index), Buffer.from(content)]);
        if (encoding !== null)
            // @ts-expect-error: toString ignores unneeded arguments
            content = content.toString(encoding);
        const newIndex = this.setFileSource(resolvedP, content);
        if (newIndex !== index)
            this.registerEntry(resolvedP, newIndex);
        if (mode !== null) {
            this.chmodSync(resolvedP, mode);
        }
    }
    prepareWriteFile(p, opts) {
        if (typeof p === `number`)
            p = this.fdToPath(p, `read`);
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`open '${p}'`);
        const resolvedP = this.resolveFilename(`open '${p}'`, p);
        if (this.listings.has(resolvedP))
            throw fslib_5.errors.EISDIR(`open '${p}'`);
        let encoding = null, mode = null;
        if (typeof opts === `string`) {
            encoding = opts;
        }
        else if (typeof opts === `object`) {
            ({
                encoding = null,
                mode = null,
            } = opts);
        }
        const index = this.entries.get(resolvedP);
        return {
            encoding,
            mode,
            resolvedP,
            index,
        };
    }
    async unlinkPromise(p) {
        return this.unlinkSync(p);
    }
    unlinkSync(p) {
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`unlink '${p}'`);
        const resolvedP = this.resolveFilename(`unlink '${p}'`, p);
        if (this.listings.has(resolvedP))
            throw fslib_5.errors.EISDIR(`unlink '${p}'`);
        const index = this.entries.get(resolvedP);
        if (typeof index === `undefined`)
            throw fslib_5.errors.EINVAL(`unlink '${p}'`);
        this.deleteEntry(resolvedP, index);
    }
    async utimesPromise(p, atime, mtime) {
        return this.utimesSync(p, atime, mtime);
    }
    utimesSync(p, atime, mtime) {
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`utimes '${p}'`);
        const resolvedP = this.resolveFilename(`utimes '${p}'`, p);
        this.utimesImpl(resolvedP, mtime);
    }
    async lutimesPromise(p, atime, mtime) {
        return this.lutimesSync(p, atime, mtime);
    }
    lutimesSync(p, atime, mtime) {
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`lutimes '${p}'`);
        const resolvedP = this.resolveFilename(`utimes '${p}'`, p, false);
        this.utimesImpl(resolvedP, mtime);
    }
    utimesImpl(resolvedP, mtime) {
        if (this.listings.has(resolvedP))
            if (!this.entries.has(resolvedP))
                this.hydrateDirectory(resolvedP);
        const entry = this.entries.get(resolvedP);
        if (entry === undefined)
            throw new Error(`Unreachable`);
        const rc = this.libzip.file.setMtime(this.zip, entry, 0, toUnixTimestamp(mtime), 0);
        if (rc === -1) {
            throw this.makeLibzipError(this.libzip.getError(this.zip));
        }
    }
    async mkdirPromise(p, opts) {
        return this.mkdirSync(p, opts);
    }
    mkdirSync(p, { mode = 0o755, recursive = false } = {}) {
        if (recursive)
            return this.mkdirpSync(p, { chmod: mode });
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`mkdir '${p}'`);
        const resolvedP = this.resolveFilename(`mkdir '${p}'`, p);
        if (this.entries.has(resolvedP) || this.listings.has(resolvedP))
            throw fslib_5.errors.EEXIST(`mkdir '${p}'`);
        this.hydrateDirectory(resolvedP);
        this.chmodSync(resolvedP, mode);
        return undefined;
    }
    async rmdirPromise(p, opts) {
        return this.rmdirSync(p, opts);
    }
    rmdirSync(p, { recursive = false } = {}) {
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`rmdir '${p}'`);
        if (recursive) {
            this.removeSync(p);
            return;
        }
        const resolvedP = this.resolveFilename(`rmdir '${p}'`, p);
        const directoryListing = this.listings.get(resolvedP);
        if (!directoryListing)
            throw fslib_5.errors.ENOTDIR(`rmdir '${p}'`);
        if (directoryListing.size > 0)
            throw fslib_5.errors.ENOTEMPTY(`rmdir '${p}'`);
        const index = this.entries.get(resolvedP);
        if (typeof index === `undefined`)
            throw fslib_5.errors.EINVAL(`rmdir '${p}'`);
        this.deleteEntry(p, index);
    }
    hydrateDirectory(resolvedP) {
        const index = this.libzip.dir.add(this.zip, fslib_6.ppath.relative(fslib_6.PortablePath.root, resolvedP));
        if (index === -1)
            throw this.makeLibzipError(this.libzip.getError(this.zip));
        this.registerListing(resolvedP);
        this.registerEntry(resolvedP, index);
        return index;
    }
    async linkPromise(existingP, newP) {
        return this.linkSync(existingP, newP);
    }
    linkSync(existingP, newP) {
        // Zip archives don't support hard links:
        // https://stackoverflow.com/questions/8859616/are-hard-links-possible-within-a-zip-archive
        throw fslib_5.errors.EOPNOTSUPP(`link '${existingP}' -> '${newP}'`);
    }
    async symlinkPromise(target, p) {
        return this.symlinkSync(target, p);
    }
    symlinkSync(target, p) {
        if (this.readOnly)
            throw fslib_5.errors.EROFS(`symlink '${target}' -> '${p}'`);
        const resolvedP = this.resolveFilename(`symlink '${target}' -> '${p}'`, p);
        if (this.listings.has(resolvedP))
            throw fslib_5.errors.EISDIR(`symlink '${target}' -> '${p}'`);
        if (this.entries.has(resolvedP))
            throw fslib_5.errors.EEXIST(`symlink '${target}' -> '${p}'`);
        const index = this.setFileSource(resolvedP, target);
        this.registerEntry(resolvedP, index);
        const rc = this.libzip.file.setExternalAttributes(this.zip, index, 0, 0, this.libzip.ZIP_OPSYS_UNIX, (fs_1.constants.S_IFLNK | 0o777) << 16);
        if (rc === -1)
            throw this.makeLibzipError(this.libzip.getError(this.zip));
        this.symlinkCount += 1;
    }
    async readFilePromise(p, encoding) {
        // This is messed up regarding the TS signatures
        if (typeof encoding === `object`)
            // @ts-expect-error
            encoding = encoding ? encoding.encoding : undefined;
        const data = await this.readFileBuffer(p, { asyncDecompress: true });
        return encoding ? data.toString(encoding) : data;
    }
    readFileSync(p, encoding) {
        // This is messed up regarding the TS signatures
        if (typeof encoding === `object`)
            // @ts-expect-error
            encoding = encoding ? encoding.encoding : undefined;
        const data = this.readFileBuffer(p);
        return encoding ? data.toString(encoding) : data;
    }
    readFileBuffer(p, opts = { asyncDecompress: false }) {
        if (typeof p === `number`)
            p = this.fdToPath(p, `read`);
        const resolvedP = this.resolveFilename(`open '${p}'`, p);
        if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOENT(`open '${p}'`);
        // Ensures that the last component is a directory, if the user said so (even if it is we'll throw right after with EISDIR anyway)
        if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOTDIR(`open '${p}'`);
        if (this.listings.has(resolvedP))
            throw fslib_5.errors.EISDIR(`read`);
        const entry = this.entries.get(resolvedP);
        if (entry === undefined)
            throw new Error(`Unreachable`);
        return this.getFileSource(entry, opts);
    }
    async readdirPromise(p, opts) {
        return this.readdirSync(p, opts);
    }
    readdirSync(p, opts) {
        const resolvedP = this.resolveFilename(`scandir '${p}'`, p);
        if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOENT(`scandir '${p}'`);
        const directoryListing = this.listings.get(resolvedP);
        if (!directoryListing)
            throw fslib_5.errors.ENOTDIR(`scandir '${p}'`);
        const entries = [...directoryListing];
        if (!(opts === null || opts === void 0 ? void 0 : opts.withFileTypes))
            return entries;
        return entries.map(name => {
            return Object.assign(this.statImpl(`lstat`, fslib_6.ppath.join(p, name)), {
                name,
            });
        });
    }
    async readlinkPromise(p) {
        const entry = this.prepareReadlink(p);
        return (await this.getFileSource(entry, { asyncDecompress: true })).toString();
    }
    readlinkSync(p) {
        const entry = this.prepareReadlink(p);
        return this.getFileSource(entry).toString();
    }
    prepareReadlink(p) {
        const resolvedP = this.resolveFilename(`readlink '${p}'`, p, false);
        if (!this.entries.has(resolvedP) && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOENT(`readlink '${p}'`);
        // Ensure that the last component is a directory (if it is we'll throw right after with EISDIR anyway)
        if (p[p.length - 1] === `/` && !this.listings.has(resolvedP))
            throw fslib_5.errors.ENOTDIR(`open '${p}'`);
        if (this.listings.has(resolvedP))
            throw fslib_5.errors.EINVAL(`readlink '${p}'`);
        const entry = this.entries.get(resolvedP);
        if (entry === undefined)
            throw new Error(`Unreachable`);
        if (!this.isSymbolicLink(entry))
            throw fslib_5.errors.EINVAL(`readlink '${p}'`);
        return entry;
    }
    async truncatePromise(p, len = 0) {
        const resolvedP = this.resolveFilename(`open '${p}'`, p);
        const index = this.entries.get(resolvedP);
        if (typeof index === `undefined`)
            throw fslib_5.errors.EINVAL(`open '${p}'`);
        const source = await this.getFileSource(index, { asyncDecompress: true });
        const truncated = Buffer.alloc(len, 0x00);
        source.copy(truncated);
        return await this.writeFilePromise(p, truncated);
    }
    truncateSync(p, len = 0) {
        const resolvedP = this.resolveFilename(`open '${p}'`, p);
        const index = this.entries.get(resolvedP);
        if (typeof index === `undefined`)
            throw fslib_5.errors.EINVAL(`open '${p}'`);
        const source = this.getFileSource(index);
        const truncated = Buffer.alloc(len, 0x00);
        source.copy(truncated);
        return this.writeFileSync(p, truncated);
    }
    async ftruncatePromise(fd, len) {
        return this.truncatePromise(this.fdToPath(fd, `ftruncate`), len);
    }
    ftruncateSync(fd, len) {
        return this.truncateSync(this.fdToPath(fd, `ftruncateSync`), len);
    }
    watch(p, a, b) {
        let persistent;
        switch (typeof a) {
            case `function`:
            case `string`:
            case `undefined`:
                {
                    persistent = true;
                }
                break;
            default:
                {
                    ({ persistent = true } = a);
                }
                break;
        }
        if (!persistent)
            return { on: () => { }, close: () => { } };
        const interval = setInterval(() => { }, 24 * 60 * 60 * 1000);
        return { on: () => { }, close: () => {
                clearInterval(interval);
            } };
    }
    watchFile(p, a, b) {
        const resolvedP = fslib_6.ppath.resolve(fslib_6.PortablePath.root, p);
        return (0, fslib_4.watchFile)(this, resolvedP, a, b);
    }
    unwatchFile(p, cb) {
        const resolvedP = fslib_6.ppath.resolve(fslib_6.PortablePath.root, p);
        return (0, fslib_4.unwatchFile)(this, resolvedP, cb);
    }
}
exports.ZipFS = ZipFS;


/***/ }),

/***/ 256:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.ZipOpenFS = exports.getArchivePart = void 0;
const fslib_1 = __webpack_require__(382);
const fslib_2 = __webpack_require__(382);
const libzip_1 = __webpack_require__(32);
/**
 * Extracts the archive part (ending in the first instance of `extension`) from a path.
 *
 * The indexOf-based implementation is ~3.7x faster than a RegExp-based implementation.
 */
function getArchivePart(path, extension) {
    let idx = path.indexOf(extension);
    if (idx <= 0)
        return null;
    let nextCharIdx = idx;
    while (idx >= 0) {
        nextCharIdx = idx + extension.length;
        if (path[nextCharIdx] === fslib_2.ppath.sep)
            break;
        // Disallow files named ".zip"
        if (path[idx - 1] === fslib_2.ppath.sep)
            return null;
        idx = path.indexOf(extension, nextCharIdx);
    }
    // The path either has to end in ".zip" or contain an archive subpath (".zip/...")
    if (path.length > nextCharIdx && path[nextCharIdx] !== fslib_2.ppath.sep)
        return null;
    return path.slice(0, nextCharIdx);
}
exports.getArchivePart = getArchivePart;
class ZipOpenFS extends fslib_1.MountFS {
    static async openPromise(fn, opts) {
        const zipOpenFs = new ZipOpenFS(opts);
        try {
            return await fn(zipOpenFs);
        }
        finally {
            zipOpenFs.saveAndClose();
        }
    }
    constructor(opts = {}) {
        const fileExtensions = opts.fileExtensions;
        const readOnlyArchives = opts.readOnlyArchives;
        const getMountPoint = typeof fileExtensions === `undefined`
            ? path => getArchivePart(path, `.zip`)
            : path => {
                for (const extension of fileExtensions) {
                    const result = getArchivePart(path, extension);
                    if (result) {
                        return result;
                    }
                }
                return null;
            };
        const factorySync = (baseFs, p) => {
            return new libzip_1.ZipFS(p, {
                baseFs,
                readOnly: readOnlyArchives,
                stats: baseFs.statSync(p),
            });
        };
        const factoryPromise = async (baseFs, p) => {
            const zipOptions = {
                baseFs,
                readOnly: readOnlyArchives,
                stats: await baseFs.statPromise(p),
            };
            return () => {
                return new libzip_1.ZipFS(p, zipOptions);
            };
        };
        super({
            ...opts,
            factorySync,
            factoryPromise,
            getMountPoint,
        });
    }
}
exports.ZipOpenFS = ZipOpenFS;


/***/ }),

/***/ 763:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mountMemoryDrive = void 0;
const tslib_1 = __webpack_require__(240);
tslib_1.__exportStar(__webpack_require__(256), exports);
tslib_1.__exportStar(__webpack_require__(154), exports);
var mountMemoryDrive_1 = __webpack_require__(650);
Object.defineProperty(exports, "mountMemoryDrive", ({ enumerable: true, get: function () { return mountMemoryDrive_1.mountMemoryDrive; } }));


/***/ }),

/***/ 309:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.tryInstance = exports.getInstance = exports.setFactory = exports.cachedInstance = void 0;
let registeredFactory = () => {
    throw new Error(`Assertion failed: No libzip instance is available, and no factory was configured`);
};
function setFactory(factory) {
    registeredFactory = factory;
}
exports.setFactory = setFactory;
function getInstance() {
    if (typeof exports.cachedInstance === `undefined`)
        exports.cachedInstance = registeredFactory();
    return exports.cachedInstance;
}
exports.getInstance = getInstance;
function tryInstance() {
    return exports.cachedInstance;
}
exports.tryInstance = tryInstance;


/***/ }),

/***/ 161:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {

var frozenFs = Object.assign({}, __webpack_require__(147));

var createModule = (function() {
  var _scriptDir =
    typeof document !== "undefined" && document.currentScript
      ? document.currentScript.src
      : undefined;
  if (typeof __filename !== "undefined") _scriptDir = _scriptDir || __filename;
  return function(createModule) {
    createModule = createModule || {};

    null;
    var Module = typeof createModule !== "undefined" ? createModule : {};
    var readyPromiseResolve, readyPromiseReject;
    Module["ready"] = new Promise(function(resolve, reject) {
      readyPromiseResolve = resolve;
      readyPromiseReject = reject;
    });
    var moduleOverrides = {};
    var key;
    for (key in Module) {
      if (Module.hasOwnProperty(key)) {
        moduleOverrides[key] = Module[key];
      }
    }
    var arguments_ = [];
    var thisProgram = "./this.program";
    var quit_ = function(status, toThrow) {
      throw toThrow;
    };
    var ENVIRONMENT_IS_WORKER = false;
    var ENVIRONMENT_IS_NODE = true;
    var scriptDirectory = "";
    function locateFile(path) {
      if (Module["locateFile"]) {
        return Module["locateFile"](path, scriptDirectory);
      }
      return scriptDirectory + path;
    }
    var read_, readBinary;
    var nodeFS;
    var nodePath;
    if (ENVIRONMENT_IS_NODE) {
      if (ENVIRONMENT_IS_WORKER) {
        scriptDirectory = (__webpack_require__(17).dirname)(scriptDirectory) + "/";
      } else {
        scriptDirectory = __dirname + "/";
      }
      read_ = function shell_read(filename, binary) {
        var ret = tryParseAsDataURI(filename);
        if (ret) {
          return binary ? ret : ret.toString();
        }
        if (!nodeFS) nodeFS = frozenFs;
        if (!nodePath) nodePath = __webpack_require__(17);
        filename = nodePath["normalize"](filename);
        return nodeFS["readFileSync"](filename, binary ? null : "utf8");
      };
      readBinary = function readBinary(filename) {
        var ret = read_(filename, true);
        if (!ret.buffer) {
          ret = new Uint8Array(ret);
        }
        assert(ret.buffer);
        return ret;
      };
      if (process["argv"].length > 1) {
        thisProgram = process["argv"][1].replace(/\\/g, "/");
      }
      arguments_ = process["argv"].slice(2);
      quit_ = function(status) {
        process["exit"](status);
      };
      Module["inspect"] = function() {
        return "[Emscripten Module object]";
      };
    } else {
    }
    var out = Module["print"] || console.log.bind(console);
    var err = Module["printErr"] || console.warn.bind(console);
    for (key in moduleOverrides) {
      if (moduleOverrides.hasOwnProperty(key)) {
        Module[key] = moduleOverrides[key];
      }
    }
    moduleOverrides = null;
    if (Module["arguments"]) arguments_ = Module["arguments"];
    if (Module["thisProgram"]) thisProgram = Module["thisProgram"];
    if (Module["quit"]) quit_ = Module["quit"];
    var tempRet0 = 0;
    var setTempRet0 = function(value) {
      tempRet0 = value;
    };
    var wasmBinary;
    if (Module["wasmBinary"]) wasmBinary = Module["wasmBinary"];
    var noExitRuntime = Module["noExitRuntime"] || true;
    if (typeof WebAssembly !== "object") {
      abort("no native wasm support detected");
    }
    function getValue(ptr, type, noSafe) {
      type = type || "i8";
      if (type.charAt(type.length - 1) === "*") type = "i32";
      switch (type) {
        case "i1":
          return HEAP8[ptr >> 0];
        case "i8":
          return HEAP8[ptr >> 0];
        case "i16":
          return LE_HEAP_LOAD_I16((ptr >> 1) * 2);
        case "i32":
          return LE_HEAP_LOAD_I32((ptr >> 2) * 4);
        case "i64":
          return LE_HEAP_LOAD_I32((ptr >> 2) * 4);
        case "float":
          return LE_HEAP_LOAD_F32((ptr >> 2) * 4);
        case "double":
          return LE_HEAP_LOAD_F64((ptr >> 3) * 8);
        default:
          abort("invalid type for getValue: " + type);
      }
      return null;
    }
    var wasmMemory;
    var ABORT = false;
    var EXITSTATUS;
    function assert(condition, text) {
      if (!condition) {
        abort("Assertion failed: " + text);
      }
    }
    function getCFunc(ident) {
      var func = Module["_" + ident];
      assert(
        func,
        "Cannot call unknown function " + ident + ", make sure it is exported"
      );
      return func;
    }
    function ccall(ident, returnType, argTypes, args, opts) {
      var toC = {
        string: function(str) {
          var ret = 0;
          if (str !== null && str !== undefined && str !== 0) {
            var len = (str.length << 2) + 1;
            ret = stackAlloc(len);
            stringToUTF8(str, ret, len);
          }
          return ret;
        },
        array: function(arr) {
          var ret = stackAlloc(arr.length);
          writeArrayToMemory(arr, ret);
          return ret;
        }
      };
      function convertReturnValue(ret) {
        if (returnType === "string") return UTF8ToString(ret);
        if (returnType === "boolean") return Boolean(ret);
        return ret;
      }
      var func = getCFunc(ident);
      var cArgs = [];
      var stack = 0;
      if (args) {
        for (var i = 0; i < args.length; i++) {
          var converter = toC[argTypes[i]];
          if (converter) {
            if (stack === 0) stack = stackSave();
            cArgs[i] = converter(args[i]);
          } else {
            cArgs[i] = args[i];
          }
        }
      }
      var ret = func.apply(null, cArgs);
      ret = convertReturnValue(ret);
      if (stack !== 0) stackRestore(stack);
      return ret;
    }
    function cwrap(ident, returnType, argTypes, opts) {
      argTypes = argTypes || [];
      var numericArgs = argTypes.every(function(type) {
        return type === "number";
      });
      var numericRet = returnType !== "string";
      if (numericRet && numericArgs && !opts) {
        return getCFunc(ident);
      }
      return function() {
        return ccall(ident, returnType, argTypes, arguments, opts);
      };
    }
    var UTF8Decoder = new TextDecoder("utf8");
    function UTF8ToString(ptr, maxBytesToRead) {
      if (!ptr) return "";
      var maxPtr = ptr + maxBytesToRead;
      for (var end = ptr; !(end >= maxPtr) && HEAPU8[end]; ) ++end;
      return UTF8Decoder.decode(HEAPU8.subarray(ptr, end));
    }
    function stringToUTF8Array(str, heap, outIdx, maxBytesToWrite) {
      if (!(maxBytesToWrite > 0)) return 0;
      var startIdx = outIdx;
      var endIdx = outIdx + maxBytesToWrite - 1;
      for (var i = 0; i < str.length; ++i) {
        var u = str.charCodeAt(i);
        if (u >= 55296 && u <= 57343) {
          var u1 = str.charCodeAt(++i);
          u = (65536 + ((u & 1023) << 10)) | (u1 & 1023);
        }
        if (u <= 127) {
          if (outIdx >= endIdx) break;
          heap[outIdx++] = u;
        } else if (u <= 2047) {
          if (outIdx + 1 >= endIdx) break;
          heap[outIdx++] = 192 | (u >> 6);
          heap[outIdx++] = 128 | (u & 63);
        } else if (u <= 65535) {
          if (outIdx + 2 >= endIdx) break;
          heap[outIdx++] = 224 | (u >> 12);
          heap[outIdx++] = 128 | ((u >> 6) & 63);
          heap[outIdx++] = 128 | (u & 63);
        } else {
          if (outIdx + 3 >= endIdx) break;
          heap[outIdx++] = 240 | (u >> 18);
          heap[outIdx++] = 128 | ((u >> 12) & 63);
          heap[outIdx++] = 128 | ((u >> 6) & 63);
          heap[outIdx++] = 128 | (u & 63);
        }
      }
      heap[outIdx] = 0;
      return outIdx - startIdx;
    }
    function stringToUTF8(str, outPtr, maxBytesToWrite) {
      return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
    }
    function lengthBytesUTF8(str) {
      var len = 0;
      for (var i = 0; i < str.length; ++i) {
        var u = str.charCodeAt(i);
        if (u >= 55296 && u <= 57343)
          u = (65536 + ((u & 1023) << 10)) | (str.charCodeAt(++i) & 1023);
        if (u <= 127) ++len;
        else if (u <= 2047) len += 2;
        else if (u <= 65535) len += 3;
        else len += 4;
      }
      return len;
    }
    function allocateUTF8(str) {
      var size = lengthBytesUTF8(str) + 1;
      var ret = _malloc(size);
      if (ret) stringToUTF8Array(str, HEAP8, ret, size);
      return ret;
    }
    function writeArrayToMemory(array, buffer) {
      HEAP8.set(array, buffer);
    }
    function alignUp(x, multiple) {
      if (x % multiple > 0) {
        x += multiple - (x % multiple);
      }
      return x;
    }
    var buffer,
      HEAP8,
      HEAPU8,
      HEAP16,
      HEAPU16,
      HEAP32,
      HEAPU32,
      HEAPF32,
      HEAPF64;
    var HEAP_DATA_VIEW;
    function updateGlobalBufferAndViews(buf) {
      buffer = buf;
      Module["HEAP_DATA_VIEW"] = HEAP_DATA_VIEW = new DataView(buf);
      Module["HEAP8"] = HEAP8 = new Int8Array(buf);
      Module["HEAP16"] = HEAP16 = new Int16Array(buf);
      Module["HEAP32"] = HEAP32 = new Int32Array(buf);
      Module["HEAPU8"] = HEAPU8 = new Uint8Array(buf);
      Module["HEAPU16"] = HEAPU16 = new Uint16Array(buf);
      Module["HEAPU32"] = HEAPU32 = new Uint32Array(buf);
      Module["HEAPF32"] = HEAPF32 = new Float32Array(buf);
      Module["HEAPF64"] = HEAPF64 = new Float64Array(buf);
    }
    var INITIAL_MEMORY = Module["INITIAL_MEMORY"] || 16777216;
    var wasmTable;
    var __ATPRERUN__ = [];
    var __ATINIT__ = [];
    var __ATPOSTRUN__ = [];
    var runtimeInitialized = false;
    function preRun() {
      if (Module["preRun"]) {
        if (typeof Module["preRun"] == "function")
          Module["preRun"] = [Module["preRun"]];
        while (Module["preRun"].length) {
          addOnPreRun(Module["preRun"].shift());
        }
      }
      callRuntimeCallbacks(__ATPRERUN__);
    }
    function initRuntime() {
      runtimeInitialized = true;
      callRuntimeCallbacks(__ATINIT__);
    }
    function postRun() {
      if (Module["postRun"]) {
        if (typeof Module["postRun"] == "function")
          Module["postRun"] = [Module["postRun"]];
        while (Module["postRun"].length) {
          addOnPostRun(Module["postRun"].shift());
        }
      }
      callRuntimeCallbacks(__ATPOSTRUN__);
    }
    function addOnPreRun(cb) {
      __ATPRERUN__.unshift(cb);
    }
    function addOnInit(cb) {
      __ATINIT__.unshift(cb);
    }
    function addOnPostRun(cb) {
      __ATPOSTRUN__.unshift(cb);
    }
    var runDependencies = 0;
    var runDependencyWatcher = null;
    var dependenciesFulfilled = null;
    function addRunDependency(id) {
      runDependencies++;
      if (Module["monitorRunDependencies"]) {
        Module["monitorRunDependencies"](runDependencies);
      }
    }
    function removeRunDependency(id) {
      runDependencies--;
      if (Module["monitorRunDependencies"]) {
        Module["monitorRunDependencies"](runDependencies);
      }
      if (runDependencies == 0) {
        if (runDependencyWatcher !== null) {
          clearInterval(runDependencyWatcher);
          runDependencyWatcher = null;
        }
        if (dependenciesFulfilled) {
          var callback = dependenciesFulfilled;
          dependenciesFulfilled = null;
          callback();
        }
      }
    }
    Module["preloadedImages"] = {};
    Module["preloadedAudios"] = {};
    function abort(what) {
      if (Module["onAbort"]) {
        Module["onAbort"](what);
      }
      what += "";
      err(what);
      ABORT = true;
      EXITSTATUS = 1;
      what = "abort(" + what + "). Build with -s ASSERTIONS=1 for more info.";
      var e = new WebAssembly.RuntimeError(what);
      readyPromiseReject(e);
      throw e;
    }
    var dataURIPrefix = "data:application/octet-stream;base64,";
    function isDataURI(filename) {
      return filename.startsWith(dataURIPrefix);
    }
    var wasmBinaryFile =
      "data:application/octet-stream;base64, ";
    if (!isDataURI(wasmBinaryFile)) {
      wasmBinaryFile = locateFile(wasmBinaryFile);
    }
    function getBinary(file) {
      try {
        if (file == wasmBinaryFile && wasmBinary) {
          return new Uint8Array(wasmBinary);
        }
        var binary = tryParseAsDataURI(file);
        if (binary) {
          return binary;
        }
        if (readBinary) {
          return readBinary(file);
        } else {
          throw "sync fetching of the wasm failed: you can preload it to Module['wasmBinary'] manually, or emcc.py will do that for you when generating HTML (but not JS)";
        }
      } catch (err) {
        abort(err);
      }
    }
    function instantiateSync(file, info) {
      var instance;
      var module;
      var binary;
      try {
        binary = getBinary(file);
        module = new WebAssembly.Module(binary);
        instance = new WebAssembly.Instance(module, info);
      } catch (e) {
        var str = e.toString();
        err("failed to compile wasm module: " + str);
        if (str.includes("imported Memory") || str.includes("memory import")) {
          err(
            "Memory size incompatibility issues may be due to changing INITIAL_MEMORY at runtime to something too large. Use ALLOW_MEMORY_GROWTH to allow any size memory (and also make sure not to set INITIAL_MEMORY at runtime to something smaller than it was at compile time)."
          );
        }
        throw e;
      }
      return [instance, module];
    }
    function createWasm() {
      var info = { a: asmLibraryArg };
      function receiveInstance(instance, module) {
        var exports = instance.exports;
        Module["asm"] = exports;
        wasmMemory = Module["asm"]["g"];
        updateGlobalBufferAndViews(wasmMemory.buffer);
        wasmTable = Module["asm"]["$"];
        addOnInit(Module["asm"]["h"]);
        removeRunDependency("wasm-instantiate");
      }
      addRunDependency("wasm-instantiate");
      if (Module["instantiateWasm"]) {
        try {
          var exports = Module["instantiateWasm"](info, receiveInstance);
          return exports;
        } catch (e) {
          err("Module.instantiateWasm callback failed with error: " + e);
          return false;
        }
      }
      var result = instantiateSync(wasmBinaryFile, info);
      receiveInstance(result[0]);
      return Module["asm"];
    }
    function LE_HEAP_LOAD_F32(byteOffset) {
      return HEAP_DATA_VIEW.getFloat32(byteOffset, true);
    }
    function LE_HEAP_LOAD_F64(byteOffset) {
      return HEAP_DATA_VIEW.getFloat64(byteOffset, true);
    }
    function LE_HEAP_LOAD_I16(byteOffset) {
      return HEAP_DATA_VIEW.getInt16(byteOffset, true);
    }
    function LE_HEAP_LOAD_I32(byteOffset) {
      return HEAP_DATA_VIEW.getInt32(byteOffset, true);
    }
    function LE_HEAP_STORE_I32(byteOffset, value) {
      HEAP_DATA_VIEW.setInt32(byteOffset, value, true);
    }
    function callRuntimeCallbacks(callbacks) {
      while (callbacks.length > 0) {
        var callback = callbacks.shift();
        if (typeof callback == "function") {
          callback(Module);
          continue;
        }
        var func = callback.func;
        if (typeof func === "number") {
          if (callback.arg === undefined) {
            wasmTable.get(func)();
          } else {
            wasmTable.get(func)(callback.arg);
          }
        } else {
          func(callback.arg === undefined ? null : callback.arg);
        }
      }
    }
    function _gmtime_r(time, tmPtr) {
      var date = new Date(LE_HEAP_LOAD_I32((time >> 2) * 4) * 1e3);
      LE_HEAP_STORE_I32((tmPtr >> 2) * 4, date.getUTCSeconds());
      LE_HEAP_STORE_I32(((tmPtr + 4) >> 2) * 4, date.getUTCMinutes());
      LE_HEAP_STORE_I32(((tmPtr + 8) >> 2) * 4, date.getUTCHours());
      LE_HEAP_STORE_I32(((tmPtr + 12) >> 2) * 4, date.getUTCDate());
      LE_HEAP_STORE_I32(((tmPtr + 16) >> 2) * 4, date.getUTCMonth());
      LE_HEAP_STORE_I32(((tmPtr + 20) >> 2) * 4, date.getUTCFullYear() - 1900);
      LE_HEAP_STORE_I32(((tmPtr + 24) >> 2) * 4, date.getUTCDay());
      LE_HEAP_STORE_I32(((tmPtr + 36) >> 2) * 4, 0);
      LE_HEAP_STORE_I32(((tmPtr + 32) >> 2) * 4, 0);
      var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);
      var yday = ((date.getTime() - start) / (1e3 * 60 * 60 * 24)) | 0;
      LE_HEAP_STORE_I32(((tmPtr + 28) >> 2) * 4, yday);
      if (!_gmtime_r.GMTString) _gmtime_r.GMTString = allocateUTF8("GMT");
      LE_HEAP_STORE_I32(((tmPtr + 40) >> 2) * 4, _gmtime_r.GMTString);
      return tmPtr;
    }
    function ___gmtime_r(a0, a1) {
      return _gmtime_r(a0, a1);
    }
    function _emscripten_memcpy_big(dest, src, num) {
      HEAPU8.copyWithin(dest, src, src + num);
    }
    function emscripten_realloc_buffer(size) {
      try {
        wasmMemory.grow((size - buffer.byteLength + 65535) >>> 16);
        updateGlobalBufferAndViews(wasmMemory.buffer);
        return 1;
      } catch (e) {}
    }
    function _emscripten_resize_heap(requestedSize) {
      var oldSize = HEAPU8.length;
      requestedSize = requestedSize >>> 0;
      var maxHeapSize = 2147483648;
      if (requestedSize > maxHeapSize) {
        return false;
      }
      for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
        var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
        overGrownHeapSize = Math.min(
          overGrownHeapSize,
          requestedSize + 100663296
        );
        var newSize = Math.min(
          maxHeapSize,
          alignUp(Math.max(requestedSize, overGrownHeapSize), 65536)
        );
        var replacement = emscripten_realloc_buffer(newSize);
        if (replacement) {
          return true;
        }
      }
      return false;
    }
    function _setTempRet0(val) {
      setTempRet0(val);
    }
    function _time(ptr) {
      var ret = (Date.now() / 1e3) | 0;
      if (ptr) {
        LE_HEAP_STORE_I32((ptr >> 2) * 4, ret);
      }
      return ret;
    }
    function _tzset() {
      if (_tzset.called) return;
      _tzset.called = true;
      var currentYear = new Date().getFullYear();
      var winter = new Date(currentYear, 0, 1);
      var summer = new Date(currentYear, 6, 1);
      var winterOffset = winter.getTimezoneOffset();
      var summerOffset = summer.getTimezoneOffset();
      var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
      LE_HEAP_STORE_I32((__get_timezone() >> 2) * 4, stdTimezoneOffset * 60);
      LE_HEAP_STORE_I32(
        (__get_daylight() >> 2) * 4,
        Number(winterOffset != summerOffset)
      );
      function extractZone(date) {
        var match = date.toTimeString().match(/\(([A-Za-z ]+)\)$/);
        return match ? match[1] : "GMT";
      }
      var winterName = extractZone(winter);
      var summerName = extractZone(summer);
      var winterNamePtr = allocateUTF8(winterName);
      var summerNamePtr = allocateUTF8(summerName);
      if (summerOffset < winterOffset) {
        LE_HEAP_STORE_I32((__get_tzname() >> 2) * 4, winterNamePtr);
        LE_HEAP_STORE_I32(((__get_tzname() + 4) >> 2) * 4, summerNamePtr);
      } else {
        LE_HEAP_STORE_I32((__get_tzname() >> 2) * 4, summerNamePtr);
        LE_HEAP_STORE_I32(((__get_tzname() + 4) >> 2) * 4, winterNamePtr);
      }
    }
    function _timegm(tmPtr) {
      _tzset();
      var time = Date.UTC(
        LE_HEAP_LOAD_I32(((tmPtr + 20) >> 2) * 4) + 1900,
        LE_HEAP_LOAD_I32(((tmPtr + 16) >> 2) * 4),
        LE_HEAP_LOAD_I32(((tmPtr + 12) >> 2) * 4),
        LE_HEAP_LOAD_I32(((tmPtr + 8) >> 2) * 4),
        LE_HEAP_LOAD_I32(((tmPtr + 4) >> 2) * 4),
        LE_HEAP_LOAD_I32((tmPtr >> 2) * 4),
        0
      );
      var date = new Date(time);
      LE_HEAP_STORE_I32(((tmPtr + 24) >> 2) * 4, date.getUTCDay());
      var start = Date.UTC(date.getUTCFullYear(), 0, 1, 0, 0, 0, 0);
      var yday = ((date.getTime() - start) / (1e3 * 60 * 60 * 24)) | 0;
      LE_HEAP_STORE_I32(((tmPtr + 28) >> 2) * 4, yday);
      return (date.getTime() / 1e3) | 0;
    }
    var decodeBase64 =
      typeof atob === "function"
        ? atob
        : function(input) {
            var keyStr =
              "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            do {
              enc1 = keyStr.indexOf(input.charAt(i++));
              enc2 = keyStr.indexOf(input.charAt(i++));
              enc3 = keyStr.indexOf(input.charAt(i++));
              enc4 = keyStr.indexOf(input.charAt(i++));
              chr1 = (enc1 << 2) | (enc2 >> 4);
              chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
              chr3 = ((enc3 & 3) << 6) | enc4;
              output = output + String.fromCharCode(chr1);
              if (enc3 !== 64) {
                output = output + String.fromCharCode(chr2);
              }
              if (enc4 !== 64) {
                output = output + String.fromCharCode(chr3);
              }
            } while (i < input.length);
            return output;
          };
    function intArrayFromBase64(s) {
      if (typeof ENVIRONMENT_IS_NODE === "boolean" && ENVIRONMENT_IS_NODE) {
        var buf;
        try {
          buf = Buffer.from(s, "base64");
        } catch (_) {
          buf = new Buffer(s, "base64");
        }
        return new Uint8Array(
          buf["buffer"],
          buf["byteOffset"],
          buf["byteLength"]
        );
      }
      try {
        var decoded = decodeBase64(s);
        var bytes = new Uint8Array(decoded.length);
        for (var i = 0; i < decoded.length; ++i) {
          bytes[i] = decoded.charCodeAt(i);
        }
        return bytes;
      } catch (_) {
        throw new Error("Converting base64 string to bytes failed.");
      }
    }
    function tryParseAsDataURI(filename) {
      if (!isDataURI(filename)) {
        return;
      }
      return intArrayFromBase64(filename.slice(dataURIPrefix.length));
    }
    var asmLibraryArg = {
      e: ___gmtime_r,
      c: _emscripten_memcpy_big,
      d: _emscripten_resize_heap,
      a: _setTempRet0,
      b: _time,
      f: _timegm
    };
    var asm = createWasm();
    var ___wasm_call_ctors = (Module["___wasm_call_ctors"] = asm["h"]);
    var _zip_ext_count_symlinks = (Module["_zip_ext_count_symlinks"] =
      asm["i"]);
    var _zip_file_get_external_attributes = (Module[
      "_zip_file_get_external_attributes"
    ] = asm["j"]);
    var _zipstruct_stat = (Module["_zipstruct_stat"] = asm["k"]);
    var _zipstruct_statS = (Module["_zipstruct_statS"] = asm["l"]);
    var _zipstruct_stat_name = (Module["_zipstruct_stat_name"] = asm["m"]);
    var _zipstruct_stat_index = (Module["_zipstruct_stat_index"] = asm["n"]);
    var _zipstruct_stat_size = (Module["_zipstruct_stat_size"] = asm["o"]);
    var _zipstruct_stat_mtime = (Module["_zipstruct_stat_mtime"] = asm["p"]);
    var _zipstruct_stat_crc = (Module["_zipstruct_stat_crc"] = asm["q"]);
    var _zipstruct_error = (Module["_zipstruct_error"] = asm["r"]);
    var _zipstruct_errorS = (Module["_zipstruct_errorS"] = asm["s"]);
    var _zipstruct_error_code_zip = (Module["_zipstruct_error_code_zip"] =
      asm["t"]);
    var _zipstruct_stat_comp_size = (Module["_zipstruct_stat_comp_size"] =
      asm["u"]);
    var _zipstruct_stat_comp_method = (Module["_zipstruct_stat_comp_method"] =
      asm["v"]);
    var _zip_close = (Module["_zip_close"] = asm["w"]);
    var _zip_delete = (Module["_zip_delete"] = asm["x"]);
    var _zip_dir_add = (Module["_zip_dir_add"] = asm["y"]);
    var _zip_discard = (Module["_zip_discard"] = asm["z"]);
    var _zip_error_init_with_code = (Module["_zip_error_init_with_code"] =
      asm["A"]);
    var _zip_get_error = (Module["_zip_get_error"] = asm["B"]);
    var _zip_file_get_error = (Module["_zip_file_get_error"] = asm["C"]);
    var _zip_error_strerror = (Module["_zip_error_strerror"] = asm["D"]);
    var _zip_fclose = (Module["_zip_fclose"] = asm["E"]);
    var _zip_file_add = (Module["_zip_file_add"] = asm["F"]);
    var _free = (Module["_free"] = asm["G"]);
    var _malloc = (Module["_malloc"] = asm["H"]);
    var _zip_source_error = (Module["_zip_source_error"] = asm["I"]);
    var _zip_source_seek = (Module["_zip_source_seek"] = asm["J"]);
    var _zip_file_set_external_attributes = (Module[
      "_zip_file_set_external_attributes"
    ] = asm["K"]);
    var _zip_file_set_mtime = (Module["_zip_file_set_mtime"] = asm["L"]);
    var _zip_fopen = (Module["_zip_fopen"] = asm["M"]);
    var _zip_fopen_index = (Module["_zip_fopen_index"] = asm["N"]);
    var _zip_fread = (Module["_zip_fread"] = asm["O"]);
    var _zip_get_name = (Module["_zip_get_name"] = asm["P"]);
    var _zip_get_num_entries = (Module["_zip_get_num_entries"] = asm["Q"]);
    var _zip_source_read = (Module["_zip_source_read"] = asm["R"]);
    var _zip_name_locate = (Module["_zip_name_locate"] = asm["S"]);
    var _zip_open_from_source = (Module["_zip_open_from_source"] = asm["T"]);
    var _zip_set_file_compression = (Module["_zip_set_file_compression"] =
      asm["U"]);
    var _zip_source_buffer = (Module["_zip_source_buffer"] = asm["V"]);
    var _zip_source_buffer_create = (Module["_zip_source_buffer_create"] =
      asm["W"]);
    var _zip_source_close = (Module["_zip_source_close"] = asm["X"]);
    var _zip_source_free = (Module["_zip_source_free"] = asm["Y"]);
    var _zip_source_keep = (Module["_zip_source_keep"] = asm["Z"]);
    var _zip_source_open = (Module["_zip_source_open"] = asm["_"]);
    var _zip_source_set_mtime = (Module["_zip_source_set_mtime"] = asm["aa"]);
    var _zip_source_tell = (Module["_zip_source_tell"] = asm["ba"]);
    var _zip_stat = (Module["_zip_stat"] = asm["ca"]);
    var _zip_stat_index = (Module["_zip_stat_index"] = asm["da"]);
    var __get_tzname = (Module["__get_tzname"] = asm["ea"]);
    var __get_daylight = (Module["__get_daylight"] = asm["fa"]);
    var __get_timezone = (Module["__get_timezone"] = asm["ga"]);
    var stackSave = (Module["stackSave"] = asm["ha"]);
    var stackRestore = (Module["stackRestore"] = asm["ia"]);
    var stackAlloc = (Module["stackAlloc"] = asm["ja"]);
    Module["cwrap"] = cwrap;
    Module["getValue"] = getValue;
    var calledRun;
    dependenciesFulfilled = function runCaller() {
      if (!calledRun) run();
      if (!calledRun) dependenciesFulfilled = runCaller;
    };
    function run(args) {
      args = args || arguments_;
      if (runDependencies > 0) {
        return;
      }
      preRun();
      if (runDependencies > 0) {
        return;
      }
      function doRun() {
        if (calledRun) return;
        calledRun = true;
        Module["calledRun"] = true;
        if (ABORT) return;
        initRuntime();
        readyPromiseResolve(Module);
        if (Module["onRuntimeInitialized"]) Module["onRuntimeInitialized"]();
        postRun();
      }
      if (Module["setStatus"]) {
        Module["setStatus"]("Running...");
        setTimeout(function() {
          setTimeout(function() {
            Module["setStatus"]("");
          }, 1);
          doRun();
        }, 1);
      } else {
        doRun();
      }
    }
    Module["run"] = run;
    if (Module["preInit"]) {
      if (typeof Module["preInit"] == "function")
        Module["preInit"] = [Module["preInit"]];
      while (Module["preInit"].length > 0) {
        Module["preInit"].pop()();
      }
    }
    run();

    return createModule;
  };
})();
if (true)
  module.exports = createModule;
else {}


/***/ }),

/***/ 815:
/***/ ((__unused_webpack_module, exports) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.makeInterface = exports.Errors = void 0;
const number64 = [
    `number`,
    `number`, // high
];
var Errors;
(function (Errors) {
    Errors[Errors["ZIP_ER_OK"] = 0] = "ZIP_ER_OK";
    Errors[Errors["ZIP_ER_MULTIDISK"] = 1] = "ZIP_ER_MULTIDISK";
    Errors[Errors["ZIP_ER_RENAME"] = 2] = "ZIP_ER_RENAME";
    Errors[Errors["ZIP_ER_CLOSE"] = 3] = "ZIP_ER_CLOSE";
    Errors[Errors["ZIP_ER_SEEK"] = 4] = "ZIP_ER_SEEK";
    Errors[Errors["ZIP_ER_READ"] = 5] = "ZIP_ER_READ";
    Errors[Errors["ZIP_ER_WRITE"] = 6] = "ZIP_ER_WRITE";
    Errors[Errors["ZIP_ER_CRC"] = 7] = "ZIP_ER_CRC";
    Errors[Errors["ZIP_ER_ZIPCLOSED"] = 8] = "ZIP_ER_ZIPCLOSED";
    Errors[Errors["ZIP_ER_NOENT"] = 9] = "ZIP_ER_NOENT";
    Errors[Errors["ZIP_ER_EXISTS"] = 10] = "ZIP_ER_EXISTS";
    Errors[Errors["ZIP_ER_OPEN"] = 11] = "ZIP_ER_OPEN";
    Errors[Errors["ZIP_ER_TMPOPEN"] = 12] = "ZIP_ER_TMPOPEN";
    Errors[Errors["ZIP_ER_ZLIB"] = 13] = "ZIP_ER_ZLIB";
    Errors[Errors["ZIP_ER_MEMORY"] = 14] = "ZIP_ER_MEMORY";
    Errors[Errors["ZIP_ER_CHANGED"] = 15] = "ZIP_ER_CHANGED";
    Errors[Errors["ZIP_ER_COMPNOTSUPP"] = 16] = "ZIP_ER_COMPNOTSUPP";
    Errors[Errors["ZIP_ER_EOF"] = 17] = "ZIP_ER_EOF";
    Errors[Errors["ZIP_ER_INVAL"] = 18] = "ZIP_ER_INVAL";
    Errors[Errors["ZIP_ER_NOZIP"] = 19] = "ZIP_ER_NOZIP";
    Errors[Errors["ZIP_ER_INTERNAL"] = 20] = "ZIP_ER_INTERNAL";
    Errors[Errors["ZIP_ER_INCONS"] = 21] = "ZIP_ER_INCONS";
    Errors[Errors["ZIP_ER_REMOVE"] = 22] = "ZIP_ER_REMOVE";
    Errors[Errors["ZIP_ER_DELETED"] = 23] = "ZIP_ER_DELETED";
    Errors[Errors["ZIP_ER_ENCRNOTSUPP"] = 24] = "ZIP_ER_ENCRNOTSUPP";
    Errors[Errors["ZIP_ER_RDONLY"] = 25] = "ZIP_ER_RDONLY";
    Errors[Errors["ZIP_ER_NOPASSWD"] = 26] = "ZIP_ER_NOPASSWD";
    Errors[Errors["ZIP_ER_WRONGPASSWD"] = 27] = "ZIP_ER_WRONGPASSWD";
    Errors[Errors["ZIP_ER_OPNOTSUPP"] = 28] = "ZIP_ER_OPNOTSUPP";
    Errors[Errors["ZIP_ER_INUSE"] = 29] = "ZIP_ER_INUSE";
    Errors[Errors["ZIP_ER_TELL"] = 30] = "ZIP_ER_TELL";
    Errors[Errors["ZIP_ER_COMPRESSED_DATA"] = 31] = "ZIP_ER_COMPRESSED_DATA";
})(Errors = exports.Errors || (exports.Errors = {}));
const makeInterface = (emZip) => ({
    // Those are getters because they can change after memory growth
    get HEAP8() {
        return emZip.HEAP8;
    },
    get HEAPU8() {
        return emZip.HEAPU8;
    },
    errors: Errors,
    SEEK_SET: 0,
    SEEK_CUR: 1,
    SEEK_END: 2,
    ZIP_CHECKCONS: 4,
    ZIP_EXCL: 2,
    ZIP_RDONLY: 16,
    ZIP_FL_OVERWRITE: 8192,
    ZIP_FL_COMPRESSED: 4,
    ZIP_OPSYS_DOS: 0x00,
    ZIP_OPSYS_AMIGA: 0x01,
    ZIP_OPSYS_OPENVMS: 0x02,
    ZIP_OPSYS_UNIX: 0x03,
    ZIP_OPSYS_VM_CMS: 0x04,
    ZIP_OPSYS_ATARI_ST: 0x05,
    ZIP_OPSYS_OS_2: 0x06,
    ZIP_OPSYS_MACINTOSH: 0x07,
    ZIP_OPSYS_Z_SYSTEM: 0x08,
    ZIP_OPSYS_CPM: 0x09,
    ZIP_OPSYS_WINDOWS_NTFS: 0x0a,
    ZIP_OPSYS_MVS: 0x0b,
    ZIP_OPSYS_VSE: 0x0c,
    ZIP_OPSYS_ACORN_RISC: 0x0d,
    ZIP_OPSYS_VFAT: 0x0e,
    ZIP_OPSYS_ALTERNATE_MVS: 0x0f,
    ZIP_OPSYS_BEOS: 0x10,
    ZIP_OPSYS_TANDEM: 0x11,
    ZIP_OPSYS_OS_400: 0x12,
    ZIP_OPSYS_OS_X: 0x13,
    ZIP_CM_DEFAULT: -1,
    ZIP_CM_STORE: 0,
    ZIP_CM_DEFLATE: 8,
    uint08S: emZip._malloc(1),
    uint16S: emZip._malloc(2),
    uint32S: emZip._malloc(4),
    uint64S: emZip._malloc(8),
    malloc: emZip._malloc,
    free: emZip._free,
    getValue: emZip.getValue,
    openFromSource: emZip.cwrap(`zip_open_from_source`, `number`, [`number`, `number`, `number`]),
    close: emZip.cwrap(`zip_close`, `number`, [`number`]),
    discard: emZip.cwrap(`zip_discard`, null, [`number`]),
    getError: emZip.cwrap(`zip_get_error`, `number`, [`number`]),
    getName: emZip.cwrap(`zip_get_name`, `string`, [`number`, `number`, `number`]),
    getNumEntries: emZip.cwrap(`zip_get_num_entries`, `number`, [`number`, `number`]),
    delete: emZip.cwrap(`zip_delete`, `number`, [`number`, `number`]),
    stat: emZip.cwrap(`zip_stat`, `number`, [`number`, `string`, `number`, `number`]),
    statIndex: emZip.cwrap(`zip_stat_index`, `number`, [`number`, ...number64, `number`, `number`]),
    fopen: emZip.cwrap(`zip_fopen`, `number`, [`number`, `string`, `number`]),
    fopenIndex: emZip.cwrap(`zip_fopen_index`, `number`, [`number`, ...number64, `number`]),
    fread: emZip.cwrap(`zip_fread`, `number`, [`number`, `number`, `number`, `number`]),
    fclose: emZip.cwrap(`zip_fclose`, `number`, [`number`]),
    dir: {
        add: emZip.cwrap(`zip_dir_add`, `number`, [`number`, `string`]),
    },
    file: {
        add: emZip.cwrap(`zip_file_add`, `number`, [`number`, `string`, `number`, `number`]),
        getError: emZip.cwrap(`zip_file_get_error`, `number`, [`number`]),
        getExternalAttributes: emZip.cwrap(`zip_file_get_external_attributes`, `number`, [`number`, ...number64, `number`, `number`, `number`]),
        setExternalAttributes: emZip.cwrap(`zip_file_set_external_attributes`, `number`, [`number`, ...number64, `number`, `number`, `number`]),
        setMtime: emZip.cwrap(`zip_file_set_mtime`, `number`, [`number`, ...number64, `number`, `number`]),
        setCompression: emZip.cwrap(`zip_set_file_compression`, `number`, [`number`, ...number64, `number`, `number`]),
    },
    ext: {
        countSymlinks: emZip.cwrap(`zip_ext_count_symlinks`, `number`, [`number`]),
    },
    error: {
        initWithCode: emZip.cwrap(`zip_error_init_with_code`, null, [`number`, `number`]),
        strerror: emZip.cwrap(`zip_error_strerror`, `string`, [`number`]),
    },
    name: {
        locate: emZip.cwrap(`zip_name_locate`, `number`, [`number`, `string`, `number`]),
    },
    source: {
        fromUnattachedBuffer: emZip.cwrap(`zip_source_buffer_create`, `number`, [`number`, ...number64, `number`, `number`]),
        fromBuffer: emZip.cwrap(`zip_source_buffer`, `number`, [`number`, `number`, ...number64, `number`]),
        free: emZip.cwrap(`zip_source_free`, null, [`number`]),
        keep: emZip.cwrap(`zip_source_keep`, null, [`number`]),
        open: emZip.cwrap(`zip_source_open`, `number`, [`number`]),
        close: emZip.cwrap(`zip_source_close`, `number`, [`number`]),
        seek: emZip.cwrap(`zip_source_seek`, `number`, [`number`, ...number64, `number`]),
        tell: emZip.cwrap(`zip_source_tell`, `number`, [`number`]),
        read: emZip.cwrap(`zip_source_read`, `number`, [`number`, `number`, `number`]),
        error: emZip.cwrap(`zip_source_error`, `number`, [`number`]),
        setMtime: emZip.cwrap(`zip_source_set_mtime`, `number`, [`number`, `number`]),
    },
    struct: {
        stat: emZip.cwrap(`zipstruct_stat`, `number`, []),
        statS: emZip.cwrap(`zipstruct_statS`, `number`, []),
        statName: emZip.cwrap(`zipstruct_stat_name`, `string`, [`number`]),
        statIndex: emZip.cwrap(`zipstruct_stat_index`, `number`, [`number`]),
        statSize: emZip.cwrap(`zipstruct_stat_size`, `number`, [`number`]),
        statCompSize: emZip.cwrap(`zipstruct_stat_comp_size`, `number`, [`number`]),
        statCompMethod: emZip.cwrap(`zipstruct_stat_comp_method`, `number`, [`number`]),
        statMtime: emZip.cwrap(`zipstruct_stat_mtime`, `number`, [`number`]),
        statCrc: emZip.cwrap(`zipstruct_stat_crc`, `number`, [`number`]),
        error: emZip.cwrap(`zipstruct_error`, `number`, []),
        errorS: emZip.cwrap(`zipstruct_errorS`, `number`, []),
        errorCodeZip: emZip.cwrap(`zipstruct_error_code_zip`, `number`, [`number`]),
    },
});
exports.makeInterface = makeInterface;


/***/ }),

/***/ 650:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.mountMemoryDrive = void 0;
const tslib_1 = __webpack_require__(240);
const fslib_1 = __webpack_require__(382);
const fs_1 = tslib_1.__importDefault(__webpack_require__(147));
const ZipFS_1 = __webpack_require__(154);
function mountMemoryDrive(origFs, mountPoint, source = Buffer.alloc(0), opts) {
    const archive = new ZipFS_1.ZipFS(source);
    const getMountPoint = (p) => {
        const detectedMountPoint = p === mountPoint || p.startsWith(`${mountPoint}/`) ? p.slice(0, mountPoint.length) : null;
        return detectedMountPoint;
    };
    const factoryPromise = async (baseFs, p) => {
        return () => archive;
    };
    const factorySync = (baseFs, p) => {
        return archive;
    };
    // We must copy the fs into a local, because otherwise
    // 1. we would make the NodeFS instance use the function that we patched (infinite loop)
    // 2. Object.create(fs) isn't enough, since it won't prevent the proto from being modified
    const localFs = { ...origFs };
    const nodeFs = new fslib_1.NodeFS(localFs);
    const mountFs = new fslib_1.MountFS({
        baseFs: nodeFs,
        getMountPoint,
        factoryPromise,
        factorySync,
        magicByte: 21,
        maxAge: Infinity,
        typeCheck: opts === null || opts === void 0 ? void 0 : opts.typeCheck,
    });
    (0, fslib_1.patchFs)(fs_1.default, new fslib_1.PosixFS(mountFs));
    return archive;
}
exports.mountMemoryDrive = mountMemoryDrive;


/***/ }),

/***/ 32:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {

"use strict";

Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.getLibzipPromise = exports.getLibzipSync = void 0;
const tslib_1 = __webpack_require__(240);
const instance_1 = __webpack_require__(309);
const libzipSync_1 = tslib_1.__importDefault(__webpack_require__(161));
const makeInterface_1 = __webpack_require__(815);
tslib_1.__exportStar(__webpack_require__(763), exports);
(0, instance_1.setFactory)(() => {
    const emZip = (0, libzipSync_1.default)();
    return (0, makeInterface_1.makeInterface)(emZip);
});
function getLibzipSync() {
    return (0, instance_1.getInstance)();
}
exports.getLibzipSync = getLibzipSync;
async function getLibzipPromise() {
    return (0, instance_1.getInstance)();
}
exports.getLibzipPromise = getLibzipPromise;


/***/ }),

/***/ 240:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "__assign": () => (/* binding */ __assign),
/* harmony export */   "__asyncDelegator": () => (/* binding */ __asyncDelegator),
/* harmony export */   "__asyncGenerator": () => (/* binding */ __asyncGenerator),
/* harmony export */   "__asyncValues": () => (/* binding */ __asyncValues),
/* harmony export */   "__await": () => (/* binding */ __await),
/* harmony export */   "__awaiter": () => (/* binding */ __awaiter),
/* harmony export */   "__classPrivateFieldGet": () => (/* binding */ __classPrivateFieldGet),
/* harmony export */   "__classPrivateFieldIn": () => (/* binding */ __classPrivateFieldIn),
/* harmony export */   "__classPrivateFieldSet": () => (/* binding */ __classPrivateFieldSet),
/* harmony export */   "__createBinding": () => (/* binding */ __createBinding),
/* harmony export */   "__decorate": () => (/* binding */ __decorate),
/* harmony export */   "__esDecorate": () => (/* binding */ __esDecorate),
/* harmony export */   "__exportStar": () => (/* binding */ __exportStar),
/* harmony export */   "__extends": () => (/* binding */ __extends),
/* harmony export */   "__generator": () => (/* binding */ __generator),
/* harmony export */   "__importDefault": () => (/* binding */ __importDefault),
/* harmony export */   "__importStar": () => (/* binding */ __importStar),
/* harmony export */   "__makeTemplateObject": () => (/* binding */ __makeTemplateObject),
/* harmony export */   "__metadata": () => (/* binding */ __metadata),
/* harmony export */   "__param": () => (/* binding */ __param),
/* harmony export */   "__propKey": () => (/* binding */ __propKey),
/* harmony export */   "__read": () => (/* binding */ __read),
/* harmony export */   "__rest": () => (/* binding */ __rest),
/* harmony export */   "__runInitializers": () => (/* binding */ __runInitializers),
/* harmony export */   "__setFunctionName": () => (/* binding */ __setFunctionName),
/* harmony export */   "__spread": () => (/* binding */ __spread),
/* harmony export */   "__spreadArray": () => (/* binding */ __spreadArray),
/* harmony export */   "__spreadArrays": () => (/* binding */ __spreadArrays),
/* harmony export */   "__values": () => (/* binding */ __values)
/* harmony export */ });
/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

function __extends(d, b) {
    if (typeof b !== "function" && b !== null)
        throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var __assign = function() {
    __assign = Object.assign || function __assign(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
    }
    return __assign.apply(this, arguments);
}

function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

function __decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}

function __param(paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
}

function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.push(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.push(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};

function __runInitializers(thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};

function __propKey(x) {
    return typeof x === "symbol" ? x : "".concat(x);
};

function __setFunctionName(f, name, prefix) {
    if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
    return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};

function __metadata(metadataKey, metadataValue) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
}

var __createBinding = Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
});

function __exportStar(m, o) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}

function __values(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}

function __read(o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
}

/** @deprecated */
function __spread() {
    for (var ar = [], i = 0; i < arguments.length; i++)
        ar = ar.concat(__read(arguments[i]));
    return ar;
}

/** @deprecated */
function __spreadArrays() {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
}

function __spreadArray(to, from, pack) {
    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
        if (ar || !(i in from)) {
            if (!ar) ar = Array.prototype.slice.call(from, 0, i);
            ar[i] = from[i];
        }
    }
    return to.concat(ar || Array.prototype.slice.call(from));
}

function __await(v) {
    return this instanceof __await ? (this.v = v, this) : new __await(v);
}

function __asyncGenerator(thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}

function __asyncDelegator(o) {
    var i, p;
    return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
}

function __asyncValues(o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}

function __makeTemplateObject(cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};

var __setModuleDefault = Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
};

function __importStar(mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
}

function __importDefault(mod) {
    return (mod && mod.__esModule) ? mod : { default: mod };
}

function __classPrivateFieldGet(receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}

function __classPrivateFieldSet(receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
}

function __classPrivateFieldIn(state, receiver) {
    if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
    return typeof state === "function" ? receiver === state : state.has(receiver);
}


/***/ }),

/***/ 113:
/***/ ((module) => {

"use strict";
module.exports = require("crypto");

/***/ }),

/***/ 361:
/***/ ((module) => {

"use strict";
module.exports = require("events");

/***/ }),

/***/ 147:
/***/ ((module) => {

"use strict";
module.exports = require("fs");

/***/ }),

/***/ 37:
/***/ ((module) => {

"use strict";
module.exports = require("os");

/***/ }),

/***/ 17:
/***/ ((module) => {

"use strict";
module.exports = require("path");

/***/ }),

/***/ 521:
/***/ ((module) => {

"use strict";
module.exports = require("readline");

/***/ }),

/***/ 955:
/***/ ((module) => {

"use strict";
module.exports = require("stream");

/***/ }),

/***/ 310:
/***/ ((module) => {

"use strict";
module.exports = require("url");

/***/ }),

/***/ 837:
/***/ ((module) => {

"use strict";
module.exports = require("util");

/***/ }),

/***/ 796:
/***/ ((module) => {

"use strict";
module.exports = require("zlib");

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/define property getters */
/******/ 	(() => {
/******/ 		// define getter functions for harmony exports
/******/ 		__webpack_require__.d = (exports, definition) => {
/******/ 			for(var key in definition) {
/******/ 				if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
/******/ 					Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
/******/ 				}
/******/ 			}
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/hasOwnProperty shorthand */
/******/ 	(() => {
/******/ 		__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, {
  "restoreFs": () => (/* binding */ restoreFs),
  "shimFs": () => (/* binding */ shimFs)
});

// EXTERNAL MODULE: ./node_modules/@yarnpkg/libzip/lib/sync.js
var sync = __webpack_require__(32);
// EXTERNAL MODULE: ./node_modules/@yarnpkg/fslib/lib/index.js
var lib = __webpack_require__(382);
// EXTERNAL MODULE: external "path"
var external_path_ = __webpack_require__(17);
// EXTERNAL MODULE: external "fs"
var external_fs_ = __webpack_require__(147);
;// CONCATENATED MODULE: ./src/fs/SnapshotZipFS.ts
var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};




const uniqBy = (arr, pick) => {
    const seen = new Set();
    return arr.filter((x) => {
        const key = pick(x);
        if (seen.has(key))
            return false;
        seen.add(key);
        return true;
    });
};
function uniqReaddir(arr) {
    return uniqBy(arr, (s) => (typeof s === 'string' ? s : s.name));
}
class SnapshotZipFS extends lib.BasePortableFakeFS {
    constructor(opts) {
        super();
        this.fdMap = new Map();
        this.nextFd = 3;
        this.accessPromise = sync.ZipOpenFS.prototype.accessPromise;
        this.accessSync = sync.ZipOpenFS.prototype.accessSync;
        this.appendFilePromise = sync.ZipOpenFS.prototype.appendFilePromise;
        this.appendFileSync = sync.ZipOpenFS.prototype.appendFileSync;
        this.chmodPromise = sync.ZipOpenFS.prototype.chmodPromise;
        this.chmodSync = sync.ZipOpenFS.prototype.chmodSync;
        this.fchmodPromise = sync.ZipOpenFS.prototype.fchmodPromise;
        this.fchmodSync = sync.ZipOpenFS.prototype.fchmodSync;
        this.chownPromise = sync.ZipOpenFS.prototype.chownPromise;
        this.chownSync = sync.ZipOpenFS.prototype.chownSync;
        this.fchownPromise = sync.ZipOpenFS.prototype.fchownPromise;
        this.fchownSync = sync.ZipOpenFS.prototype.fchownSync;
        this.closePromise = sync.ZipOpenFS.prototype.closePromise;
        this.closeSync = sync.ZipOpenFS.prototype.closeSync;
        this.createReadStream = sync.ZipOpenFS.prototype.createReadStream;
        this.createWriteStream = sync.ZipOpenFS.prototype.createWriteStream;
        this.existsPromise = sync.ZipOpenFS.prototype.existsPromise;
        this.existsSync = sync.ZipOpenFS.prototype.existsSync;
        this.fstatPromise = sync.ZipOpenFS.prototype.fstatPromise;
        this.fstatSync = sync.ZipOpenFS.prototype.fstatSync;
        this.getExtractHint = sync.ZipOpenFS.prototype.getExtractHint;
        this.getRealPath = sync.ZipOpenFS.prototype.getRealPath;
        this.linkPromise = sync.ZipOpenFS.prototype.linkPromise;
        this.linkSync = sync.ZipOpenFS.prototype.linkSync;
        this.lstatPromise = sync.ZipOpenFS.prototype.lstatPromise;
        this.lstatSync = sync.ZipOpenFS.prototype.lstatSync;
        this.openPromise = sync.ZipOpenFS.prototype.openPromise;
        this.openSync = sync.ZipOpenFS.prototype.openSync;
        this.readFilePromise = sync.ZipOpenFS.prototype.readFilePromise;
        this.readFileSync = sync.ZipOpenFS.prototype.readFileSync;
        this.readlinkPromise = sync.ZipOpenFS.prototype.readlinkPromise;
        this.readlinkSync = sync.ZipOpenFS.prototype.readlinkSync;
        this.readPromise = sync.ZipOpenFS.prototype.readPromise;
        this.readSync = sync.ZipOpenFS.prototype.readSync;
        this.renamePromise = sync.ZipOpenFS.prototype.renamePromise;
        this.renameSync = sync.ZipOpenFS.prototype.renameSync;
        this.resolve = sync.ZipOpenFS.prototype.resolve;
        this.statPromise = sync.ZipOpenFS.prototype.statPromise;
        this.statSync = sync.ZipOpenFS.prototype.statSync;
        this.symlinkPromise = sync.ZipOpenFS.prototype.symlinkPromise;
        this.symlinkSync = sync.ZipOpenFS.prototype.symlinkSync;
        this.truncatePromise = sync.ZipOpenFS.prototype.truncatePromise;
        this.truncateSync = sync.ZipOpenFS.prototype.truncateSync;
        this.ftruncatePromise = sync.ZipOpenFS.prototype.ftruncatePromise;
        this.ftruncateSync = sync.ZipOpenFS.prototype.ftruncateSync;
        this.unlinkPromise = sync.ZipOpenFS.prototype.unlinkPromise;
        this.unlinkSync = sync.ZipOpenFS.prototype.unlinkSync;
        this.unwatchFile = sync.ZipOpenFS.prototype.unwatchFile;
        this.utimesPromise = sync.ZipOpenFS.prototype.utimesPromise;
        this.utimesSync = sync.ZipOpenFS.prototype.utimesSync;
        this.lutimesPromise = sync.ZipOpenFS.prototype.utimesPromise;
        this.lutimesSync = sync.ZipOpenFS.prototype.utimesSync;
        this.watch = sync.ZipOpenFS.prototype.watch;
        this.watchFile = sync.ZipOpenFS.prototype.watchFile;
        this.writeFilePromise = sync.ZipOpenFS.prototype.writeFilePromise;
        this.writeFileSync = sync.ZipOpenFS.prototype.writeFileSync;
        this.writePromise = sync.ZipOpenFS.prototype.writePromise;
        this.writeSync = sync.ZipOpenFS.prototype.writeSync;
        // @ts-ignore
        this.remapFd = sync.ZipOpenFS.prototype.remapFd;
        this.zipFs = opts.zipFs;
        this.baseFs = opts.baseFs;
        this.root = opts.root;
        this.magic = 0x2a << 24;
    }
    makeCallPromise(p, discard, accept, { requireSubpath = true } = {}) {
        return __awaiter(this, void 0, void 0, function* () {
            if (typeof p !== 'string')
                return yield discard();
            const normalizedP = this.resolve(p);
            const zipInfo = this.findZip(normalizedP);
            if (!zipInfo)
                return yield discard();
            if (requireSubpath && zipInfo.subPath === '/')
                return yield discard();
            return yield accept(this.zipFs, zipInfo);
        });
    }
    makeCallSync(p, discard, accept, { requireSubpath = true } = {}) {
        if (typeof p !== 'string')
            return discard();
        const normalizedP = this.resolve(p);
        const zipInfo = this.findZip(normalizedP);
        if (!zipInfo)
            return discard();
        if (requireSubpath && zipInfo.subPath === '/')
            return discard();
        return accept(this.zipFs, Object.assign({ archivePath: '' }, zipInfo));
    }
    realpathPromise(p) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.realpathSync(p);
        });
    }
    realpathSync(p) {
        return this.makeCallSync(p, () => this.baseFs.realpathSync(p), (zipFs, { subPath }) => {
            if (zipFs.lstatSync(subPath).isSymbolicLink()) {
                return zipFs.realpathSync(subPath);
            }
            else {
                // return the original path in case it wasn't under /snapshot, e.g. if it was for a node module - otherwise the node module parent path is the wrong one (and other things resolve relative to that)
                return p;
            }
        });
    }
    findZip(p) {
        p = this.resolve(p);
        const snapshotPP = lib.npath.toPortablePath('/snapshot');
        const pathsToTry = Array.from(new Set([
            p,
            (0,external_path_.resolve)('/snapshot', p),
            lib.ppath.resolve(snapshotPP, lib.npath.toPortablePath(lib.npath.relative(lib.npath.fromPortablePath(this.root), lib.npath.fromPortablePath(p)))),
            lib.ppath.resolve(snapshotPP, lib.npath.toPortablePath(lib.npath.relative((0,external_path_.toNamespacedPath)(lib.npath.fromPortablePath(this.root)), (0,external_path_.toNamespacedPath)(lib.npath.fromPortablePath(p))))),
            lib.ppath.resolve(snapshotPP, lib.npath.toPortablePath(lib.npath.relative(lib.npath.fromPortablePath(process.cwd()), lib.npath.fromPortablePath(p)))),
            lib.ppath.resolve(snapshotPP, lib.npath.toPortablePath(lib.npath.relative((0,external_path_.toNamespacedPath)(lib.npath.fromPortablePath(process.cwd())), (0,external_path_.toNamespacedPath)(lib.npath.fromPortablePath(p))))),
        ]));
        for (const path of pathsToTry) {
            const portablePath = lib.npath.toPortablePath(path);
            if (this.zipFs.existsSync(portablePath)) {
                return {
                    subPath: portablePath,
                };
            }
        }
    }
    copyFilePromise(sourceP, destP, flags = 0) {
        return __awaiter(this, void 0, void 0, function* () {
            const fallback = (sourceFs, sourceP, destFs, destP) => __awaiter(this, void 0, void 0, function* () {
                if ((flags & external_fs_.constants.COPYFILE_FICLONE_FORCE) !== 0)
                    throw Object.assign(new Error(`EXDEV: cross-device clone not permitted, copyfile '${sourceP}' -> ${destP}'`), { code: `EXDEV` });
                if (flags & external_fs_.constants.COPYFILE_EXCL && (yield this.existsPromise(sourceP)))
                    throw Object.assign(new Error(`EEXIST: file already exists, copyfile '${sourceP}' -> '${destP}'`), { code: `EEXIST` });
                let content;
                try {
                    content = yield sourceFs.readFilePromise(sourceP);
                }
                catch (error) {
                    throw Object.assign(new Error(`EINVAL: invalid argument, copyfile '${sourceP}' -> '${destP}'`), { code: `EINVAL` });
                }
                yield destFs.writeFilePromise(destP, content);
            });
            return yield this.makeCallPromise(sourceP, () => __awaiter(this, void 0, void 0, function* () {
                return yield this.baseFs.copyFilePromise(sourceP, destP, flags);
            }), (zipFsS, { subPath: subPathS }) => __awaiter(this, void 0, void 0, function* () {
                return yield fallback(zipFsS, subPathS, this.baseFs, destP);
            }));
        });
    }
    copyFileSync(sourceP, destP, flags = 0) {
        const fallback = (sourceFs, sourceP, destFs, destP) => {
            if ((flags & external_fs_.constants.COPYFILE_FICLONE_FORCE) !== 0)
                throw Object.assign(new Error(`EXDEV: cross-device clone not permitted, copyfile '${sourceP}' -> ${destP}'`), { code: `EXDEV` });
            if (flags & external_fs_.constants.COPYFILE_EXCL && this.existsSync(sourceP))
                throw Object.assign(new Error(`EEXIST: file already exists, copyfile '${sourceP}' -> '${destP}'`), { code: `EEXIST` });
            let content;
            try {
                content = sourceFs.readFileSync(sourceP);
            }
            catch (error) {
                throw Object.assign(new Error(`EINVAL: invalid argument, copyfile '${sourceP}' -> '${destP}'`), { code: `EINVAL` });
            }
            destFs.writeFileSync(destP, content);
        };
        return this.makeCallSync(sourceP, () => {
            return this.baseFs.copyFileSync(sourceP, destP, flags);
        }, (zipFsS, { subPath: subPathS }) => {
            return fallback(zipFsS, subPathS, this.baseFs, destP);
        });
    }
    readdirPromise(p, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            const fallback = () => __awaiter(this, void 0, void 0, function* () {
                return yield this.baseFs.readdirPromise(p, opts);
            });
            return yield this.makeCallPromise(p, fallback, (zipFs, { subPath }) => __awaiter(this, void 0, void 0, function* () {
                const fallbackPaths = yield fallback().catch(() => []);
                return Promise.resolve(uniqReaddir(fallbackPaths.concat(yield zipFs.readdirPromise(subPath, opts))));
            }), {
                requireSubpath: false,
            });
        });
    }
    readdirSync(p, opts) {
        const fallback = () => {
            return this.baseFs.readdirSync(p, opts);
        };
        return this.makeCallSync(p, fallback, (zipFs, { subPath }) => {
            let fallbackPaths = [];
            try {
                fallbackPaths = fallback();
            }
            catch (e) { }
            return fallbackPaths.concat(uniqReaddir(zipFs.readdirSync(subPath, opts)));
        }, {
            requireSubpath: false,
        });
    }
    mkdirPromise(p, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.baseFs.mkdirPromise(p, opts);
        });
    }
    mkdirSync(p, opts) {
        return this.baseFs.mkdirSync(p, opts);
    }
    rmdirPromise(p, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            return yield this.baseFs.rmdirPromise(p, opts);
        });
    }
    rmdirSync(p, opts) {
        return this.baseFs.rmdirSync(p, opts);
    }
    opendirPromise(p, opts) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.opendirSync(p, opts);
        });
    }
    opendirSync(p, opts) {
        const zipInfo = this.findZip(p);
        let zipFsDir = null;
        if (zipInfo) {
            zipFsDir = this.zipFs.opendirSync(zipInfo.subPath);
        }
        let realFsDir = null;
        try {
            realFsDir = this.baseFs.opendirSync(p);
        }
        catch (e) {
            if (!zipFsDir)
                throw e;
        }
        const seen = new Set();
        const nextDirent = () => {
            const entry = (realFsDir === null || realFsDir === void 0 ? void 0 : realFsDir.readSync()) || (zipFsDir === null || zipFsDir === void 0 ? void 0 : zipFsDir.readSync());
            if (entry && !seen.has(entry.name)) {
                seen.add(entry.name);
                return entry;
            }
            return null;
        };
        const onClose = () => {
            zipFsDir === null || zipFsDir === void 0 ? void 0 : zipFsDir.closeSync();
            realFsDir === null || realFsDir === void 0 ? void 0 : realFsDir.closeSync();
        };
        return new lib.CustomDir(p, nextDirent, { onClose });
    }
}

;// CONCATENATED MODULE: external "assert"
const external_assert_namespaceObject = require("assert");
;// CONCATENATED MODULE: external "constants"
const external_constants_namespaceObject = require("constants");
;// CONCATENATED MODULE: ./src/fs/patch.ts






let originalFsMethods = null;
let lazyRestoreFs = () => { };
const patches = process.nexe.patches || {};
const originalPatches = Object.assign({}, patches);
delete process.nexe;
function shimFs(binary, fs = __webpack_require__(147)) {
    if (originalFsMethods !== null) {
        return;
    }
    originalFsMethods = Object.assign({}, fs);
    const realFs = Object.assign({}, fs);
    const nodeFs = new lib.NodeFS(realFs);
    const blob = Buffer.allocUnsafe(binary.layout.resourceSize);
    const blobFd = realFs.openSync(binary.blobPath, 'r');
    const bytesRead = realFs.readSync(blobFd, blob, 0, binary.layout.resourceSize, binary.layout.resourceStart);
    external_assert_namespaceObject.equal(bytesRead, binary.layout.resourceSize);
    const zipFs = new sync.ZipFS(blob, { readOnly: true });
    const snapshotZipFS = new SnapshotZipFS({
        libzip: (0,sync.getLibzipSync)(),
        zipFs,
        baseFs: nodeFs,
        root: (0,external_path_.dirname)(process.argv[0]),
    });
    const posixSnapshotZipFs = new lib.PosixFS(snapshotZipFS);
    (0,lib.patchFs)(fs, posixSnapshotZipFs);
    let log = (_) => true;
    if ((process.env.DEBUG || '').toLowerCase().includes('nexe:require')) {
        process.stderr.write(
        // @ts-ignore
        `[nexe] - FILES ${JSON.stringify(Array.from(zipFs.entries.keys()), null, 4)}\n`);
        process.stderr.write(
        // @ts-ignore
        `[nexe] - DIRECTORIES ${JSON.stringify(Array.from(zipFs.listings.keys()), null, 4)}\n`);
        log = (text) => {
            return process.stderr.write(`[nexe] - ${text}\n`);
        };
    }
    function internalModuleReadFile(original, ...args) {
        log(`internalModuleReadFile ${args[0]}`);
        try {
            return posixSnapshotZipFs.readFileSync(args[0], 'utf-8');
        }
        catch (e) {
            return '';
        }
    }
    if (patches.internalModuleReadFile) {
        patches.internalModuleReadFile = internalModuleReadFile;
    }
    let returningArray;
    patches.internalModuleReadJSON = function (original, ...args) {
        if (returningArray == null)
            returningArray = Array.isArray(original.call(this, ''));
        const res = internalModuleReadFile.call(this, original, ...args);
        return returningArray && !Array.isArray(res)
            ? res === ''
                ? []
                : [res, /"(main|name|type|exports|imports)"/.test(res)]
            : res;
    };
    patches.internalModuleStat = function (original, ...args) {
        let statPath = args[0];
        //in node 22, the path arg moved to arg[1]
        if (typeof args[0] !== 'string')
            statPath = args[1];
        let result = 0;
        try {
            const stat = posixSnapshotZipFs.statSync(statPath);
            if (stat.isDirectory())
                result = 1;
            else
                result = 0;
        }
        catch (e) {
            result = -external_constants_namespaceObject.ENOENT;
        }
        log(`internalModuleStat ${result} ${statPath}`);
        return result;
    };
    lazyRestoreFs = () => {
        Object.assign(fs, originalFsMethods);
        Object.assign(patches, originalPatches);
        lazyRestoreFs = () => { };
    };
}
function restoreFs() {
    lazyRestoreFs();
}


})();

module.exports = __webpack_exports__;
/******/ })()
;
//# sourceMappingURL=patch.bundle.js.map