.pnp.loader.mjs 68 KB

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