Woodland_Furniture
/
.pnp.loader.mjs
2090 строк · 69.2 Кб
1import fs from 'fs';2import { URL as URL$1, fileURLToPath, pathToFileURL } from 'url';3import path from 'path';4import { createHash } from 'crypto';5import { EOL } from 'os';6import moduleExports, { isBuiltin } from 'module';7import assert from 'assert';8
9const SAFE_TIME = 456789e3;10
11const PortablePath = {12root: `/`,13dot: `.`,14parent: `..`15};16const npath = Object.create(path);17const ppath = Object.create(path.posix);18npath.cwd = () => process.cwd();19ppath.cwd = process.platform === `win32` ? () => toPortablePath(process.cwd()) : process.cwd;20if (process.platform === `win32`) {21ppath.resolve = (...segments) => {22if (segments.length > 0 && ppath.isAbsolute(segments[0])) {23return path.posix.resolve(...segments);24} else {25return path.posix.resolve(ppath.cwd(), ...segments);26}27};28}
29const contains = function(pathUtils, from, to) {30from = pathUtils.normalize(from);31to = pathUtils.normalize(to);32if (from === to)33return `.`;34if (!from.endsWith(pathUtils.sep))35from = from + pathUtils.sep;36if (to.startsWith(from)) {37return to.slice(from.length);38} else {39return null;40}41};42npath.contains = (from, to) => contains(npath, from, to);43ppath.contains = (from, to) => contains(ppath, from, to);44const WINDOWS_PATH_REGEXP = /^([a-zA-Z]:.*)$/;45const UNC_WINDOWS_PATH_REGEXP = /^\/\/(\.\/)?(.*)$/;46const PORTABLE_PATH_REGEXP = /^\/([a-zA-Z]:.*)$/;47const UNC_PORTABLE_PATH_REGEXP = /^\/unc\/(\.dot\/)?(.*)$/;48function fromPortablePathWin32(p) {49let portablePathMatch, uncPortablePathMatch;50if (portablePathMatch = p.match(PORTABLE_PATH_REGEXP))51p = portablePathMatch[1];52else if (uncPortablePathMatch = p.match(UNC_PORTABLE_PATH_REGEXP))53p = `\\\\${uncPortablePathMatch[1] ? `.\\` : ``}${uncPortablePathMatch[2]}`;54else55return p;56return p.replace(/\//g, `\\`);57}
58function toPortablePathWin32(p) {59p = p.replace(/\\/g, `/`);60let windowsPathMatch, uncWindowsPathMatch;61if (windowsPathMatch = p.match(WINDOWS_PATH_REGEXP))62p = `/${windowsPathMatch[1]}`;63else if (uncWindowsPathMatch = p.match(UNC_WINDOWS_PATH_REGEXP))64p = `/unc/${uncWindowsPathMatch[1] ? `.dot/` : ``}${uncWindowsPathMatch[2]}`;65return p;66}
67const toPortablePath = process.platform === `win32` ? toPortablePathWin32 : (p) => p;68const fromPortablePath = process.platform === `win32` ? fromPortablePathWin32 : (p) => p;69npath.fromPortablePath = fromPortablePath;70npath.toPortablePath = toPortablePath;71function convertPath(targetPathUtils, sourcePath) {72return targetPathUtils === npath ? fromPortablePath(sourcePath) : toPortablePath(sourcePath);73}
74
75const defaultTime = new Date(SAFE_TIME * 1e3);76const defaultTimeMs = defaultTime.getTime();77async function copyPromise(destinationFs, destination, sourceFs, source, opts) {78const normalizedDestination = destinationFs.pathUtils.normalize(destination);79const normalizedSource = sourceFs.pathUtils.normalize(source);80const prelayout = [];81const postlayout = [];82const { atime, mtime } = opts.stableTime ? { atime: defaultTime, mtime: defaultTime } : await sourceFs.lstatPromise(normalizedSource);83await destinationFs.mkdirpPromise(destinationFs.pathUtils.dirname(destination), { utimes: [atime, mtime] });84await copyImpl(prelayout, postlayout, destinationFs, normalizedDestination, sourceFs, normalizedSource, { ...opts, didParentExist: true });85for (const operation of prelayout)86await operation();87await Promise.all(postlayout.map((operation) => {88return operation();89}));90}
91async function copyImpl(prelayout, postlayout, destinationFs, destination, sourceFs, source, opts) {92const destinationStat = opts.didParentExist ? await maybeLStat(destinationFs, destination) : null;93const sourceStat = await sourceFs.lstatPromise(source);94const { atime, mtime } = opts.stableTime ? { atime: defaultTime, mtime: defaultTime } : sourceStat;95let updated;96switch (true) {97case sourceStat.isDirectory():98{99updated = await copyFolder(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);100}101break;102case sourceStat.isFile():103{104updated = await copyFile(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);105}106break;107case sourceStat.isSymbolicLink():108{109updated = await copySymlink(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);110}111break;112default:113{114throw new Error(`Unsupported file type (${sourceStat.mode})`);115}116}117if (opts.linkStrategy?.type !== `HardlinkFromIndex` || !sourceStat.isFile()) {118if (updated || destinationStat?.mtime?.getTime() !== mtime.getTime() || destinationStat?.atime?.getTime() !== atime.getTime()) {119postlayout.push(() => destinationFs.lutimesPromise(destination, atime, mtime));120updated = true;121}122if (destinationStat === null || (destinationStat.mode & 511) !== (sourceStat.mode & 511)) {123postlayout.push(() => destinationFs.chmodPromise(destination, sourceStat.mode & 511));124updated = true;125}126}127return updated;128}
129async function maybeLStat(baseFs, p) {130try {131return await baseFs.lstatPromise(p);132} catch (e) {133return null;134}135}
136async function copyFolder(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {137if (destinationStat !== null && !destinationStat.isDirectory()) {138if (opts.overwrite) {139prelayout.push(async () => destinationFs.removePromise(destination));140destinationStat = null;141} else {142return false;143}144}145let updated = false;146if (destinationStat === null) {147prelayout.push(async () => {148try {149await destinationFs.mkdirPromise(destination, { mode: sourceStat.mode });150} catch (err) {151if (err.code !== `EEXIST`) {152throw err;153}154}155});156updated = true;157}158const entries = await sourceFs.readdirPromise(source);159const nextOpts = opts.didParentExist && !destinationStat ? { ...opts, didParentExist: false } : opts;160if (opts.stableSort) {161for (const entry of entries.sort()) {162if (await copyImpl(prelayout, postlayout, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), nextOpts)) {163updated = true;164}165}166} else {167const entriesUpdateStatus = await Promise.all(entries.map(async (entry) => {168await copyImpl(prelayout, postlayout, destinationFs, destinationFs.pathUtils.join(destination, entry), sourceFs, sourceFs.pathUtils.join(source, entry), nextOpts);169}));170if (entriesUpdateStatus.some((status) => status)) {171updated = true;172}173}174return updated;175}
176async function copyFileViaIndex(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts, linkStrategy) {177const sourceHash = await sourceFs.checksumFilePromise(source, { algorithm: `sha1` });178const indexPath = destinationFs.pathUtils.join(linkStrategy.indexPath, sourceHash.slice(0, 2), `${sourceHash}.dat`);179let AtomicBehavior;180((AtomicBehavior2) => {181AtomicBehavior2[AtomicBehavior2["Lock"] = 0] = "Lock";182AtomicBehavior2[AtomicBehavior2["Rename"] = 1] = "Rename";183})(AtomicBehavior || (AtomicBehavior = {}));184let atomicBehavior = 1 /* Rename */;185let indexStat = await maybeLStat(destinationFs, indexPath);186if (destinationStat) {187const isDestinationHardlinkedFromIndex = indexStat && destinationStat.dev === indexStat.dev && destinationStat.ino === indexStat.ino;188const isIndexModified = indexStat?.mtimeMs !== defaultTimeMs;189if (isDestinationHardlinkedFromIndex) {190if (isIndexModified && linkStrategy.autoRepair) {191atomicBehavior = 0 /* Lock */;192indexStat = null;193}194}195if (!isDestinationHardlinkedFromIndex) {196if (opts.overwrite) {197prelayout.push(async () => destinationFs.removePromise(destination));198destinationStat = null;199} else {200return false;201}202}203}204const tempPath = !indexStat && atomicBehavior === 1 /* Rename */ ? `${indexPath}.${Math.floor(Math.random() * 4294967296).toString(16).padStart(8, `0`)}` : null;205let tempPathCleaned = false;206prelayout.push(async () => {207if (!indexStat) {208if (atomicBehavior === 0 /* Lock */) {209await destinationFs.lockPromise(indexPath, async () => {210const content = await sourceFs.readFilePromise(source);211await destinationFs.writeFilePromise(indexPath, content);212});213}214if (atomicBehavior === 1 /* Rename */ && tempPath) {215const content = await sourceFs.readFilePromise(source);216await destinationFs.writeFilePromise(tempPath, content);217try {218await destinationFs.linkPromise(tempPath, indexPath);219} catch (err) {220if (err.code === `EEXIST`) {221tempPathCleaned = true;222await destinationFs.unlinkPromise(tempPath);223} else {224throw err;225}226}227}228}229if (!destinationStat) {230await destinationFs.linkPromise(indexPath, destination);231}232});233postlayout.push(async () => {234if (!indexStat)235await destinationFs.lutimesPromise(indexPath, defaultTime, defaultTime);236if (tempPath && !tempPathCleaned) {237await destinationFs.unlinkPromise(tempPath);238}239});240return false;241}
242async function copyFileDirect(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {243if (destinationStat !== null) {244if (opts.overwrite) {245prelayout.push(async () => destinationFs.removePromise(destination));246destinationStat = null;247} else {248return false;249}250}251prelayout.push(async () => {252const content = await sourceFs.readFilePromise(source);253await destinationFs.writeFilePromise(destination, content);254});255return true;256}
257async function copyFile(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {258if (opts.linkStrategy?.type === `HardlinkFromIndex`) {259return copyFileViaIndex(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts, opts.linkStrategy);260} else {261return copyFileDirect(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts);262}263}
264async function copySymlink(prelayout, postlayout, destinationFs, destination, destinationStat, sourceFs, source, sourceStat, opts) {265if (destinationStat !== null) {266if (opts.overwrite) {267prelayout.push(async () => destinationFs.removePromise(destination));268destinationStat = null;269} else {270return false;271}272}273prelayout.push(async () => {274await destinationFs.symlinkPromise(convertPath(destinationFs.pathUtils, await sourceFs.readlinkPromise(source)), destination);275});276return true;277}
278
279class FakeFS {280constructor(pathUtils) {281this.pathUtils = pathUtils;282}283async *genTraversePromise(init, { stableSort = false } = {}) {284const stack = [init];285while (stack.length > 0) {286const p = stack.shift();287const entry = await this.lstatPromise(p);288if (entry.isDirectory()) {289const entries = await this.readdirPromise(p);290if (stableSort) {291for (const entry2 of entries.sort()) {292stack.push(this.pathUtils.join(p, entry2));293}294} else {295throw new Error(`Not supported`);296}297} else {298yield p;299}300}301}302async checksumFilePromise(path, { algorithm = `sha512` } = {}) {303const fd = await this.openPromise(path, `r`);304try {305const CHUNK_SIZE = 65536;306const chunk = Buffer.allocUnsafeSlow(CHUNK_SIZE);307const hash = createHash(algorithm);308let bytesRead = 0;309while ((bytesRead = await this.readPromise(fd, chunk, 0, CHUNK_SIZE)) !== 0)310hash.update(bytesRead === CHUNK_SIZE ? chunk : chunk.slice(0, bytesRead));311return hash.digest(`hex`);312} finally {313await this.closePromise(fd);314}315}316async removePromise(p, { recursive = true, maxRetries = 5 } = {}) {317let stat;318try {319stat = await this.lstatPromise(p);320} catch (error) {321if (error.code === `ENOENT`) {322return;323} else {324throw error;325}326}327if (stat.isDirectory()) {328if (recursive) {329const entries = await this.readdirPromise(p);330await Promise.all(entries.map((entry) => {331return this.removePromise(this.pathUtils.resolve(p, entry));332}));333}334for (let t = 0; t <= maxRetries; t++) {335try {336await this.rmdirPromise(p);337break;338} catch (error) {339if (error.code !== `EBUSY` && error.code !== `ENOTEMPTY`) {340throw error;341} else if (t < maxRetries) {342await new Promise((resolve) => setTimeout(resolve, t * 100));343}344}345}346} else {347await this.unlinkPromise(p);348}349}350removeSync(p, { recursive = true } = {}) {351let stat;352try {353stat = this.lstatSync(p);354} catch (error) {355if (error.code === `ENOENT`) {356return;357} else {358throw error;359}360}361if (stat.isDirectory()) {362if (recursive)363for (const entry of this.readdirSync(p))364this.removeSync(this.pathUtils.resolve(p, entry));365this.rmdirSync(p);366} else {367this.unlinkSync(p);368}369}370async mkdirpPromise(p, { chmod, utimes } = {}) {371p = this.resolve(p);372if (p === this.pathUtils.dirname(p))373return void 0;374const parts = p.split(this.pathUtils.sep);375let createdDirectory;376for (let u = 2; u <= parts.length; ++u) {377const subPath = parts.slice(0, u).join(this.pathUtils.sep);378if (!this.existsSync(subPath)) {379try {380await this.mkdirPromise(subPath);381} catch (error) {382if (error.code === `EEXIST`) {383continue;384} else {385throw error;386}387}388createdDirectory ??= subPath;389if (chmod != null)390await this.chmodPromise(subPath, chmod);391if (utimes != null) {392await this.utimesPromise(subPath, utimes[0], utimes[1]);393} else {394const parentStat = await this.statPromise(this.pathUtils.dirname(subPath));395await this.utimesPromise(subPath, parentStat.atime, parentStat.mtime);396}397}398}399return createdDirectory;400}401mkdirpSync(p, { chmod, utimes } = {}) {402p = this.resolve(p);403if (p === this.pathUtils.dirname(p))404return void 0;405const parts = p.split(this.pathUtils.sep);406let createdDirectory;407for (let u = 2; u <= parts.length; ++u) {408const subPath = parts.slice(0, u).join(this.pathUtils.sep);409if (!this.existsSync(subPath)) {410try {411this.mkdirSync(subPath);412} catch (error) {413if (error.code === `EEXIST`) {414continue;415} else {416throw error;417}418}419createdDirectory ??= subPath;420if (chmod != null)421this.chmodSync(subPath, chmod);422if (utimes != null) {423this.utimesSync(subPath, utimes[0], utimes[1]);424} else {425const parentStat = this.statSync(this.pathUtils.dirname(subPath));426this.utimesSync(subPath, parentStat.atime, parentStat.mtime);427}428}429}430return createdDirectory;431}432async copyPromise(destination, source, { baseFs = this, overwrite = true, stableSort = false, stableTime = false, linkStrategy = null } = {}) {433return await copyPromise(this, destination, baseFs, source, { overwrite, stableSort, stableTime, linkStrategy });434}435copySync(destination, source, { baseFs = this, overwrite = true } = {}) {436const stat = baseFs.lstatSync(source);437const exists = this.existsSync(destination);438if (stat.isDirectory()) {439this.mkdirpSync(destination);440const directoryListing = baseFs.readdirSync(source);441for (const entry of directoryListing) {442this.copySync(this.pathUtils.join(destination, entry), baseFs.pathUtils.join(source, entry), { baseFs, overwrite });443}444} else if (stat.isFile()) {445if (!exists || overwrite) {446if (exists)447this.removeSync(destination);448const content = baseFs.readFileSync(source);449this.writeFileSync(destination, content);450}451} else if (stat.isSymbolicLink()) {452if (!exists || overwrite) {453if (exists)454this.removeSync(destination);455const target = baseFs.readlinkSync(source);456this.symlinkSync(convertPath(this.pathUtils, target), destination);457}458} else {459throw new Error(`Unsupported file type (file: ${source}, mode: 0o${stat.mode.toString(8).padStart(6, `0`)})`);460}461const mode = stat.mode & 511;462this.chmodSync(destination, mode);463}464async changeFilePromise(p, content, opts = {}) {465if (Buffer.isBuffer(content)) {466return this.changeFileBufferPromise(p, content, opts);467} else {468return this.changeFileTextPromise(p, content, opts);469}470}471async changeFileBufferPromise(p, content, { mode } = {}) {472let current = Buffer.alloc(0);473try {474current = await this.readFilePromise(p);475} catch (error) {476}477if (Buffer.compare(current, content) === 0)478return;479await this.writeFilePromise(p, content, { mode });480}481async changeFileTextPromise(p, content, { automaticNewlines, mode } = {}) {482let current = ``;483try {484current = await this.readFilePromise(p, `utf8`);485} catch (error) {486}487const normalizedContent = automaticNewlines ? normalizeLineEndings(current, content) : content;488if (current === normalizedContent)489return;490await this.writeFilePromise(p, normalizedContent, { mode });491}492changeFileSync(p, content, opts = {}) {493if (Buffer.isBuffer(content)) {494return this.changeFileBufferSync(p, content, opts);495} else {496return this.changeFileTextSync(p, content, opts);497}498}499changeFileBufferSync(p, content, { mode } = {}) {500let current = Buffer.alloc(0);501try {502current = this.readFileSync(p);503} catch (error) {504}505if (Buffer.compare(current, content) === 0)506return;507this.writeFileSync(p, content, { mode });508}509changeFileTextSync(p, content, { automaticNewlines = false, mode } = {}) {510let current = ``;511try {512current = this.readFileSync(p, `utf8`);513} catch (error) {514}515const normalizedContent = automaticNewlines ? normalizeLineEndings(current, content) : content;516if (current === normalizedContent)517return;518this.writeFileSync(p, normalizedContent, { mode });519}520async movePromise(fromP, toP) {521try {522await this.renamePromise(fromP, toP);523} catch (error) {524if (error.code === `EXDEV`) {525await this.copyPromise(toP, fromP);526await this.removePromise(fromP);527} else {528throw error;529}530}531}532moveSync(fromP, toP) {533try {534this.renameSync(fromP, toP);535} catch (error) {536if (error.code === `EXDEV`) {537this.copySync(toP, fromP);538this.removeSync(fromP);539} else {540throw error;541}542}543}544async lockPromise(affectedPath, callback) {545const lockPath = `${affectedPath}.flock`;546const interval = 1e3 / 60;547const startTime = Date.now();548let fd = null;549const isAlive = async () => {550let pid;551try {552[pid] = await this.readJsonPromise(lockPath);553} catch (error) {554return Date.now() - startTime < 500;555}556try {557process.kill(pid, 0);558return true;559} catch (error) {560return false;561}562};563while (fd === null) {564try {565fd = await this.openPromise(lockPath, `wx`);566} catch (error) {567if (error.code === `EEXIST`) {568if (!await isAlive()) {569try {570await this.unlinkPromise(lockPath);571continue;572} catch (error2) {573}574}575if (Date.now() - startTime < 60 * 1e3) {576await new Promise((resolve) => setTimeout(resolve, interval));577} else {578throw new Error(`Couldn't acquire a lock in a reasonable time (via ${lockPath})`);579}580} else {581throw error;582}583}584}585await this.writePromise(fd, JSON.stringify([process.pid]));586try {587return await callback();588} finally {589try {590await this.closePromise(fd);591await this.unlinkPromise(lockPath);592} catch (error) {593}594}595}596async readJsonPromise(p) {597const content = await this.readFilePromise(p, `utf8`);598try {599return JSON.parse(content);600} catch (error) {601error.message += ` (in ${p})`;602throw error;603}604}605readJsonSync(p) {606const content = this.readFileSync(p, `utf8`);607try {608return JSON.parse(content);609} catch (error) {610error.message += ` (in ${p})`;611throw error;612}613}614async writeJsonPromise(p, data, { compact = false } = {}) {615const space = compact ? 0 : 2;616return await this.writeFilePromise(p, `${JSON.stringify(data, null, space)}617`);618}619writeJsonSync(p, data, { compact = false } = {}) {620const space = compact ? 0 : 2;621return this.writeFileSync(p, `${JSON.stringify(data, null, space)}622`);623}624async preserveTimePromise(p, cb) {625const stat = await this.lstatPromise(p);626const result = await cb();627if (typeof result !== `undefined`)628p = result;629await this.lutimesPromise(p, stat.atime, stat.mtime);630}631async preserveTimeSync(p, cb) {632const stat = this.lstatSync(p);633const result = cb();634if (typeof result !== `undefined`)635p = result;636this.lutimesSync(p, stat.atime, stat.mtime);637}638}
639class BasePortableFakeFS extends FakeFS {640constructor() {641super(ppath);642}643}
644function getEndOfLine(content) {645const matches = content.match(/\r?\n/g);646if (matches === null)647return EOL;648const crlf = matches.filter((nl) => nl === `\r649`).length;650const lf = matches.length - crlf;651return crlf > lf ? `\r652` : `653`;654}
655function normalizeLineEndings(originalContent, newContent) {656return newContent.replace(/\r?\n/g, getEndOfLine(originalContent));657}
658
659class ProxiedFS extends FakeFS {660getExtractHint(hints) {661return this.baseFs.getExtractHint(hints);662}663resolve(path) {664return this.mapFromBase(this.baseFs.resolve(this.mapToBase(path)));665}666getRealPath() {667return this.mapFromBase(this.baseFs.getRealPath());668}669async openPromise(p, flags, mode) {670return this.baseFs.openPromise(this.mapToBase(p), flags, mode);671}672openSync(p, flags, mode) {673return this.baseFs.openSync(this.mapToBase(p), flags, mode);674}675async opendirPromise(p, opts) {676return Object.assign(await this.baseFs.opendirPromise(this.mapToBase(p), opts), { path: p });677}678opendirSync(p, opts) {679return Object.assign(this.baseFs.opendirSync(this.mapToBase(p), opts), { path: p });680}681async readPromise(fd, buffer, offset, length, position) {682return await this.baseFs.readPromise(fd, buffer, offset, length, position);683}684readSync(fd, buffer, offset, length, position) {685return this.baseFs.readSync(fd, buffer, offset, length, position);686}687async writePromise(fd, buffer, offset, length, position) {688if (typeof buffer === `string`) {689return await this.baseFs.writePromise(fd, buffer, offset);690} else {691return await this.baseFs.writePromise(fd, buffer, offset, length, position);692}693}694writeSync(fd, buffer, offset, length, position) {695if (typeof buffer === `string`) {696return this.baseFs.writeSync(fd, buffer, offset);697} else {698return this.baseFs.writeSync(fd, buffer, offset, length, position);699}700}701async closePromise(fd) {702return this.baseFs.closePromise(fd);703}704closeSync(fd) {705this.baseFs.closeSync(fd);706}707createReadStream(p, opts) {708return this.baseFs.createReadStream(p !== null ? this.mapToBase(p) : p, opts);709}710createWriteStream(p, opts) {711return this.baseFs.createWriteStream(p !== null ? this.mapToBase(p) : p, opts);712}713async realpathPromise(p) {714return this.mapFromBase(await this.baseFs.realpathPromise(this.mapToBase(p)));715}716realpathSync(p) {717return this.mapFromBase(this.baseFs.realpathSync(this.mapToBase(p)));718}719async existsPromise(p) {720return this.baseFs.existsPromise(this.mapToBase(p));721}722existsSync(p) {723return this.baseFs.existsSync(this.mapToBase(p));724}725accessSync(p, mode) {726return this.baseFs.accessSync(this.mapToBase(p), mode);727}728async accessPromise(p, mode) {729return this.baseFs.accessPromise(this.mapToBase(p), mode);730}731async statPromise(p, opts) {732return this.baseFs.statPromise(this.mapToBase(p), opts);733}734statSync(p, opts) {735return this.baseFs.statSync(this.mapToBase(p), opts);736}737async fstatPromise(fd, opts) {738return this.baseFs.fstatPromise(fd, opts);739}740fstatSync(fd, opts) {741return this.baseFs.fstatSync(fd, opts);742}743lstatPromise(p, opts) {744return this.baseFs.lstatPromise(this.mapToBase(p), opts);745}746lstatSync(p, opts) {747return this.baseFs.lstatSync(this.mapToBase(p), opts);748}749async fchmodPromise(fd, mask) {750return this.baseFs.fchmodPromise(fd, mask);751}752fchmodSync(fd, mask) {753return this.baseFs.fchmodSync(fd, mask);754}755async chmodPromise(p, mask) {756return this.baseFs.chmodPromise(this.mapToBase(p), mask);757}758chmodSync(p, mask) {759return this.baseFs.chmodSync(this.mapToBase(p), mask);760}761async fchownPromise(fd, uid, gid) {762return this.baseFs.fchownPromise(fd, uid, gid);763}764fchownSync(fd, uid, gid) {765return this.baseFs.fchownSync(fd, uid, gid);766}767async chownPromise(p, uid, gid) {768return this.baseFs.chownPromise(this.mapToBase(p), uid, gid);769}770chownSync(p, uid, gid) {771return this.baseFs.chownSync(this.mapToBase(p), uid, gid);772}773async renamePromise(oldP, newP) {774return this.baseFs.renamePromise(this.mapToBase(oldP), this.mapToBase(newP));775}776renameSync(oldP, newP) {777return this.baseFs.renameSync(this.mapToBase(oldP), this.mapToBase(newP));778}779async copyFilePromise(sourceP, destP, flags = 0) {780return this.baseFs.copyFilePromise(this.mapToBase(sourceP), this.mapToBase(destP), flags);781}782copyFileSync(sourceP, destP, flags = 0) {783return this.baseFs.copyFileSync(this.mapToBase(sourceP), this.mapToBase(destP), flags);784}785async appendFilePromise(p, content, opts) {786return this.baseFs.appendFilePromise(this.fsMapToBase(p), content, opts);787}788appendFileSync(p, content, opts) {789return this.baseFs.appendFileSync(this.fsMapToBase(p), content, opts);790}791async writeFilePromise(p, content, opts) {792return this.baseFs.writeFilePromise(this.fsMapToBase(p), content, opts);793}794writeFileSync(p, content, opts) {795return this.baseFs.writeFileSync(this.fsMapToBase(p), content, opts);796}797async unlinkPromise(p) {798return this.baseFs.unlinkPromise(this.mapToBase(p));799}800unlinkSync(p) {801return this.baseFs.unlinkSync(this.mapToBase(p));802}803async utimesPromise(p, atime, mtime) {804return this.baseFs.utimesPromise(this.mapToBase(p), atime, mtime);805}806utimesSync(p, atime, mtime) {807return this.baseFs.utimesSync(this.mapToBase(p), atime, mtime);808}809async lutimesPromise(p, atime, mtime) {810return this.baseFs.lutimesPromise(this.mapToBase(p), atime, mtime);811}812lutimesSync(p, atime, mtime) {813return this.baseFs.lutimesSync(this.mapToBase(p), atime, mtime);814}815async mkdirPromise(p, opts) {816return this.baseFs.mkdirPromise(this.mapToBase(p), opts);817}818mkdirSync(p, opts) {819return this.baseFs.mkdirSync(this.mapToBase(p), opts);820}821async rmdirPromise(p, opts) {822return this.baseFs.rmdirPromise(this.mapToBase(p), opts);823}824rmdirSync(p, opts) {825return this.baseFs.rmdirSync(this.mapToBase(p), opts);826}827async linkPromise(existingP, newP) {828return this.baseFs.linkPromise(this.mapToBase(existingP), this.mapToBase(newP));829}830linkSync(existingP, newP) {831return this.baseFs.linkSync(this.mapToBase(existingP), this.mapToBase(newP));832}833async symlinkPromise(target, p, type) {834const mappedP = this.mapToBase(p);835if (this.pathUtils.isAbsolute(target))836return this.baseFs.symlinkPromise(this.mapToBase(target), mappedP, type);837const mappedAbsoluteTarget = this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(p), target));838const mappedTarget = this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(mappedP), mappedAbsoluteTarget);839return this.baseFs.symlinkPromise(mappedTarget, mappedP, type);840}841symlinkSync(target, p, type) {842const mappedP = this.mapToBase(p);843if (this.pathUtils.isAbsolute(target))844return this.baseFs.symlinkSync(this.mapToBase(target), mappedP, type);845const mappedAbsoluteTarget = this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(p), target));846const mappedTarget = this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(mappedP), mappedAbsoluteTarget);847return this.baseFs.symlinkSync(mappedTarget, mappedP, type);848}849async readFilePromise(p, encoding) {850return this.baseFs.readFilePromise(this.fsMapToBase(p), encoding);851}852readFileSync(p, encoding) {853return this.baseFs.readFileSync(this.fsMapToBase(p), encoding);854}855readdirPromise(p, opts) {856return this.baseFs.readdirPromise(this.mapToBase(p), opts);857}858readdirSync(p, opts) {859return this.baseFs.readdirSync(this.mapToBase(p), opts);860}861async readlinkPromise(p) {862return this.mapFromBase(await this.baseFs.readlinkPromise(this.mapToBase(p)));863}864readlinkSync(p) {865return this.mapFromBase(this.baseFs.readlinkSync(this.mapToBase(p)));866}867async truncatePromise(p, len) {868return this.baseFs.truncatePromise(this.mapToBase(p), len);869}870truncateSync(p, len) {871return this.baseFs.truncateSync(this.mapToBase(p), len);872}873async ftruncatePromise(fd, len) {874return this.baseFs.ftruncatePromise(fd, len);875}876ftruncateSync(fd, len) {877return this.baseFs.ftruncateSync(fd, len);878}879watch(p, a, b) {880return this.baseFs.watch(881this.mapToBase(p),882a,883b
884);885}886watchFile(p, a, b) {887return this.baseFs.watchFile(888this.mapToBase(p),889a,890b
891);892}893unwatchFile(p, cb) {894return this.baseFs.unwatchFile(this.mapToBase(p), cb);895}896fsMapToBase(p) {897if (typeof p === `number`) {898return p;899} else {900return this.mapToBase(p);901}902}903}
904
905function direntToPortable(dirent) {906const portableDirent = dirent;907if (typeof dirent.path === `string`)908portableDirent.path = npath.toPortablePath(dirent.path);909return portableDirent;910}
911class NodeFS extends BasePortableFakeFS {912constructor(realFs = fs) {913super();914this.realFs = realFs;915}916getExtractHint() {917return false;918}919getRealPath() {920return PortablePath.root;921}922resolve(p) {923return ppath.resolve(p);924}925async openPromise(p, flags, mode) {926return await new Promise((resolve, reject) => {927this.realFs.open(npath.fromPortablePath(p), flags, mode, this.makeCallback(resolve, reject));928});929}930openSync(p, flags, mode) {931return this.realFs.openSync(npath.fromPortablePath(p), flags, mode);932}933async opendirPromise(p, opts) {934return await new Promise((resolve, reject) => {935if (typeof opts !== `undefined`) {936this.realFs.opendir(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));937} else {938this.realFs.opendir(npath.fromPortablePath(p), this.makeCallback(resolve, reject));939}940}).then((dir) => {941const dirWithFixedPath = dir;942Object.defineProperty(dirWithFixedPath, `path`, {943value: p,944configurable: true,945writable: true946});947return dirWithFixedPath;948});949}950opendirSync(p, opts) {951const dir = typeof opts !== `undefined` ? this.realFs.opendirSync(npath.fromPortablePath(p), opts) : this.realFs.opendirSync(npath.fromPortablePath(p));952const dirWithFixedPath = dir;953Object.defineProperty(dirWithFixedPath, `path`, {954value: p,955configurable: true,956writable: true957});958return dirWithFixedPath;959}960async readPromise(fd, buffer, offset = 0, length = 0, position = -1) {961return await new Promise((resolve, reject) => {962this.realFs.read(fd, buffer, offset, length, position, (error, bytesRead) => {963if (error) {964reject(error);965} else {966resolve(bytesRead);967}968});969});970}971readSync(fd, buffer, offset, length, position) {972return this.realFs.readSync(fd, buffer, offset, length, position);973}974async writePromise(fd, buffer, offset, length, position) {975return await new Promise((resolve, reject) => {976if (typeof buffer === `string`) {977return this.realFs.write(fd, buffer, offset, this.makeCallback(resolve, reject));978} else {979return this.realFs.write(fd, buffer, offset, length, position, this.makeCallback(resolve, reject));980}981});982}983writeSync(fd, buffer, offset, length, position) {984if (typeof buffer === `string`) {985return this.realFs.writeSync(fd, buffer, offset);986} else {987return this.realFs.writeSync(fd, buffer, offset, length, position);988}989}990async closePromise(fd) {991await new Promise((resolve, reject) => {992this.realFs.close(fd, this.makeCallback(resolve, reject));993});994}995closeSync(fd) {996this.realFs.closeSync(fd);997}998createReadStream(p, opts) {999const realPath = p !== null ? npath.fromPortablePath(p) : p;1000return this.realFs.createReadStream(realPath, opts);1001}1002createWriteStream(p, opts) {1003const realPath = p !== null ? npath.fromPortablePath(p) : p;1004return this.realFs.createWriteStream(realPath, opts);1005}1006async realpathPromise(p) {1007return await new Promise((resolve, reject) => {1008this.realFs.realpath(npath.fromPortablePath(p), {}, this.makeCallback(resolve, reject));1009}).then((path) => {1010return npath.toPortablePath(path);1011});1012}1013realpathSync(p) {1014return npath.toPortablePath(this.realFs.realpathSync(npath.fromPortablePath(p), {}));1015}1016async existsPromise(p) {1017return await new Promise((resolve) => {1018this.realFs.exists(npath.fromPortablePath(p), resolve);1019});1020}1021accessSync(p, mode) {1022return this.realFs.accessSync(npath.fromPortablePath(p), mode);1023}1024async accessPromise(p, mode) {1025return await new Promise((resolve, reject) => {1026this.realFs.access(npath.fromPortablePath(p), mode, this.makeCallback(resolve, reject));1027});1028}1029existsSync(p) {1030return this.realFs.existsSync(npath.fromPortablePath(p));1031}1032async statPromise(p, opts) {1033return await new Promise((resolve, reject) => {1034if (opts) {1035this.realFs.stat(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));1036} else {1037this.realFs.stat(npath.fromPortablePath(p), this.makeCallback(resolve, reject));1038}1039});1040}1041statSync(p, opts) {1042if (opts) {1043return this.realFs.statSync(npath.fromPortablePath(p), opts);1044} else {1045return this.realFs.statSync(npath.fromPortablePath(p));1046}1047}1048async fstatPromise(fd, opts) {1049return await new Promise((resolve, reject) => {1050if (opts) {1051this.realFs.fstat(fd, opts, this.makeCallback(resolve, reject));1052} else {1053this.realFs.fstat(fd, this.makeCallback(resolve, reject));1054}1055});1056}1057fstatSync(fd, opts) {1058if (opts) {1059return this.realFs.fstatSync(fd, opts);1060} else {1061return this.realFs.fstatSync(fd);1062}1063}1064async lstatPromise(p, opts) {1065return await new Promise((resolve, reject) => {1066if (opts) {1067this.realFs.lstat(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));1068} else {1069this.realFs.lstat(npath.fromPortablePath(p), this.makeCallback(resolve, reject));1070}1071});1072}1073lstatSync(p, opts) {1074if (opts) {1075return this.realFs.lstatSync(npath.fromPortablePath(p), opts);1076} else {1077return this.realFs.lstatSync(npath.fromPortablePath(p));1078}1079}1080async fchmodPromise(fd, mask) {1081return await new Promise((resolve, reject) => {1082this.realFs.fchmod(fd, mask, this.makeCallback(resolve, reject));1083});1084}1085fchmodSync(fd, mask) {1086return this.realFs.fchmodSync(fd, mask);1087}1088async chmodPromise(p, mask) {1089return await new Promise((resolve, reject) => {1090this.realFs.chmod(npath.fromPortablePath(p), mask, this.makeCallback(resolve, reject));1091});1092}1093chmodSync(p, mask) {1094return this.realFs.chmodSync(npath.fromPortablePath(p), mask);1095}1096async fchownPromise(fd, uid, gid) {1097return await new Promise((resolve, reject) => {1098this.realFs.fchown(fd, uid, gid, this.makeCallback(resolve, reject));1099});1100}1101fchownSync(fd, uid, gid) {1102return this.realFs.fchownSync(fd, uid, gid);1103}1104async chownPromise(p, uid, gid) {1105return await new Promise((resolve, reject) => {1106this.realFs.chown(npath.fromPortablePath(p), uid, gid, this.makeCallback(resolve, reject));1107});1108}1109chownSync(p, uid, gid) {1110return this.realFs.chownSync(npath.fromPortablePath(p), uid, gid);1111}1112async renamePromise(oldP, newP) {1113return await new Promise((resolve, reject) => {1114this.realFs.rename(npath.fromPortablePath(oldP), npath.fromPortablePath(newP), this.makeCallback(resolve, reject));1115});1116}1117renameSync(oldP, newP) {1118return this.realFs.renameSync(npath.fromPortablePath(oldP), npath.fromPortablePath(newP));1119}1120async copyFilePromise(sourceP, destP, flags = 0) {1121return await new Promise((resolve, reject) => {1122this.realFs.copyFile(npath.fromPortablePath(sourceP), npath.fromPortablePath(destP), flags, this.makeCallback(resolve, reject));1123});1124}1125copyFileSync(sourceP, destP, flags = 0) {1126return this.realFs.copyFileSync(npath.fromPortablePath(sourceP), npath.fromPortablePath(destP), flags);1127}1128async appendFilePromise(p, content, opts) {1129return await new Promise((resolve, reject) => {1130const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;1131if (opts) {1132this.realFs.appendFile(fsNativePath, content, opts, this.makeCallback(resolve, reject));1133} else {1134this.realFs.appendFile(fsNativePath, content, this.makeCallback(resolve, reject));1135}1136});1137}1138appendFileSync(p, content, opts) {1139const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;1140if (opts) {1141this.realFs.appendFileSync(fsNativePath, content, opts);1142} else {1143this.realFs.appendFileSync(fsNativePath, content);1144}1145}1146async writeFilePromise(p, content, opts) {1147return await new Promise((resolve, reject) => {1148const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;1149if (opts) {1150this.realFs.writeFile(fsNativePath, content, opts, this.makeCallback(resolve, reject));1151} else {1152this.realFs.writeFile(fsNativePath, content, this.makeCallback(resolve, reject));1153}1154});1155}1156writeFileSync(p, content, opts) {1157const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;1158if (opts) {1159this.realFs.writeFileSync(fsNativePath, content, opts);1160} else {1161this.realFs.writeFileSync(fsNativePath, content);1162}1163}1164async unlinkPromise(p) {1165return await new Promise((resolve, reject) => {1166this.realFs.unlink(npath.fromPortablePath(p), this.makeCallback(resolve, reject));1167});1168}1169unlinkSync(p) {1170return this.realFs.unlinkSync(npath.fromPortablePath(p));1171}1172async utimesPromise(p, atime, mtime) {1173return await new Promise((resolve, reject) => {1174this.realFs.utimes(npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject));1175});1176}1177utimesSync(p, atime, mtime) {1178this.realFs.utimesSync(npath.fromPortablePath(p), atime, mtime);1179}1180async lutimesPromise(p, atime, mtime) {1181return await new Promise((resolve, reject) => {1182this.realFs.lutimes(npath.fromPortablePath(p), atime, mtime, this.makeCallback(resolve, reject));1183});1184}1185lutimesSync(p, atime, mtime) {1186this.realFs.lutimesSync(npath.fromPortablePath(p), atime, mtime);1187}1188async mkdirPromise(p, opts) {1189return await new Promise((resolve, reject) => {1190this.realFs.mkdir(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));1191});1192}1193mkdirSync(p, opts) {1194return this.realFs.mkdirSync(npath.fromPortablePath(p), opts);1195}1196async rmdirPromise(p, opts) {1197return await new Promise((resolve, reject) => {1198if (opts) {1199this.realFs.rmdir(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));1200} else {1201this.realFs.rmdir(npath.fromPortablePath(p), this.makeCallback(resolve, reject));1202}1203});1204}1205rmdirSync(p, opts) {1206return this.realFs.rmdirSync(npath.fromPortablePath(p), opts);1207}1208async linkPromise(existingP, newP) {1209return await new Promise((resolve, reject) => {1210this.realFs.link(npath.fromPortablePath(existingP), npath.fromPortablePath(newP), this.makeCallback(resolve, reject));1211});1212}1213linkSync(existingP, newP) {1214return this.realFs.linkSync(npath.fromPortablePath(existingP), npath.fromPortablePath(newP));1215}1216async symlinkPromise(target, p, type) {1217return await new Promise((resolve, reject) => {1218this.realFs.symlink(npath.fromPortablePath(target.replace(/\/+$/, ``)), npath.fromPortablePath(p), type, this.makeCallback(resolve, reject));1219});1220}1221symlinkSync(target, p, type) {1222return this.realFs.symlinkSync(npath.fromPortablePath(target.replace(/\/+$/, ``)), npath.fromPortablePath(p), type);1223}1224async readFilePromise(p, encoding) {1225return await new Promise((resolve, reject) => {1226const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;1227this.realFs.readFile(fsNativePath, encoding, this.makeCallback(resolve, reject));1228});1229}1230readFileSync(p, encoding) {1231const fsNativePath = typeof p === `string` ? npath.fromPortablePath(p) : p;1232return this.realFs.readFileSync(fsNativePath, encoding);1233}1234async readdirPromise(p, opts) {1235return await new Promise((resolve, reject) => {1236if (opts) {1237if (opts.recursive && process.platform === `win32`) {1238if (opts.withFileTypes) {1239this.realFs.readdir(npath.fromPortablePath(p), opts, this.makeCallback((results) => resolve(results.map(direntToPortable)), reject));1240} else {1241this.realFs.readdir(npath.fromPortablePath(p), opts, this.makeCallback((results) => resolve(results.map(npath.toPortablePath)), reject));1242}1243} else {1244this.realFs.readdir(npath.fromPortablePath(p), opts, this.makeCallback(resolve, reject));1245}1246} else {1247this.realFs.readdir(npath.fromPortablePath(p), this.makeCallback(resolve, reject));1248}1249});1250}1251readdirSync(p, opts) {1252if (opts) {1253if (opts.recursive && process.platform === `win32`) {1254if (opts.withFileTypes) {1255return this.realFs.readdirSync(npath.fromPortablePath(p), opts).map(direntToPortable);1256} else {1257return this.realFs.readdirSync(npath.fromPortablePath(p), opts).map(npath.toPortablePath);1258}1259} else {1260return this.realFs.readdirSync(npath.fromPortablePath(p), opts);1261}1262} else {1263return this.realFs.readdirSync(npath.fromPortablePath(p));1264}1265}1266async readlinkPromise(p) {1267return await new Promise((resolve, reject) => {1268this.realFs.readlink(npath.fromPortablePath(p), this.makeCallback(resolve, reject));1269}).then((path) => {1270return npath.toPortablePath(path);1271});1272}1273readlinkSync(p) {1274return npath.toPortablePath(this.realFs.readlinkSync(npath.fromPortablePath(p)));1275}1276async truncatePromise(p, len) {1277return await new Promise((resolve, reject) => {1278this.realFs.truncate(npath.fromPortablePath(p), len, this.makeCallback(resolve, reject));1279});1280}1281truncateSync(p, len) {1282return this.realFs.truncateSync(npath.fromPortablePath(p), len);1283}1284async ftruncatePromise(fd, len) {1285return await new Promise((resolve, reject) => {1286this.realFs.ftruncate(fd, len, this.makeCallback(resolve, reject));1287});1288}1289ftruncateSync(fd, len) {1290return this.realFs.ftruncateSync(fd, len);1291}1292watch(p, a, b) {1293return this.realFs.watch(1294npath.fromPortablePath(p),1295a,1296b
1297);1298}1299watchFile(p, a, b) {1300return this.realFs.watchFile(1301npath.fromPortablePath(p),1302a,1303b
1304);1305}1306unwatchFile(p, cb) {1307return this.realFs.unwatchFile(npath.fromPortablePath(p), cb);1308}1309makeCallback(resolve, reject) {1310return (err, result) => {1311if (err) {1312reject(err);1313} else {1314resolve(result);1315}1316};1317}1318}
1319
1320const NUMBER_REGEXP = /^[0-9]+$/;1321const VIRTUAL_REGEXP = /^(\/(?:[^/]+\/)*?(?:\$\$virtual|__virtual__))((?:\/((?:[^/]+-)?[a-f0-9]+)(?:\/([^/]+))?)?((?:\/.*)?))$/;1322const VALID_COMPONENT = /^([^/]+-)?[a-f0-9]+$/;1323class VirtualFS extends ProxiedFS {1324constructor({ baseFs = new NodeFS() } = {}) {1325super(ppath);1326this.baseFs = baseFs;1327}1328static makeVirtualPath(base, component, to) {1329if (ppath.basename(base) !== `__virtual__`)1330throw new Error(`Assertion failed: Virtual folders must be named "__virtual__"`);1331if (!ppath.basename(component).match(VALID_COMPONENT))1332throw new Error(`Assertion failed: Virtual components must be ended by an hexadecimal hash`);1333const target = ppath.relative(ppath.dirname(base), to);1334const segments = target.split(`/`);1335let depth = 0;1336while (depth < segments.length && segments[depth] === `..`)1337depth += 1;1338const finalSegments = segments.slice(depth);1339const fullVirtualPath = ppath.join(base, component, String(depth), ...finalSegments);1340return fullVirtualPath;1341}1342static resolveVirtual(p) {1343const match = p.match(VIRTUAL_REGEXP);1344if (!match || !match[3] && match[5])1345return p;1346const target = ppath.dirname(match[1]);1347if (!match[3] || !match[4])1348return target;1349const isnum = NUMBER_REGEXP.test(match[4]);1350if (!isnum)1351return p;1352const depth = Number(match[4]);1353const backstep = `../`.repeat(depth);1354const subpath = match[5] || `.`;1355return VirtualFS.resolveVirtual(ppath.join(target, backstep, subpath));1356}1357getExtractHint(hints) {1358return this.baseFs.getExtractHint(hints);1359}1360getRealPath() {1361return this.baseFs.getRealPath();1362}1363realpathSync(p) {1364const match = p.match(VIRTUAL_REGEXP);1365if (!match)1366return this.baseFs.realpathSync(p);1367if (!match[5])1368return p;1369const realpath = this.baseFs.realpathSync(this.mapToBase(p));1370return VirtualFS.makeVirtualPath(match[1], match[3], realpath);1371}1372async realpathPromise(p) {1373const match = p.match(VIRTUAL_REGEXP);1374if (!match)1375return await this.baseFs.realpathPromise(p);1376if (!match[5])1377return p;1378const realpath = await this.baseFs.realpathPromise(this.mapToBase(p));1379return VirtualFS.makeVirtualPath(match[1], match[3], realpath);1380}1381mapToBase(p) {1382if (p === ``)1383return p;1384if (this.pathUtils.isAbsolute(p))1385return VirtualFS.resolveVirtual(p);1386const resolvedRoot = VirtualFS.resolveVirtual(this.baseFs.resolve(PortablePath.dot));1387const resolvedP = VirtualFS.resolveVirtual(this.baseFs.resolve(p));1388return ppath.relative(resolvedRoot, resolvedP) || PortablePath.dot;1389}1390mapFromBase(p) {1391return p;1392}1393}
1394
1395const [major, minor] = process.versions.node.split(`.`).map((value) => parseInt(value, 10));1396const WATCH_MODE_MESSAGE_USES_ARRAYS = major > 19 || major === 19 && minor >= 2 || major === 18 && minor >= 13;1397const HAS_LAZY_LOADED_TRANSLATORS = major === 20 && minor < 6 || major === 19 && minor >= 3;1398
1399function readPackageScope(checkPath) {1400const rootSeparatorIndex = checkPath.indexOf(npath.sep);1401let separatorIndex;1402do {1403separatorIndex = checkPath.lastIndexOf(npath.sep);1404checkPath = checkPath.slice(0, separatorIndex);1405if (checkPath.endsWith(`${npath.sep}node_modules`))1406return false;1407const pjson = readPackage(checkPath + npath.sep);1408if (pjson) {1409return {1410data: pjson,1411path: checkPath1412};1413}1414} while (separatorIndex > rootSeparatorIndex);1415return false;1416}
1417function readPackage(requestPath) {1418const jsonPath = npath.resolve(requestPath, `package.json`);1419if (!fs.existsSync(jsonPath))1420return null;1421return JSON.parse(fs.readFileSync(jsonPath, `utf8`));1422}
1423
1424async function tryReadFile$1(path2) {1425try {1426return await fs.promises.readFile(path2, `utf8`);1427} catch (error) {1428if (error.code === `ENOENT`)1429return null;1430throw error;1431}1432}
1433function tryParseURL(str, base) {1434try {1435return new URL$1(str, base);1436} catch {1437return null;1438}1439}
1440let entrypointPath = null;1441function setEntrypointPath(file) {1442entrypointPath = file;1443}
1444function getFileFormat(filepath) {1445const ext = path.extname(filepath);1446switch (ext) {1447case `.mjs`: {1448return `module`;1449}1450case `.cjs`: {1451return `commonjs`;1452}1453case `.wasm`: {1454throw new Error(1455`Unknown file extension ".wasm" for ${filepath}`1456);1457}1458case `.json`: {1459return `json`;1460}1461case `.js`: {1462const pkg = readPackageScope(filepath);1463if (!pkg)1464return `commonjs`;1465return pkg.data.type ?? `commonjs`;1466}1467default: {1468if (entrypointPath !== filepath)1469return null;1470const pkg = readPackageScope(filepath);1471if (!pkg)1472return `commonjs`;1473if (pkg.data.type === `module`)1474return null;1475return pkg.data.type ?? `commonjs`;1476}1477}1478}
1479
1480async function load$1(urlString, context, nextLoad) {1481const url = tryParseURL(urlString);1482if (url?.protocol !== `file:`)1483return nextLoad(urlString, context, nextLoad);1484const filePath = fileURLToPath(url);1485const format = getFileFormat(filePath);1486if (!format)1487return nextLoad(urlString, context, nextLoad);1488if (format === `json` && context.importAssertions?.type !== `json`) {1489const err = new TypeError(`[ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "${urlString}" needs an import assertion of type "json"`);1490err.code = `ERR_IMPORT_ASSERTION_TYPE_MISSING`;1491throw err;1492}1493if (process.env.WATCH_REPORT_DEPENDENCIES && process.send) {1494const pathToSend = pathToFileURL(1495npath.fromPortablePath(1496VirtualFS.resolveVirtual(npath.toPortablePath(filePath))1497)1498).href;1499process.send({1500"watch:import": WATCH_MODE_MESSAGE_USES_ARRAYS ? [pathToSend] : pathToSend1501});1502}1503return {1504format,1505source: format === `commonjs` ? void 0 : await fs.promises.readFile(filePath, `utf8`),1506shortCircuit: true1507};1508}
1509
1510const ArrayIsArray = Array.isArray;1511const JSONStringify = JSON.stringify;1512const ObjectGetOwnPropertyNames = Object.getOwnPropertyNames;1513const ObjectPrototypeHasOwnProperty = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);1514const RegExpPrototypeExec = (obj, string) => RegExp.prototype.exec.call(obj, string);1515const RegExpPrototypeSymbolReplace = (obj, ...rest) => RegExp.prototype[Symbol.replace].apply(obj, rest);1516const StringPrototypeEndsWith = (str, ...rest) => String.prototype.endsWith.apply(str, rest);1517const StringPrototypeIncludes = (str, ...rest) => String.prototype.includes.apply(str, rest);1518const StringPrototypeLastIndexOf = (str, ...rest) => String.prototype.lastIndexOf.apply(str, rest);1519const StringPrototypeIndexOf = (str, ...rest) => String.prototype.indexOf.apply(str, rest);1520const StringPrototypeReplace = (str, ...rest) => String.prototype.replace.apply(str, rest);1521const StringPrototypeSlice = (str, ...rest) => String.prototype.slice.apply(str, rest);1522const StringPrototypeStartsWith = (str, ...rest) => String.prototype.startsWith.apply(str, rest);1523const SafeMap = Map;1524const JSONParse = JSON.parse;1525
1526function createErrorType(code, messageCreator, errorType) {1527return class extends errorType {1528constructor(...args) {1529super(messageCreator(...args));1530this.code = code;1531this.name = `${errorType.name} [${code}]`;1532}1533};1534}
1535const ERR_PACKAGE_IMPORT_NOT_DEFINED = createErrorType(1536`ERR_PACKAGE_IMPORT_NOT_DEFINED`,1537(specifier, packagePath, base) => {1538return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ``} imported from ${base}`;1539},1540TypeError
1541);1542const ERR_INVALID_MODULE_SPECIFIER = createErrorType(1543`ERR_INVALID_MODULE_SPECIFIER`,1544(request, reason, base = void 0) => {1545return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ``}`;1546},1547TypeError
1548);1549const ERR_INVALID_PACKAGE_TARGET = createErrorType(1550`ERR_INVALID_PACKAGE_TARGET`,1551(pkgPath, key, target, isImport = false, base = void 0) => {1552const relError = typeof target === `string` && !isImport && target.length && !StringPrototypeStartsWith(target, `./`);1553if (key === `.`) {1554assert(isImport === false);1555return `Invalid "exports" main target ${JSONStringify(target)} defined in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ``}${relError ? `; targets must start with "./"` : ``}`;1556}1557return `Invalid "${isImport ? `imports` : `exports`}" target ${JSONStringify(1558target
1559)} defined for '${key}' in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ``}${relError ? `; targets must start with "./"` : ``}`;1560},1561Error
1562);1563const ERR_INVALID_PACKAGE_CONFIG = createErrorType(1564`ERR_INVALID_PACKAGE_CONFIG`,1565(path, base, message) => {1566return `Invalid package config ${path}${base ? ` while importing ${base}` : ``}${message ? `. ${message}` : ``}`;1567},1568Error
1569);1570
1571function filterOwnProperties(source, keys) {1572const filtered = /* @__PURE__ */ Object.create(null);1573for (let i = 0; i < keys.length; i++) {1574const key = keys[i];1575if (ObjectPrototypeHasOwnProperty(source, key)) {1576filtered[key] = source[key];1577}1578}1579return filtered;1580}
1581
1582const packageJSONCache = new SafeMap();1583function getPackageConfig(path, specifier, base, readFileSyncFn) {1584const existing = packageJSONCache.get(path);1585if (existing !== void 0) {1586return existing;1587}1588const source = readFileSyncFn(path);1589if (source === void 0) {1590const packageConfig2 = {1591pjsonPath: path,1592exists: false,1593main: void 0,1594name: void 0,1595type: "none",1596exports: void 0,1597imports: void 01598};1599packageJSONCache.set(path, packageConfig2);1600return packageConfig2;1601}1602let packageJSON;1603try {1604packageJSON = JSONParse(source);1605} catch (error) {1606throw new ERR_INVALID_PACKAGE_CONFIG(1607path,1608(base ? `"${specifier}" from ` : "") + fileURLToPath(base || specifier),1609error.message1610);1611}1612let { imports, main, name, type } = filterOwnProperties(packageJSON, [1613"imports",1614"main",1615"name",1616"type"1617]);1618const exports = ObjectPrototypeHasOwnProperty(packageJSON, "exports") ? packageJSON.exports : void 0;1619if (typeof imports !== "object" || imports === null) {1620imports = void 0;1621}1622if (typeof main !== "string") {1623main = void 0;1624}1625if (typeof name !== "string") {1626name = void 0;1627}1628if (type !== "module" && type !== "commonjs") {1629type = "none";1630}1631const packageConfig = {1632pjsonPath: path,1633exists: true,1634main,1635name,1636type,1637exports,1638imports
1639};1640packageJSONCache.set(path, packageConfig);1641return packageConfig;1642}
1643function getPackageScopeConfig(resolved, readFileSyncFn) {1644let packageJSONUrl = new URL("./package.json", resolved);1645while (true) {1646const packageJSONPath2 = packageJSONUrl.pathname;1647if (StringPrototypeEndsWith(packageJSONPath2, "node_modules/package.json")) {1648break;1649}1650const packageConfig2 = getPackageConfig(1651fileURLToPath(packageJSONUrl),1652resolved,1653void 0,1654readFileSyncFn
1655);1656if (packageConfig2.exists) {1657return packageConfig2;1658}1659const lastPackageJSONUrl = packageJSONUrl;1660packageJSONUrl = new URL("../package.json", packageJSONUrl);1661if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {1662break;1663}1664}1665const packageJSONPath = fileURLToPath(packageJSONUrl);1666const packageConfig = {1667pjsonPath: packageJSONPath,1668exists: false,1669main: void 0,1670name: void 0,1671type: "none",1672exports: void 0,1673imports: void 01674};1675packageJSONCache.set(packageJSONPath, packageConfig);1676return packageConfig;1677}
1678
1679/**
1680@license
1681Copyright Node.js contributors. All rights reserved.
1682
1683Permission is hereby granted, free of charge, to any person obtaining a copy
1684of this software and associated documentation files (the "Software"), to
1685deal in the Software without restriction, including without limitation the
1686rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
1687sell copies of the Software, and to permit persons to whom the Software is
1688furnished to do so, subject to the following conditions:
1689
1690The above copyright notice and this permission notice shall be included in
1691all copies or substantial portions of the Software.
1692
1693THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1694IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1695FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1696AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1697LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
1698FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
1699IN THE SOFTWARE.
1700*/
1701function throwImportNotDefined(specifier, packageJSONUrl, base) {1702throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(1703specifier,1704packageJSONUrl && fileURLToPath(new URL(".", packageJSONUrl)),1705fileURLToPath(base)1706);1707}
1708function throwInvalidSubpath(subpath, packageJSONUrl, internal, base) {1709const reason = `request is not a valid subpath for the "${internal ? "imports" : "exports"}" resolution of ${fileURLToPath(packageJSONUrl)}`;1710throw new ERR_INVALID_MODULE_SPECIFIER(1711subpath,1712reason,1713base && fileURLToPath(base)1714);1715}
1716function throwInvalidPackageTarget(subpath, target, packageJSONUrl, internal, base) {1717if (typeof target === "object" && target !== null) {1718target = JSONStringify(target, null, "");1719} else {1720target = `${target}`;1721}1722throw new ERR_INVALID_PACKAGE_TARGET(1723fileURLToPath(new URL(".", packageJSONUrl)),1724subpath,1725target,1726internal,1727base && fileURLToPath(base)1728);1729}
1730const invalidSegmentRegEx = /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i;1731const patternRegEx = /\*/g;1732function resolvePackageTargetString(target, subpath, match, packageJSONUrl, base, pattern, internal, conditions) {1733if (subpath !== "" && !pattern && target[target.length - 1] !== "/")1734throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);1735if (!StringPrototypeStartsWith(target, "./")) {1736if (internal && !StringPrototypeStartsWith(target, "../") && !StringPrototypeStartsWith(target, "/")) {1737let isURL = false;1738try {1739new URL(target);1740isURL = true;1741} catch {1742}1743if (!isURL) {1744const exportTarget = pattern ? RegExpPrototypeSymbolReplace(patternRegEx, target, () => subpath) : target + subpath;1745return exportTarget;1746}1747}1748throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);1749}1750if (RegExpPrototypeExec(1751invalidSegmentRegEx,1752StringPrototypeSlice(target, 2)1753) !== null)1754throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);1755const resolved = new URL(target, packageJSONUrl);1756const resolvedPath = resolved.pathname;1757const packagePath = new URL(".", packageJSONUrl).pathname;1758if (!StringPrototypeStartsWith(resolvedPath, packagePath))1759throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);1760if (subpath === "")1761return resolved;1762if (RegExpPrototypeExec(invalidSegmentRegEx, subpath) !== null) {1763const request = pattern ? StringPrototypeReplace(match, "*", () => subpath) : match + subpath;1764throwInvalidSubpath(request, packageJSONUrl, internal, base);1765}1766if (pattern) {1767return new URL(1768RegExpPrototypeSymbolReplace(patternRegEx, resolved.href, () => subpath)1769);1770}1771return new URL(subpath, resolved);1772}
1773function isArrayIndex(key) {1774const keyNum = +key;1775if (`${keyNum}` !== key)1776return false;1777return keyNum >= 0 && keyNum < 4294967295;1778}
1779function resolvePackageTarget(packageJSONUrl, target, subpath, packageSubpath, base, pattern, internal, conditions) {1780if (typeof target === "string") {1781return resolvePackageTargetString(1782target,1783subpath,1784packageSubpath,1785packageJSONUrl,1786base,1787pattern,1788internal);1789} else if (ArrayIsArray(target)) {1790if (target.length === 0) {1791return null;1792}1793let lastException;1794for (let i = 0; i < target.length; i++) {1795const targetItem = target[i];1796let resolveResult;1797try {1798resolveResult = resolvePackageTarget(1799packageJSONUrl,1800targetItem,1801subpath,1802packageSubpath,1803base,1804pattern,1805internal,1806conditions
1807);1808} catch (e) {1809lastException = e;1810if (e.code === "ERR_INVALID_PACKAGE_TARGET") {1811continue;1812}1813throw e;1814}1815if (resolveResult === void 0) {1816continue;1817}1818if (resolveResult === null) {1819lastException = null;1820continue;1821}1822return resolveResult;1823}1824if (lastException === void 0 || lastException === null)1825return lastException;1826throw lastException;1827} else if (typeof target === "object" && target !== null) {1828const keys = ObjectGetOwnPropertyNames(target);1829for (let i = 0; i < keys.length; i++) {1830const key = keys[i];1831if (isArrayIndex(key)) {1832throw new ERR_INVALID_PACKAGE_CONFIG(1833fileURLToPath(packageJSONUrl),1834base,1835'"exports" cannot contain numeric property keys.'1836);1837}1838}1839for (let i = 0; i < keys.length; i++) {1840const key = keys[i];1841if (key === "default" || conditions.has(key)) {1842const conditionalTarget = target[key];1843const resolveResult = resolvePackageTarget(1844packageJSONUrl,1845conditionalTarget,1846subpath,1847packageSubpath,1848base,1849pattern,1850internal,1851conditions
1852);1853if (resolveResult === void 0)1854continue;1855return resolveResult;1856}1857}1858return void 0;1859} else if (target === null) {1860return null;1861}1862throwInvalidPackageTarget(1863packageSubpath,1864target,1865packageJSONUrl,1866internal,1867base
1868);1869}
1870function patternKeyCompare(a, b) {1871const aPatternIndex = StringPrototypeIndexOf(a, "*");1872const bPatternIndex = StringPrototypeIndexOf(b, "*");1873const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;1874const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;1875if (baseLenA > baseLenB)1876return -1;1877if (baseLenB > baseLenA)1878return 1;1879if (aPatternIndex === -1)1880return 1;1881if (bPatternIndex === -1)1882return -1;1883if (a.length > b.length)1884return -1;1885if (b.length > a.length)1886return 1;1887return 0;1888}
1889function packageImportsResolve({ name, base, conditions, readFileSyncFn }) {1890if (name === "#" || StringPrototypeStartsWith(name, "#/") || StringPrototypeEndsWith(name, "/")) {1891const reason = "is not a valid internal imports specifier name";1892throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath(base));1893}1894let packageJSONUrl;1895const packageConfig = getPackageScopeConfig(base, readFileSyncFn);1896if (packageConfig.exists) {1897packageJSONUrl = pathToFileURL(packageConfig.pjsonPath);1898const imports = packageConfig.imports;1899if (imports) {1900if (ObjectPrototypeHasOwnProperty(imports, name) && !StringPrototypeIncludes(name, "*")) {1901const resolveResult = resolvePackageTarget(1902packageJSONUrl,1903imports[name],1904"",1905name,1906base,1907false,1908true,1909conditions
1910);1911if (resolveResult != null) {1912return resolveResult;1913}1914} else {1915let bestMatch = "";1916let bestMatchSubpath;1917const keys = ObjectGetOwnPropertyNames(imports);1918for (let i = 0; i < keys.length; i++) {1919const key = keys[i];1920const patternIndex = StringPrototypeIndexOf(key, "*");1921if (patternIndex !== -1 && StringPrototypeStartsWith(1922name,1923StringPrototypeSlice(key, 0, patternIndex)1924)) {1925const patternTrailer = StringPrototypeSlice(key, patternIndex + 1);1926if (name.length >= key.length && StringPrototypeEndsWith(name, patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && StringPrototypeLastIndexOf(key, "*") === patternIndex) {1927bestMatch = key;1928bestMatchSubpath = StringPrototypeSlice(1929name,1930patternIndex,1931name.length - patternTrailer.length1932);1933}1934}1935}1936if (bestMatch) {1937const target = imports[bestMatch];1938const resolveResult = resolvePackageTarget(1939packageJSONUrl,1940target,1941bestMatchSubpath,1942bestMatch,1943base,1944true,1945true,1946conditions
1947);1948if (resolveResult != null) {1949return resolveResult;1950}1951}1952}1953}1954}1955throwImportNotDefined(name, packageJSONUrl, base);1956}
1957
1958const pathRegExp = /^(?![a-zA-Z]:[\\/]|\\\\|\.{0,2}(?:\/|$))((?:node:)?(?:@[^/]+\/)?[^/]+)\/*(.*|)$/;1959const isRelativeRegexp = /^\.{0,2}\//;1960function tryReadFile(filePath) {1961try {1962return fs.readFileSync(filePath, `utf8`);1963} catch (err) {1964if (err.code === `ENOENT`)1965return void 0;1966throw err;1967}1968}
1969async function resolvePrivateRequest(specifier, issuer, context, nextResolve) {1970const resolved = packageImportsResolve({1971name: specifier,1972base: pathToFileURL(issuer),1973conditions: new Set(context.conditions),1974readFileSyncFn: tryReadFile1975});1976if (resolved instanceof URL) {1977return { url: resolved.href, shortCircuit: true };1978} else {1979if (resolved.startsWith(`#`))1980throw new Error(`Mapping from one private import to another isn't allowed`);1981return resolve$1(resolved, context, nextResolve);1982}1983}
1984async function resolve$1(originalSpecifier, context, nextResolve) {1985const { findPnpApi } = moduleExports;1986if (!findPnpApi || isBuiltin(originalSpecifier))1987return nextResolve(originalSpecifier, context, nextResolve);1988let specifier = originalSpecifier;1989const url = tryParseURL(specifier, isRelativeRegexp.test(specifier) ? context.parentURL : void 0);1990if (url) {1991if (url.protocol !== `file:`)1992return nextResolve(originalSpecifier, context, nextResolve);1993specifier = fileURLToPath(url);1994}1995const { parentURL, conditions = [] } = context;1996const issuer = parentURL && tryParseURL(parentURL)?.protocol === `file:` ? fileURLToPath(parentURL) : process.cwd();1997const pnpapi = findPnpApi(issuer) ?? (url ? findPnpApi(specifier) : null);1998if (!pnpapi)1999return nextResolve(originalSpecifier, context, nextResolve);2000if (specifier.startsWith(`#`))2001return resolvePrivateRequest(specifier, issuer, context, nextResolve);2002const dependencyNameMatch = specifier.match(pathRegExp);2003let allowLegacyResolve = false;2004if (dependencyNameMatch) {2005const [, dependencyName, subPath] = dependencyNameMatch;2006if (subPath === `` && dependencyName !== `pnpapi`) {2007const resolved = pnpapi.resolveToUnqualified(`${dependencyName}/package.json`, issuer);2008if (resolved) {2009const content = await tryReadFile$1(resolved);2010if (content) {2011const pkg = JSON.parse(content);2012allowLegacyResolve = pkg.exports == null;2013}2014}2015}2016}2017let result;2018try {2019result = pnpapi.resolveRequest(specifier, issuer, {2020conditions: new Set(conditions),2021extensions: allowLegacyResolve ? void 0 : []2022});2023} catch (err) {2024if (err instanceof Error && `code` in err && err.code === `MODULE_NOT_FOUND`)2025err.code = `ERR_MODULE_NOT_FOUND`;2026throw err;2027}2028if (!result)2029throw new Error(`Resolving '${specifier}' from '${issuer}' failed`);2030const resultURL = pathToFileURL(result);2031if (url) {2032resultURL.search = url.search;2033resultURL.hash = url.hash;2034}2035if (!parentURL)2036setEntrypointPath(fileURLToPath(resultURL));2037return {2038url: resultURL.href,2039shortCircuit: true2040};2041}
2042
2043if (!HAS_LAZY_LOADED_TRANSLATORS) {2044const binding = process.binding(`fs`);2045const originalReadFile = binding.readFileUtf8 || binding.readFileSync;2046if (originalReadFile) {2047binding[originalReadFile.name] = function(...args) {2048try {2049return fs.readFileSync(args[0], {2050encoding: `utf8`,2051flag: args[1]2052});2053} catch {2054}2055return originalReadFile.apply(this, args);2056};2057} else {2058const binding2 = process.binding(`fs`);2059const originalfstat = binding2.fstat;2060const ZIP_MASK = 4278190080;2061const ZIP_MAGIC = 704643072;2062binding2.fstat = function(...args) {2063const [fd, useBigint, req] = args;2064if ((fd & ZIP_MASK) === ZIP_MAGIC && useBigint === false && req === void 0) {2065try {2066const stats = fs.fstatSync(fd);2067return new Float64Array([2068stats.dev,2069stats.mode,2070stats.nlink,2071stats.uid,2072stats.gid,2073stats.rdev,2074stats.blksize,2075stats.ino,2076stats.size,2077stats.blocks2078]);2079} catch {2080}2081}2082return originalfstat.apply(this, args);2083};2084}2085}
2086
2087const resolve = resolve$1;2088const load = load$1;2089
2090export { load, resolve };2091