.pnp.loader.mjs 70 KB

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