.pnp.loader.mjs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import { URL, fileURLToPath, pathToFileURL } from 'url';
  2. import fs from 'fs';
  3. import path from 'path';
  4. import moduleExports, { Module } from 'module';
  5. var PathType;
  6. (function(PathType2) {
  7. PathType2[PathType2["File"] = 0] = "File";
  8. PathType2[PathType2["Portable"] = 1] = "Portable";
  9. PathType2[PathType2["Native"] = 2] = "Native";
  10. })(PathType || (PathType = {}));
  11. const npath = Object.create(path);
  12. const ppath = Object.create(path.posix);
  13. npath.cwd = () => process.cwd();
  14. ppath.cwd = () => toPortablePath(process.cwd());
  15. ppath.resolve = (...segments) => {
  16. if (segments.length > 0 && ppath.isAbsolute(segments[0])) {
  17. return path.posix.resolve(...segments);
  18. } else {
  19. return path.posix.resolve(ppath.cwd(), ...segments);
  20. }
  21. };
  22. const contains = function(pathUtils, from, to) {
  23. from = pathUtils.normalize(from);
  24. to = pathUtils.normalize(to);
  25. if (from === to)
  26. return `.`;
  27. if (!from.endsWith(pathUtils.sep))
  28. from = from + pathUtils.sep;
  29. if (to.startsWith(from)) {
  30. return to.slice(from.length);
  31. } else {
  32. return null;
  33. }
  34. };
  35. npath.fromPortablePath = fromPortablePath;
  36. npath.toPortablePath = toPortablePath;
  37. npath.contains = (from, to) => contains(npath, from, to);
  38. ppath.contains = (from, to) => contains(ppath, from, to);
  39. const WINDOWS_PATH_REGEXP = /^([a-zA-Z]:.*)$/;
  40. const UNC_WINDOWS_PATH_REGEXP = /^\/\/(\.\/)?(.*)$/;
  41. const PORTABLE_PATH_REGEXP = /^\/([a-zA-Z]:.*)$/;
  42. const UNC_PORTABLE_PATH_REGEXP = /^\/unc\/(\.dot\/)?(.*)$/;
  43. function fromPortablePath(p) {
  44. if (process.platform !== `win32`)
  45. return p;
  46. let portablePathMatch, uncPortablePathMatch;
  47. if (portablePathMatch = p.match(PORTABLE_PATH_REGEXP))
  48. p = portablePathMatch[1];
  49. else if (uncPortablePathMatch = p.match(UNC_PORTABLE_PATH_REGEXP))
  50. p = `\\\\${uncPortablePathMatch[1] ? `.\\` : ``}${uncPortablePathMatch[2]}`;
  51. else
  52. return p;
  53. return p.replace(/\//g, `\\`);
  54. }
  55. function toPortablePath(p) {
  56. if (process.platform !== `win32`)
  57. return p;
  58. p = p.replace(/\\/g, `/`);
  59. let windowsPathMatch, uncWindowsPathMatch;
  60. if (windowsPathMatch = p.match(WINDOWS_PATH_REGEXP))
  61. p = `/${windowsPathMatch[1]}`;
  62. else if (uncWindowsPathMatch = p.match(UNC_WINDOWS_PATH_REGEXP))
  63. p = `/unc/${uncWindowsPathMatch[1] ? `.dot/` : ``}${uncWindowsPathMatch[2]}`;
  64. return p;
  65. }
  66. const builtinModules = new Set(Module.builtinModules || Object.keys(process.binding(`natives`)));
  67. const isBuiltinModule = (request) => request.startsWith(`node:`) || builtinModules.has(request);
  68. function readPackageScope(checkPath) {
  69. const rootSeparatorIndex = checkPath.indexOf(npath.sep);
  70. let separatorIndex;
  71. do {
  72. separatorIndex = checkPath.lastIndexOf(npath.sep);
  73. checkPath = checkPath.slice(0, separatorIndex);
  74. if (checkPath.endsWith(`${npath.sep}node_modules`))
  75. return false;
  76. const pjson = readPackage(checkPath + npath.sep);
  77. if (pjson) {
  78. return {
  79. data: pjson,
  80. path: checkPath
  81. };
  82. }
  83. } while (separatorIndex > rootSeparatorIndex);
  84. return false;
  85. }
  86. function readPackage(requestPath) {
  87. const jsonPath = npath.resolve(requestPath, `package.json`);
  88. if (!fs.existsSync(jsonPath))
  89. return null;
  90. return JSON.parse(fs.readFileSync(jsonPath, `utf8`));
  91. }
  92. async function tryReadFile(path2) {
  93. try {
  94. return await fs.promises.readFile(path2, `utf8`);
  95. } catch (error) {
  96. if (error.code === `ENOENT`)
  97. return null;
  98. throw error;
  99. }
  100. }
  101. function tryParseURL(str, base) {
  102. try {
  103. return new URL(str, base);
  104. } catch {
  105. return null;
  106. }
  107. }
  108. let entrypointPath = null;
  109. function setEntrypointPath(file) {
  110. entrypointPath = file;
  111. }
  112. function getFileFormat(filepath) {
  113. var _a, _b;
  114. const ext = path.extname(filepath);
  115. switch (ext) {
  116. case `.mjs`: {
  117. return `module`;
  118. }
  119. case `.cjs`: {
  120. return `commonjs`;
  121. }
  122. case `.wasm`: {
  123. throw new Error(`Unknown file extension ".wasm" for ${filepath}`);
  124. }
  125. case `.json`: {
  126. throw new Error(`Unknown file extension ".json" for ${filepath}`);
  127. }
  128. case `.js`: {
  129. const pkg = readPackageScope(filepath);
  130. if (!pkg)
  131. return `commonjs`;
  132. return (_a = pkg.data.type) != null ? _a : `commonjs`;
  133. }
  134. default: {
  135. if (entrypointPath !== filepath)
  136. return null;
  137. const pkg = readPackageScope(filepath);
  138. if (!pkg)
  139. return `commonjs`;
  140. if (pkg.data.type === `module`)
  141. return null;
  142. return (_b = pkg.data.type) != null ? _b : `commonjs`;
  143. }
  144. }
  145. }
  146. async function getFormat$1(resolved, context, defaultGetFormat) {
  147. const url = tryParseURL(resolved);
  148. if ((url == null ? void 0 : url.protocol) !== `file:`)
  149. return defaultGetFormat(resolved, context, defaultGetFormat);
  150. const format = getFileFormat(fileURLToPath(url));
  151. if (format) {
  152. return {
  153. format
  154. };
  155. }
  156. return defaultGetFormat(resolved, context, defaultGetFormat);
  157. }
  158. async function getSource$1(urlString, context, defaultGetSource) {
  159. const url = tryParseURL(urlString);
  160. if ((url == null ? void 0 : url.protocol) !== `file:`)
  161. return defaultGetSource(urlString, context, defaultGetSource);
  162. return {
  163. source: await fs.promises.readFile(fileURLToPath(url), `utf8`)
  164. };
  165. }
  166. async function load$1(urlString, context, defaultLoad) {
  167. const url = tryParseURL(urlString);
  168. if ((url == null ? void 0 : url.protocol) !== `file:`)
  169. return defaultLoad(urlString, context, defaultLoad);
  170. const filePath = fileURLToPath(url);
  171. const format = getFileFormat(filePath);
  172. if (!format)
  173. return defaultLoad(urlString, context, defaultLoad);
  174. return {
  175. format,
  176. source: await fs.promises.readFile(filePath, `utf8`)
  177. };
  178. }
  179. const pathRegExp = /^(?![a-zA-Z]:[\\/]|\\\\|\.{0,2}(?:\/|$))((?:node:)?(?:@[^/]+\/)?[^/]+)\/*(.*|)$/;
  180. const isRelativeRegexp = /^\.{0,2}\//;
  181. async function resolve$1(originalSpecifier, context, defaultResolver) {
  182. var _a;
  183. const {findPnpApi} = moduleExports;
  184. if (!findPnpApi || isBuiltinModule(originalSpecifier))
  185. return defaultResolver(originalSpecifier, context, defaultResolver);
  186. let specifier = originalSpecifier;
  187. const url = tryParseURL(specifier, isRelativeRegexp.test(specifier) ? context.parentURL : void 0);
  188. if (url) {
  189. if (url.protocol !== `file:`)
  190. return defaultResolver(originalSpecifier, context, defaultResolver);
  191. specifier = fileURLToPath(url);
  192. }
  193. const {parentURL, conditions = []} = context;
  194. const issuer = parentURL ? fileURLToPath(parentURL) : process.cwd();
  195. const pnpapi = (_a = findPnpApi(issuer)) != null ? _a : url ? findPnpApi(specifier) : null;
  196. if (!pnpapi)
  197. return defaultResolver(originalSpecifier, context, defaultResolver);
  198. const dependencyNameMatch = specifier.match(pathRegExp);
  199. let allowLegacyResolve = false;
  200. if (dependencyNameMatch) {
  201. const [, dependencyName, subPath] = dependencyNameMatch;
  202. if (subPath === ``) {
  203. const resolved = pnpapi.resolveToUnqualified(`${dependencyName}/package.json`, issuer);
  204. if (resolved) {
  205. const content = await tryReadFile(resolved);
  206. if (content) {
  207. const pkg = JSON.parse(content);
  208. allowLegacyResolve = pkg.exports == null;
  209. }
  210. }
  211. }
  212. }
  213. const result = pnpapi.resolveRequest(specifier, issuer, {
  214. conditions: new Set(conditions),
  215. extensions: allowLegacyResolve ? void 0 : []
  216. });
  217. if (!result)
  218. throw new Error(`Resolving '${specifier}' from '${issuer}' failed`);
  219. const resultURL = pathToFileURL(result);
  220. if (url) {
  221. resultURL.search = url.search;
  222. resultURL.hash = url.hash;
  223. }
  224. if (!parentURL)
  225. setEntrypointPath(fileURLToPath(resultURL));
  226. return {
  227. url: resultURL.href
  228. };
  229. }
  230. const binding = process.binding(`fs`);
  231. const originalfstat = binding.fstat;
  232. const ZIP_FD = 2147483648;
  233. binding.fstat = function(...args) {
  234. const [fd, useBigint, req] = args;
  235. if ((fd & ZIP_FD) !== 0 && useBigint === false && req === void 0) {
  236. try {
  237. const stats = fs.fstatSync(fd);
  238. return new Float64Array([
  239. stats.dev,
  240. stats.mode,
  241. stats.nlink,
  242. stats.uid,
  243. stats.gid,
  244. stats.rdev,
  245. stats.blksize,
  246. stats.ino,
  247. stats.size,
  248. stats.blocks
  249. ]);
  250. } catch {
  251. }
  252. }
  253. return originalfstat.apply(this, args);
  254. };
  255. const [major, minor] = process.versions.node.split(`.`).map((value) => parseInt(value, 10));
  256. const hasConsolidatedHooks = major > 16 || major === 16 && minor >= 12;
  257. const resolve = resolve$1;
  258. const getFormat = hasConsolidatedHooks ? void 0 : getFormat$1;
  259. const getSource = hasConsolidatedHooks ? void 0 : getSource$1;
  260. const load = hasConsolidatedHooks ? load$1 : void 0;
  261. export { getFormat, getSource, load, resolve };