UNPKG

@dhelarius/entity-parser

Version:

Parse yours json objects to tsc entities

1,502 lines (1,487 loc) 586 kB
#!/usr/bin/env node /* eslint-disable */ "use strict"; function $$SETUP_STATE(hydrateRuntimeState, basePath) { return hydrateRuntimeState(JSON.parse('{\ "__info": [\ "This file is automatically generated. Do not touch it, or risk",\ "your modifications being lost. We also recommend you not to read",\ "it either without using the @yarnpkg/pnp package, as the data layout",\ "is entirely unspecified and WILL change from a version to another."\ ],\ "dependencyTreeRoots": [\ {\ "name": "@dhelarius/entity-parser",\ "reference": "workspace:."\ }\ ],\ "enableTopLevelFallback": true,\ "ignorePatternData": "(^(?:\\\\.yarn\\\\/sdks(?:\\\\/(?!\\\\.{1,2}(?:\\\\/|$))(?:(?:(?!(?:^|\\\\/)\\\\.{1,2}(?:\\\\/|$)).)*?)|$))$)",\ "fallbackExclusionList": [\ ["@dhelarius/entity-parser", ["workspace:."]]\ ],\ "fallbackPool": [\ ],\ "packageRegistryData": [\ [null, [\ [null, {\ "packageLocation": "./",\ "packageDependencies": [\ ],\ "linkType": "SOFT"\ }]\ ]],\ ["@dhelarius/entity-parser", [\ ["workspace:.", {\ "packageLocation": "./",\ "packageDependencies": [\ ["@dhelarius/entity-parser", "workspace:."]\ ],\ "linkType": "SOFT"\ }]\ ]]\ ]\ }'), {basePath: basePath || __dirname}); } const fs = require('fs'); const path = require('path'); const require$$0 = require('module'); const StringDecoder = require('string_decoder'); const url = require('url'); const os = require('os'); const nodeUtils = require('util'); const assert = require('assert'); const stream = require('stream'); const zlib = require('zlib'); const events = require('events'); const _interopDefaultLegacy = e => e && typeof e === 'object' && 'default' in e ? e : { default: e }; function _interopNamespace(e) { if (e && e.__esModule) return e; const n = Object.create(null); if (e) { for (const k in e) { if (k !== 'default') { const d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: () => e[k] }); } } } n.default = e; return Object.freeze(n); } const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs); const path__default = /*#__PURE__*/_interopDefaultLegacy(path); const require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0); const StringDecoder__default = /*#__PURE__*/_interopDefaultLegacy(StringDecoder); const nodeUtils__namespace = /*#__PURE__*/_interopNamespace(nodeUtils); const assert__default = /*#__PURE__*/_interopDefaultLegacy(assert); const zlib__default = /*#__PURE__*/_interopDefaultLegacy(zlib); const S_IFMT = 61440; const S_IFDIR = 16384; const S_IFREG = 32768; const S_IFLNK = 40960; const SAFE_TIME = 456789e3; const DEFAULT_MODE = S_IFREG | 420; 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 = DEFAULT_MODE; this.nlink = 1; this.rdev = 0; this.blocks = 1; } isBlockDevice() { return false; } isCharacterDevice() { return false; } isDirectory() { return (this.mode & S_IFMT) === S_IFDIR; } isFIFO() { return false; } isFile() { return (this.mode & S_IFMT) === S_IFREG; } isSocket() { return false; } isSymbolicLink() { return (this.mode & S_IFMT) === S_IFLNK; } } class BigIntStatsEntry { 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(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(S_IFMT)) === BigInt(S_IFDIR); } isFIFO() { return false; } isFile() { return (this.mode & BigInt(S_IFMT)) === BigInt(S_IFREG); } isSocket() { return false; } isSymbolicLink() { return (this.mode & BigInt(S_IFMT)) === BigInt(S_IFLNK); } } function makeDefaultStats() { return new StatEntry(); } function clearStats(stats) { for (const key in stats) { if (Object.prototype.hasOwnProperty.call(stats, key)) { const element = stats[key]; if (typeof element === `number`) { stats[key] = 0; } else if (typeof element === `bigint`) { stats[key] = BigInt(0); } else if (nodeUtils__namespace.types.isDate(element)) { stats[key] = new Date(0); } } } return stats; } 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`) { bigintStats[key] = BigInt(element); } else if (nodeUtils__namespace.types.isDate(element)) { bigintStats[key] = new Date(element); } } } bigintStats.atimeNs = bigintStats.atimeMs * BigInt(1e6); bigintStats.mtimeNs = bigintStats.mtimeMs * BigInt(1e6); bigintStats.ctimeNs = bigintStats.ctimeMs * BigInt(1e6); bigintStats.birthtimeNs = bigintStats.birthtimeMs * BigInt(1e6); return bigintStats; } function areStatsEqual(a, b) { if (a.atimeMs !== b.atimeMs) return false; if (a.birthtimeMs !== b.birthtimeMs) return false; if (a.blksize !== b.blksize) return false; if (a.blocks !== b.blocks) return false; if (a.ctimeMs !== b.ctimeMs) return false; if (a.dev !== b.dev) return false; if (a.gid !== b.gid) return false; if (a.ino !== b.ino) return false; if (a.isBlockDevice() !== b.isBlockDevice()) return false; if (a.isCharacterDevice() !== b.isCharacterDevice()) return false; if (a.isDirectory() !== b.isDirectory()) return false; if (a.isFIFO() !== b.isFIFO()) return false; if (a.isFile() !== b.isFile()) return false; if (a.isSocket() !== b.isSocket()) return false; if (a.isSymbolicLink() !== b.isSymbolicLink()) return false; if (a.mode !== b.mode) return false; if (a.mtimeMs !== b.mtimeMs) return false; if (a.nlink !== b.nlink) return false; if (a.rdev !== b.rdev) return false; if (a.size !== b.size) return false; if (a.uid !== b.uid) return false; const aN = a; const bN = b; if (aN.atimeNs !== bN.atimeNs) return false; if (aN.mtimeNs !== bN.mtimeNs) return false; if (aN.ctimeNs !== bN.ctimeNs) return false; if (aN.birthtimeNs !== bN.birthtimeNs) return false; return true; } const PortablePath = { root: `/`, dot: `.`, parent: `..` }; const Filename = { nodeModules: `node_modules`, manifest: `package.json`, lockfile: `yarn.lock`, virtual: `__virtual__`, pnpJs: `.pnp.js`, pnpCjs: `.pnp.cjs`, rc: `.yarnrc.yml` }; const npath = Object.create(path__default.default); const ppath = Object.create(path__default.default.posix); npath.cwd = () => process.cwd(); ppath.cwd = () => toPortablePath(process.cwd()); ppath.resolve = (...segments) => { if (segments.length > 0 && ppath.isAbsolute(segments[0])) { return path__default.default.posix.resolve(...segments); } else { return path__default.default.posix.resolve(ppath.cwd(), ...segments); } }; const contains = function(pathUtils, from, to) { from = pathUtils.normalize(from); to = pathUtils.normalize(to); if (from === to) return `.`; if (!from.endsWith(pathUtils.sep)) from = from + pathUtils.sep; if (to.startsWith(from)) { return to.slice(from.length); } else { return null; } }; npath.fromPortablePath = fromPortablePath; npath.toPortablePath = toPortablePath; npath.contains = (from, to) => contains(npath, from, to); ppath.contains = (from, to) => contains(ppath, from, to); const WINDOWS_PATH_REGEXP = /^([a-zA-Z]:.*)$/; const UNC_WINDOWS_PATH_REGEXP = /^\/\/(\.\/)?(.*)$/; const PORTABLE_PATH_REGEXP = /^\/([a-zA-Z]:.*)$/; const UNC_PORTABLE_PATH_REGEXP = /^\/unc\/(\.dot\/)?(.*)$/; function 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, `\\`); } 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 === npath ? fromPortablePath(sourcePath) : toPortablePath(sourcePath); } const defaultTime = new Date(SAFE_TIME * 1e3); 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] }); const updateTime = typeof destinationFs.lutimesPromise === `function` ? destinationFs.lutimesPromise.bind(destinationFs) : destinationFs.utimesPromise.bind(destinationFs); await copyImpl(prelayout, postlayout, updateTime, destinationFs, normalizedDestination, sourceFs, normalizedSource, { ...opts, didParentExist: true }); for (const operation of prelayout) await operation(); await Promise.all(postlayout.map((operation) => { return operation(); })); } async function copyImpl(prelayout, postlayout, updateTime, destinationFs, destination, sourceFs, source, opts) { var _a, _b; 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, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts); } break; case sourceStat.isFile(): { updated = await copyFile(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts); } break; case sourceStat.isSymbolicLink(): { updated = await copySymlink(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts); } break; default: { throw new Error(`Unsupported file type (${sourceStat.mode})`); } } if (updated || ((_a = destinationStat == null ? void 0 : destinationStat.mtime) == null ? void 0 : _a.getTime()) !== mtime.getTime() || ((_b = destinationStat == null ? void 0 : destinationStat.atime) == null ? void 0 : _b.getTime()) !== atime.getTime()) { postlayout.push(() => updateTime(destination, atime, mtime)); updated = true; } if (destinationStat === null || (destinationStat.mode & 511) !== (sourceStat.mode & 511)) { postlayout.push(() => destinationFs.chmodPromise(destination, sourceStat.mode & 511)); updated = true; } return updated; } async function maybeLStat(baseFs, p) { try { return await baseFs.lstatPromise(p); } catch (e) { return null; } } async function copyFolder(prelayout, postlayout, updateTime, 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, updateTime, 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, updateTime, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), nextOpts); })); if (entriesUpdateStatus.some((status) => status)) { updated = true; } } return updated; } const isCloneSupportedCache = /* @__PURE__ */ new WeakMap(); function makeLinkOperation(opFs, destination, source, sourceStat, linkStrategy) { return async () => { await opFs.linkPromise(source, destination); if (linkStrategy === "readOnly" /* ReadOnly */) { sourceStat.mode &= ~146; await opFs.chmodPromise(destination, sourceStat.mode); } }; } function makeCloneLinkOperation(opFs, destination, source, sourceStat, linkStrategy) { const isCloneSupported = isCloneSupportedCache.get(opFs); if (typeof isCloneSupported === `undefined`) { return async () => { try { await opFs.copyFilePromise(source, destination, fs__default.default.constants.COPYFILE_FICLONE_FORCE); isCloneSupportedCache.set(opFs, true); } catch (err) { if (err.code === `ENOSYS` || err.code === `ENOTSUP`) { isCloneSupportedCache.set(opFs, false); await makeLinkOperation(opFs, destination, source, sourceStat, linkStrategy)(); } else { throw err; } } }; } else { if (isCloneSupported) { return async () => opFs.copyFilePromise(source, destination, fs__default.default.constants.COPYFILE_FICLONE_FORCE); } else { return makeLinkOperation(opFs, destination, source, sourceStat, linkStrategy); } } } async function copyFile(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) { var _a; if (destinationStat !== null) { if (opts.overwrite) { prelayout.push(async () => destinationFs.removePromise(destination)); destinationStat = null; } else { return false; } } const linkStrategy = (_a = opts.linkStrategy) != null ? _a : null; const op = destinationFs === sourceFs ? linkStrategy !== null ? makeCloneLinkOperation(destinationFs, destination, source, sourceStat, linkStrategy) : async () => destinationFs.copyFilePromise(source, destination, fs__default.default.constants.COPYFILE_FICLONE) : linkStrategy !== null ? makeLinkOperation(destinationFs, destination, source, sourceStat, linkStrategy) : async () => destinationFs.writeFilePromise(destination, await sourceFs.readFilePromise(source)); prelayout.push(async () => op()); return true; } async function copySymlink(prelayout, postlayout, updateTime, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) { if (destinationStat !== null) { if (opts.overwrite) { prelayout.push(async () => destinationFs.removePromise(destination)); destinationStat = null; } else { return false; } } prelayout.push(async () => { await destinationFs.symlinkPromise(convertPath(destinationFs.pathUtils, await sourceFs.readlinkPromise(source)), destination); }); return true; } function makeError$1(code, message) { return Object.assign(new Error(`${code}: ${message}`), { code }); } function EBUSY(message) { return makeError$1(`EBUSY`, message); } function ENOSYS(message, reason) { return makeError$1(`ENOSYS`, `${message}, ${reason}`); } function EINVAL(reason) { return makeError$1(`EINVAL`, `invalid argument, ${reason}`); } function EBADF(reason) { return makeError$1(`EBADF`, `bad file descriptor, ${reason}`); } function ENOENT(reason) { return makeError$1(`ENOENT`, `no such file or directory, ${reason}`); } function ENOTDIR(reason) { return makeError$1(`ENOTDIR`, `not a directory, ${reason}`); } function EISDIR(reason) { return makeError$1(`EISDIR`, `illegal operation on a directory, ${reason}`); } function EEXIST(reason) { return makeError$1(`EEXIST`, `file already exists, ${reason}`); } function EROFS(reason) { return makeError$1(`EROFS`, `read-only filesystem, ${reason}`); } function ENOTEMPTY(reason) { return makeError$1(`ENOTEMPTY`, `directory not empty, ${reason}`); } function EOPNOTSUPP(reason) { return makeError$1(`EOPNOTSUPP`, `operation not supported, ${reason}`); } function ERR_DIR_CLOSED() { return makeError$1(`ERR_DIR_CLOSED`, `Directory handle was closed`); } class LibzipError extends Error { constructor(message, code) { super(message); this.name = `Libzip Error`; this.code = code; } } class CustomDir { constructor(path, nextDirent, opts = {}) { this.path = path; this.nextDirent = nextDirent; this.opts = opts; this.closed = false; } throwIfClosed() { if (this.closed) { throw ERR_DIR_CLOSED(); } } async *[Symbol.asyncIterator]() { try { let dirent; while ((dirent = await this.read()) !== null) { yield dirent; } } finally { await this.close(); } } read(cb) { const dirent = this.readSync(); if (typeof cb !== `undefined`) return cb(null, dirent); return Promise.resolve(dirent); } readSync() { this.throwIfClosed(); return this.nextDirent(); } close(cb) { this.closeSync(); if (typeof cb !== `undefined`) return cb(null); return Promise.resolve(); } closeSync() { var _a, _b; this.throwIfClosed(); (_b = (_a = this.opts).onClose) == null ? void 0 : _b.call(_a); this.closed = true; } } 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); } 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 entry2 of entries.sort()) { stack.push(this.pathUtils.join(p, entry2)); } } else { throw new Error(`Not supported`); } } else { yield p; } } } async removePromise(p, { recursive = true, maxRetries = 5 } = {}) { let stat; try { stat = await this.lstatPromise(p); } catch (error) { if (error.code === `ENOENT`) { return; } else { throw error; } } if (stat.isDirectory()) { if (recursive) { const entries = await this.readdirPromise(p); await Promise.all(entries.map((entry) => { return this.removePromise(this.pathUtils.resolve(p, entry)); })); } for (let t = 0; t <= maxRetries; t++) { try { await this.rmdirPromise(p); break; } catch (error) { if (error.code !== `EBUSY` && error.code !== `ENOTEMPTY`) { throw error; } else if (t < maxRetries) { await new Promise((resolve) => setTimeout(resolve, t * 100)); } } } } else { await this.unlinkPromise(p); } } removeSync(p, { recursive = true } = {}) { let stat; try { stat = this.lstatSync(p); } catch (error) { if (error.code === `ENOENT`) { return; } else { throw error; } } if (stat.isDirectory()) { if (recursive) for (const entry of this.readdirSync(p)) this.removeSync(this.pathUtils.resolve(p, entry)); this.rmdirSync(p); } else { this.unlinkSync(p); } } async mkdirpPromise(p, { chmod, utimes } = {}) { p = this.resolve(p); if (p === this.pathUtils.dirname(p)) return void 0; const parts = p.split(this.pathUtils.sep); let createdDirectory; for (let u = 2; u <= parts.length; ++u) { const subPath = parts.slice(0, u).join(this.pathUtils.sep); if (!this.existsSync(subPath)) { try { await this.mkdirPromise(subPath); } catch (error) { if (error.code === `EEXIST`) { continue; } else { throw error; } } createdDirectory != null ? 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 void 0; const parts = p.split(this.pathUtils.sep); let createdDirectory; for (let u = 2; u <= parts.length; ++u) { const subPath = parts.slice(0, u).join(this.pathUtils.sep); if (!this.existsSync(subPath)) { try { this.mkdirSync(subPath); } catch (error) { if (error.code === `EEXIST`) { continue; } else { throw error; } } createdDirectory != null ? 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 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(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 & 511; 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) { } 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) { } 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) { } 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) { } 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 = 1e3 / 60; const startTime = Date.now(); let fd = null; const isAlive = async () => { let pid; try { [pid] = await this.readJsonPromise(lockPath); } catch (error) { return Date.now() - startTime < 500; } try { 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 (error2) { } } if (Date.now() - startTime < 60 * 1e3) { 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 { await this.closePromise(fd); await this.unlinkPromise(lockPath); } catch (error) { } } } 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)} `); } writeJsonSync(p, data) { return this.writeFileSync(p, `${JSON.stringify(data, null, 2)} `); } async preserveTimePromise(p, cb) { const stat = await this.lstatPromise(p); const result = await cb(); if (typeof result !== `undefined`) p = result; if (this.lutimesPromise) { await this.lutimesPromise(p, stat.atime, stat.mtime); } else if (!stat.isSymbolicLink()) { await this.utimesPromise(p, stat.atime, stat.mtime); } } async preserveTimeSync(p, cb) { const stat = this.lstatSync(p); const result = cb(); if (typeof result !== `undefined`) p = result; if (this.lutimesSync) { this.lutimesSync(p, stat.atime, stat.mtime); } else if (!stat.isSymbolicLink()) { this.utimesSync(p, stat.atime, stat.mtime); } } } class BasePortableFakeFS extends FakeFS { constructor() { super(ppath); } } function getEndOfLine(content) { const matches = content.match(/\r?\n/g); if (matches === null) return os.EOL; const crlf = matches.filter((nl) => nl === `\r `).length; const lf = matches.length - crlf; return crlf > lf ? `\r ` : ` `; } function normalizeLineEndings(originalContent, newContent) { return newContent.replace(/\r?\n/g, getEndOfLine(originalContent)); } class NodeFS extends BasePortableFakeFS { constructor(realFs = fs__default.default) { super(); this.realFs = realFs; if (typeof this.realFs.lutimes !== `undefined`) { this.lutimesPromise = this.lutimesPromiseImpl; this.lutimesSync = this.lutimesSyncImpl; } } getExtractHint() { return false; } getRealPath() { return PortablePath.root; } resolve(p) { return ppath.resolve(p); } async openPromise(p, flags, mode) { return await new Promise((resolve, reject) => { this.realFs.open(npath.fromPortablePath(p), flags, mode, this.makeCallback(resolve, reject)); }); } openSync(p, flags, mode) { return this.realFs.openSync(npath.fromPortablePath(p), flags, mode); } async opendirPromise(p, opts) { return await new Promise((resolve, reject) => { if (typeof opts !== `undefined`) { this.realFs.opendir(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject)); } else { this.realFs.opendir(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(npath.fromPortablePath(p), opts) : this.realFs.opendirSync(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 ? npath.fromPortablePath(p) : p; return this.realFs.createReadStream(realPath, opts); } createWriteStream(p, opts) { const realPath = p !== null ? npath.fromPortablePath(p) : p; return this.realFs.createWriteStream(realPath, opts); } async realpathPromise(p) { return await new Promise((resolve, reject) => { this.realFs.realpath(npath.fromPortablePath(p), {}, this.makeCallback(resolve, reject)); }).then((path) => { return npath.toPortablePath(path); }); } realpathSync(p) { return npath.toPortablePath(this.realFs.realpathSync(npath.fromPortablePath(p), {})); } async existsPromise(p) { return await new Promise((resolve) => { this.realFs.exists(npath.fromPortablePath(p), resolve); }); } accessSync(p, mode) { return this.realFs.accessSync(npath.fromPortablePath(p), mode); } async accessPromise(p, mode) { return await new Promise((resolve, reject) => { this.realFs.access(npath.fromPortablePath(p), mode, this.makeCallback(resolve, reject)); }); } existsSync(p) { return this.realFs.existsSync(npath.fromPortablePath(p)); } async statPromise(p, opts) { return await new Promise((resolve, reject) => { if (opts) { this.realFs.stat(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject)); } else { this.realFs.stat(npath.fromPortablePath(p), this.makeCallback(resolve, reject)); } }); } statSync(p, opts) { if (opts) { return this.realFs.statSync(npath.fromPortablePath(p), opts); } else { return this.realFs.statSync(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(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject)); } else { this.realFs.lstat(npath.fromPortablePath(p), this.makeCallback(resolve, reject)); } }); } lstatSync(p, opts) { if (opts) { return this.realFs.lstatSync(npath.fromPortablePath(p), opts); } else { return this.realFs.lstatSync(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(npath.fromPortablePath(p), mask, this.makeCallback(resolve, reject)); }); } chmodSync(p, mask) { return this.realFs.chmodSync(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(npath.fromPortablePath(p), uid, gid, this.makeCallback(resolve, reject)); }); } chownSync(p, uid, gid) { return this.realFs.chownSync(npath.fromPortablePath(p), uid, gid); } async renamePromise(oldP, newP) { return await new Promise((resolve, reject) => { this.realFs.rename(npath.fromPortablePath(oldP), npath.fromPortablePath(newP), this.makeCallback(resolve, reject)); }); } renameSync(oldP, newP) { return this.realFs.renameSync(npath.fromPortablePath(oldP), npath.fromPortablePath(newP)); } async copyFilePromise(sourceP, destP, flags = 0) { return await new Promise((resolve, reject) => { this.realFs.copyFile(npath.fromPortablePath(sourceP), npath.fromPortablePath(destP), flags, this.makeCallback(resolve, reject)); }); } copyFileSync(sourceP, destP, flags = 0) { return this.realFs.copyFileSync(npath.fromPortablePath(sourceP), npath.fromPortablePath(destP), flags); } async appendFilePromise(p, content, opts) { return await new Promise((resolve, reject) => { const fsNativePath = typeof p === `string` ? 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` ? 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` ? 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` ? 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(npath.fromPortablePath(p), this.makeCallback(resolve, reject)); }); } unlinkSync(p) { return this.realFs.unlinkSync(npath.fromPortablePath(p)); } async utimesPromise(p, atime, mtime) { return await new Promise((resolve, reject) => { this.realFs.utimes(npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject)); }); } utimesSync(p, atime, mtime) { this.realFs.utimesSync(npath.fromPortablePath(p), atime, mtime); } async lutimesPromiseImpl(p, atime, mtime) { const lutimes = this.realFs.lutimes; if (typeof lutimes === `undefined`) throw ENOSYS(`unavailable Node binding`, `lutimes '${p}'`); return await new Promise((resolve, reject) => { lutimes.call(this.realFs, npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject)); }); } lutimesSyncImpl(p, atime, mtime) { const lutimesSync = this.realFs.lutimesSync; if (typeof lutimesSync === `undefined`) throw ENOSYS(`unavailable Node binding`, `lutimes '${p}'`); lutimesSync.call(this.realFs, npath.fromPortablePath(p), atime, mtime); } async mkdirPromise(p, opts) { return await new Promise((resolve, reject) => { this.realFs.mkdir(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject)); }); } mkdirSync(p, opts) { return this.realFs.mkdirSync(npath.fromPortablePath(p), opts); } async rmdirPromise(p, opts) { return await new Promise((resolve, reject) => { if (opts) { this.realFs.rmdir(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject)); } else { this.realFs.rmdir(npath.fromPortablePath(p), this.makeCallback(resolve, reject)); } }); } rmdirSync(p, opts) { return this.realFs.rmdirSync(npath.fromPortablePath(p), opts); } async linkPromise(existingP, newP) { return await new Promise((resolve, reject) => { this.realFs.link(npath.fromPortablePath(existingP), npath.fromPortablePath(newP), this.makeCallback(resolve, reject)); }); } linkSync(existingP, newP) { return this.realFs.linkSync(npath.fromPortablePath(existingP), npath.fromPortablePath(newP)); } async symlinkPromise(target, p, type) { return await new Promise((resolve, reject) => { this.realFs.symlink(npath.fromPortablePath(target.replace(/\/+$/, ``)), npath.fromPortablePath(p), type, this.makeCallback(resolve, reject)); }); } symlinkSync(target, p, type) { return this.realFs.symlinkSync(npath.fromPortablePath(target.replace(/\/+$/, ``)), npath.fromPortablePath(p), type); } async readFilePromise(p, encoding) { return await new Promise((resolve, reject) => { const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p; this.realFs.readFile(fsNativePath, encoding, this.makeCallback(resolve, reject)); }); } readFileSync(p, encoding) { const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p; return this.realFs.readFileSync(fsNativePath, encoding); } async readdirPromise(p, opts) { return await new Promise((resolve, reject) => { if (opts == null ? void 0 : opts.withFileTypes) { this.realFs.readdir(npath.fromPortablePath(p), { withFileTypes: true }, this.makeCallback(resolve, reject)); } else { this.realFs.readdir(npath.fromPortablePath(p), this.makeCallback((value) => resolve(value), reject)); } }); } readdirSync(p, opts) { if (opts == null ? void 0 : opts.withFileTypes) { return this.realFs.readdirSync(npath.fromPortablePath(p), { withFileTypes: true }); } else { return this.realFs.readdirSync(npath.fromPortablePath(p)); } } async readlinkPromise(p) { return await new Promise((resolve, reject) => { this.realFs.readlink(npath.fromPortablePath(p), this.makeCallback(resolve, reject)); }).then((path) => { return npath.toPortablePath(path); }); } readlinkSync(p) { return npath.toPortablePath(this.realFs.readlinkSync(npath.fromPortablePath(p))); } async truncatePromise(p, len) { return await new Promise((resolve, reject) => { this.realFs.truncate(npath.fromPortablePath(p), len, this.makeCallback(resolve, reject)); }); } truncateSync(p, len) { return this.realFs.truncateSync(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( npath.fromPortablePath(p), a, b ); } watchFile(p, a, b) { return this.realFs.watchFile( npath.fromPortablePath(p), a, b ); } unwatchFile(p, cb) { return this.realFs.unwatchFile(npath.fromPortablePath(p), cb); } makeCallback(resolve, reject) { return (err, result) => { if (err) { reject(err); } else { resolve(result); } }; } } function assertStatus(current, expected) { if (current !== expected) { throw new Error(`Invalid StatWatcher status: expected '${expected}', got '${current}'`); } } class CustomStatWatcher extends events.EventEmitter { constructor(fakeFs, path, { bigint = false } = {}) { super(); this.status = "ready" /* Ready */; this.changeListeners = /* @__PURE__ */ new Map(); this.startTimeout = null; this.fakeFs = fakeFs; this.path = path; this.bigint = bigint; this.lastStats = this.stat(); } static create(fakeFs, path, opts) { const statWatcher = new CustomStatWatcher(fakeFs, path, opts); statWatcher.start(); return statWatcher; } start() { assertStatus(this.status, "ready" /* Ready */); this.status = "running" /* Running */; this.startTimeout = setTimeout(() => { this.startTimeout = null; if (!this.fakeFs.existsSync(this.path)) { this.emit("change" /* Change */, this.lastStats, this.lastStats); } }, 3); } stop() { assertStatus(this.status, "running" /* Running */); this.status = "stopped" /* Stopped */; if (this.startTimeout !== null) { clearTimeout(this.startTimeout); this.startTimeout = null; } this.emit("stop" /* Stop */); } stat() { try { return this.fakeFs.statSync(this.path, { bigint: this.bigint }); } catch (error) { const statInstance = this.bigint ? new BigIntStatsEntry() : new StatEntry(); return clearStats(statInstance); } } makeInterval(opts) { const interval = setInterval(() => { const currentStats = this.stat(); const previousStats = this.lastStats; if (areStatsEqual(currentStats, previousStats)) return; this.lastStats = currentStats; this.emit("change" /* Change */, currentStats, previousStats); }, opts.interval); return opts.persistent ? interval : interval.unref(); } registerChangeListener(listener, opts) { this.addListener("change" /* Change */, listener); this.changeListeners.set(listener, this.makeInterval(opts)); } unregisterChangeListener(listener) { this.removeListener("change" /* Change */, listener); const interval = this.changeListeners.get(listener); if (typeof interval !== `undefined`) clearInterval(interval); this.changeListeners.delete(listener); } unregisterAllChangeListeners() { for (const listener of this.changeListeners.keys()) { this.unregisterChangeListener(listener); } } hasChangeListeners() { return this.changeListeners.size > 0; } ref() { for (const interval of this.changeListeners.values()) interval.ref(); return this; } unref() { for (const interval of this.changeListeners.values()) interval.unref(); return this; } } const statWatchersByFakeFS = /* @__PURE__ */ new WeakMap(); function watchFile(fakeFs, path, a, b) { let bigint; let persistent; let interval; let listener; switch (typeof a) { case `function`: { bigint = false; persistent = true; interval = 5007; listener = a; } break; default: { ({ bigint = false, persistent = true, interval = 5007 } = a); listener = b; } break; } let statWatchers = statWatchersByFakeFS.get(fakeFs); if (typeof statWatchers === `undefined`) statWatchersByFakeFS.set(fakeFs, statWatchers = /* @__PURE__ */ new Map()); let statWatcher = statWatchers.get(path); if (typeof statWatcher === `undefined`) { statWatcher = CustomStatWatcher.create(fakeFs, pa