index.cjs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __export = (target, all) => {
  9. for (var name in all)
  10. __defProp(target, name, { get: all[name], enumerable: true });
  11. };
  12. var __copyProps = (to, from, except, desc) => {
  13. if (from && typeof from === "object" || typeof from === "function") {
  14. for (let key of __getOwnPropNames(from))
  15. if (!__hasOwnProp.call(to, key) && key !== except)
  16. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  17. }
  18. return to;
  19. };
  20. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  21. // If the importer is in node compatibility mode or this is not an ESM
  22. // file that has been converted to a CommonJS file using a Babel-
  23. // compatible transform (i.e. "__esModule" has not been set), then set
  24. // "default" to the CommonJS "module.exports" for node compatibility.
  25. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  26. mod
  27. ));
  28. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  29. // index.js
  30. var index_exports = {};
  31. __export(index_exports, {
  32. moduleResolve: () => moduleResolve,
  33. resolve: () => resolve
  34. });
  35. module.exports = __toCommonJS(index_exports);
  36. // lib/resolve.js
  37. var import_node_assert2 = __toESM(require("node:assert"), 1);
  38. var import_node_fs2 = require("node:fs");
  39. var import_node_process = __toESM(require("node:process"), 1);
  40. var import_node_url3 = require("node:url");
  41. var import_node_path2 = __toESM(require("node:path"), 1);
  42. var import_node_module = require("node:module");
  43. // lib/get-format.js
  44. var import_node_url2 = require("node:url");
  45. // lib/package-json-reader.js
  46. var import_node_fs = __toESM(require("node:fs"), 1);
  47. var import_node_path = __toESM(require("node:path"), 1);
  48. var import_node_url = require("node:url");
  49. // lib/errors.js
  50. var import_node_v8 = __toESM(require("node:v8"), 1);
  51. var import_node_assert = __toESM(require("node:assert"), 1);
  52. var import_node_util = require("node:util");
  53. var own = {}.hasOwnProperty;
  54. var classRegExp = /^([A-Z][a-z\d]*)+$/;
  55. var kTypes = /* @__PURE__ */ new Set([
  56. "string",
  57. "function",
  58. "number",
  59. "object",
  60. // Accept 'Function' and 'Object' as alternative to the lower cased version.
  61. "Function",
  62. "Object",
  63. "boolean",
  64. "bigint",
  65. "symbol"
  66. ]);
  67. var codes = {};
  68. function formatList(array, type = "and") {
  69. return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array[array.length - 1]}`;
  70. }
  71. var messages = /* @__PURE__ */ new Map();
  72. var nodeInternalPrefix = "__node_internal_";
  73. var userStackTraceLimit;
  74. codes.ERR_INVALID_ARG_TYPE = createError(
  75. "ERR_INVALID_ARG_TYPE",
  76. /**
  77. * @param {string} name
  78. * @param {Array<string> | string} expected
  79. * @param {unknown} actual
  80. */
  81. (name, expected, actual) => {
  82. import_node_assert.default.ok(typeof name === "string", "'name' must be a string");
  83. if (!Array.isArray(expected)) {
  84. expected = [expected];
  85. }
  86. let message = "The ";
  87. if (name.endsWith(" argument")) {
  88. message += `${name} `;
  89. } else {
  90. const type = name.includes(".") ? "property" : "argument";
  91. message += `"${name}" ${type} `;
  92. }
  93. message += "must be ";
  94. const types = [];
  95. const instances = [];
  96. const other = [];
  97. for (const value of expected) {
  98. import_node_assert.default.ok(
  99. typeof value === "string",
  100. "All expected entries have to be of type string"
  101. );
  102. if (kTypes.has(value)) {
  103. types.push(value.toLowerCase());
  104. } else if (classRegExp.exec(value) === null) {
  105. import_node_assert.default.ok(
  106. value !== "object",
  107. 'The value "object" should be written as "Object"'
  108. );
  109. other.push(value);
  110. } else {
  111. instances.push(value);
  112. }
  113. }
  114. if (instances.length > 0) {
  115. const pos = types.indexOf("object");
  116. if (pos !== -1) {
  117. types.slice(pos, 1);
  118. instances.push("Object");
  119. }
  120. }
  121. if (types.length > 0) {
  122. message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(
  123. types,
  124. "or"
  125. )}`;
  126. if (instances.length > 0 || other.length > 0) message += " or ";
  127. }
  128. if (instances.length > 0) {
  129. message += `an instance of ${formatList(instances, "or")}`;
  130. if (other.length > 0) message += " or ";
  131. }
  132. if (other.length > 0) {
  133. if (other.length > 1) {
  134. message += `one of ${formatList(other, "or")}`;
  135. } else {
  136. if (other[0].toLowerCase() !== other[0]) message += "an ";
  137. message += `${other[0]}`;
  138. }
  139. }
  140. message += `. Received ${determineSpecificType(actual)}`;
  141. return message;
  142. },
  143. TypeError
  144. );
  145. codes.ERR_INVALID_MODULE_SPECIFIER = createError(
  146. "ERR_INVALID_MODULE_SPECIFIER",
  147. /**
  148. * @param {string} request
  149. * @param {string} reason
  150. * @param {string} [base]
  151. */
  152. (request, reason, base = void 0) => {
  153. return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
  154. },
  155. TypeError
  156. );
  157. codes.ERR_INVALID_PACKAGE_CONFIG = createError(
  158. "ERR_INVALID_PACKAGE_CONFIG",
  159. /**
  160. * @param {string} path
  161. * @param {string} [base]
  162. * @param {string} [message]
  163. */
  164. (path3, base, message) => {
  165. return `Invalid package config ${path3}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
  166. },
  167. Error
  168. );
  169. codes.ERR_INVALID_PACKAGE_TARGET = createError(
  170. "ERR_INVALID_PACKAGE_TARGET",
  171. /**
  172. * @param {string} packagePath
  173. * @param {string} key
  174. * @param {unknown} target
  175. * @param {boolean} [isImport=false]
  176. * @param {string} [base]
  177. */
  178. (packagePath, key, target, isImport = false, base = void 0) => {
  179. const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
  180. if (key === ".") {
  181. import_node_assert.default.ok(isImport === false);
  182. return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
  183. }
  184. return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
  185. target
  186. )} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
  187. },
  188. Error
  189. );
  190. codes.ERR_MODULE_NOT_FOUND = createError(
  191. "ERR_MODULE_NOT_FOUND",
  192. /**
  193. * @param {string} path
  194. * @param {string} base
  195. * @param {boolean} [exactUrl]
  196. */
  197. (path3, base, exactUrl = false) => {
  198. return `Cannot find ${exactUrl ? "module" : "package"} '${path3}' imported from ${base}`;
  199. },
  200. Error
  201. );
  202. codes.ERR_NETWORK_IMPORT_DISALLOWED = createError(
  203. "ERR_NETWORK_IMPORT_DISALLOWED",
  204. "import of '%s' by %s is not supported: %s",
  205. Error
  206. );
  207. codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
  208. "ERR_PACKAGE_IMPORT_NOT_DEFINED",
  209. /**
  210. * @param {string} specifier
  211. * @param {string} packagePath
  212. * @param {string} base
  213. */
  214. (specifier, packagePath, base) => {
  215. return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ""} imported from ${base}`;
  216. },
  217. TypeError
  218. );
  219. codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
  220. "ERR_PACKAGE_PATH_NOT_EXPORTED",
  221. /**
  222. * @param {string} packagePath
  223. * @param {string} subpath
  224. * @param {string} [base]
  225. */
  226. (packagePath, subpath, base = void 0) => {
  227. if (subpath === ".")
  228. return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
  229. return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
  230. },
  231. Error
  232. );
  233. codes.ERR_UNSUPPORTED_DIR_IMPORT = createError(
  234. "ERR_UNSUPPORTED_DIR_IMPORT",
  235. "Directory import '%s' is not supported resolving ES modules imported from %s",
  236. Error
  237. );
  238. codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError(
  239. "ERR_UNSUPPORTED_RESOLVE_REQUEST",
  240. 'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.',
  241. TypeError
  242. );
  243. codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
  244. "ERR_UNKNOWN_FILE_EXTENSION",
  245. /**
  246. * @param {string} extension
  247. * @param {string} path
  248. */
  249. (extension, path3) => {
  250. return `Unknown file extension "${extension}" for ${path3}`;
  251. },
  252. TypeError
  253. );
  254. codes.ERR_INVALID_ARG_VALUE = createError(
  255. "ERR_INVALID_ARG_VALUE",
  256. /**
  257. * @param {string} name
  258. * @param {unknown} value
  259. * @param {string} [reason='is invalid']
  260. */
  261. (name, value, reason = "is invalid") => {
  262. let inspected = (0, import_node_util.inspect)(value);
  263. if (inspected.length > 128) {
  264. inspected = `${inspected.slice(0, 128)}...`;
  265. }
  266. const type = name.includes(".") ? "property" : "argument";
  267. return `The ${type} '${name}' ${reason}. Received ${inspected}`;
  268. },
  269. TypeError
  270. // Note: extra classes have been shaken out.
  271. // , RangeError
  272. );
  273. function createError(sym, value, constructor) {
  274. messages.set(sym, value);
  275. return makeNodeErrorWithCode(constructor, sym);
  276. }
  277. function makeNodeErrorWithCode(Base, key) {
  278. return NodeError;
  279. function NodeError(...parameters) {
  280. const limit = Error.stackTraceLimit;
  281. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
  282. const error = new Base();
  283. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
  284. const message = getMessage(key, parameters, error);
  285. Object.defineProperties(error, {
  286. // Note: no need to implement `kIsNodeError` symbol, would be hard,
  287. // probably.
  288. message: {
  289. value: message,
  290. enumerable: false,
  291. writable: true,
  292. configurable: true
  293. },
  294. toString: {
  295. /** @this {Error} */
  296. value() {
  297. return `${this.name} [${key}]: ${this.message}`;
  298. },
  299. enumerable: false,
  300. writable: true,
  301. configurable: true
  302. }
  303. });
  304. captureLargerStackTrace(error);
  305. error.code = key;
  306. return error;
  307. }
  308. }
  309. function isErrorStackTraceLimitWritable() {
  310. try {
  311. if (import_node_v8.default.startupSnapshot.isBuildingSnapshot()) {
  312. return false;
  313. }
  314. } catch {
  315. }
  316. const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
  317. if (desc === void 0) {
  318. return Object.isExtensible(Error);
  319. }
  320. return own.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
  321. }
  322. function hideStackFrames(wrappedFunction) {
  323. const hidden = nodeInternalPrefix + wrappedFunction.name;
  324. Object.defineProperty(wrappedFunction, "name", { value: hidden });
  325. return wrappedFunction;
  326. }
  327. var captureLargerStackTrace = hideStackFrames(
  328. /**
  329. * @param {Error} error
  330. * @returns {Error}
  331. */
  332. // @ts-expect-error: fine
  333. function(error) {
  334. const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
  335. if (stackTraceLimitIsWritable) {
  336. userStackTraceLimit = Error.stackTraceLimit;
  337. Error.stackTraceLimit = Number.POSITIVE_INFINITY;
  338. }
  339. Error.captureStackTrace(error);
  340. if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
  341. return error;
  342. }
  343. );
  344. function getMessage(key, parameters, self) {
  345. const message = messages.get(key);
  346. import_node_assert.default.ok(message !== void 0, "expected `message` to be found");
  347. if (typeof message === "function") {
  348. import_node_assert.default.ok(
  349. message.length <= parameters.length,
  350. // Default options do not count.
  351. `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
  352. );
  353. return Reflect.apply(message, self, parameters);
  354. }
  355. const regex = /%[dfijoOs]/g;
  356. let expectedLength = 0;
  357. while (regex.exec(message) !== null) expectedLength++;
  358. import_node_assert.default.ok(
  359. expectedLength === parameters.length,
  360. `Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
  361. );
  362. if (parameters.length === 0) return message;
  363. parameters.unshift(message);
  364. return Reflect.apply(import_node_util.format, null, parameters);
  365. }
  366. function determineSpecificType(value) {
  367. if (value === null || value === void 0) {
  368. return String(value);
  369. }
  370. if (typeof value === "function" && value.name) {
  371. return `function ${value.name}`;
  372. }
  373. if (typeof value === "object") {
  374. if (value.constructor && value.constructor.name) {
  375. return `an instance of ${value.constructor.name}`;
  376. }
  377. return `${(0, import_node_util.inspect)(value, { depth: -1 })}`;
  378. }
  379. let inspected = (0, import_node_util.inspect)(value, { colors: false });
  380. if (inspected.length > 28) {
  381. inspected = `${inspected.slice(0, 25)}...`;
  382. }
  383. return `type ${typeof value} (${inspected})`;
  384. }
  385. // lib/package-json-reader.js
  386. var hasOwnProperty = {}.hasOwnProperty;
  387. var { ERR_INVALID_PACKAGE_CONFIG } = codes;
  388. var cache = /* @__PURE__ */ new Map();
  389. function read(jsonPath, { base, specifier }) {
  390. const existing = cache.get(jsonPath);
  391. if (existing) {
  392. return existing;
  393. }
  394. let string;
  395. try {
  396. string = import_node_fs.default.readFileSync(import_node_path.default.toNamespacedPath(jsonPath), "utf8");
  397. } catch (error) {
  398. const exception = (
  399. /** @type {ErrnoException} */
  400. error
  401. );
  402. if (exception.code !== "ENOENT") {
  403. throw exception;
  404. }
  405. }
  406. const result = {
  407. exists: false,
  408. pjsonPath: jsonPath,
  409. main: void 0,
  410. name: void 0,
  411. type: "none",
  412. // Ignore unknown types for forwards compatibility
  413. exports: void 0,
  414. imports: void 0
  415. };
  416. if (string !== void 0) {
  417. let parsed;
  418. try {
  419. parsed = JSON.parse(string);
  420. } catch (error_) {
  421. const cause = (
  422. /** @type {ErrnoException} */
  423. error_
  424. );
  425. const error = new ERR_INVALID_PACKAGE_CONFIG(
  426. jsonPath,
  427. (base ? `"${specifier}" from ` : "") + (0, import_node_url.fileURLToPath)(base || specifier),
  428. cause.message
  429. );
  430. error.cause = cause;
  431. throw error;
  432. }
  433. result.exists = true;
  434. if (hasOwnProperty.call(parsed, "name") && typeof parsed.name === "string") {
  435. result.name = parsed.name;
  436. }
  437. if (hasOwnProperty.call(parsed, "main") && typeof parsed.main === "string") {
  438. result.main = parsed.main;
  439. }
  440. if (hasOwnProperty.call(parsed, "exports")) {
  441. result.exports = parsed.exports;
  442. }
  443. if (hasOwnProperty.call(parsed, "imports")) {
  444. result.imports = parsed.imports;
  445. }
  446. if (hasOwnProperty.call(parsed, "type") && (parsed.type === "commonjs" || parsed.type === "module")) {
  447. result.type = parsed.type;
  448. }
  449. }
  450. cache.set(jsonPath, result);
  451. return result;
  452. }
  453. function getPackageScopeConfig(resolved) {
  454. let packageJSONUrl = new URL("package.json", resolved);
  455. while (true) {
  456. const packageJSONPath2 = packageJSONUrl.pathname;
  457. if (packageJSONPath2.endsWith("node_modules/package.json")) {
  458. break;
  459. }
  460. const packageConfig = read((0, import_node_url.fileURLToPath)(packageJSONUrl), {
  461. specifier: resolved
  462. });
  463. if (packageConfig.exists) {
  464. return packageConfig;
  465. }
  466. const lastPackageJSONUrl = packageJSONUrl;
  467. packageJSONUrl = new URL("../package.json", packageJSONUrl);
  468. if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
  469. break;
  470. }
  471. }
  472. const packageJSONPath = (0, import_node_url.fileURLToPath)(packageJSONUrl);
  473. return {
  474. pjsonPath: packageJSONPath,
  475. exists: false,
  476. type: "none"
  477. };
  478. }
  479. function getPackageType(url) {
  480. return getPackageScopeConfig(url).type;
  481. }
  482. // lib/get-format.js
  483. var { ERR_UNKNOWN_FILE_EXTENSION } = codes;
  484. var hasOwnProperty2 = {}.hasOwnProperty;
  485. var extensionFormatMap = {
  486. // @ts-expect-error: hush.
  487. __proto__: null,
  488. ".cjs": "commonjs",
  489. ".js": "module",
  490. ".json": "json",
  491. ".mjs": "module"
  492. };
  493. function mimeToFormat(mime) {
  494. if (mime && /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime))
  495. return "module";
  496. if (mime === "application/json") return "json";
  497. return null;
  498. }
  499. var protocolHandlers = {
  500. // @ts-expect-error: hush.
  501. __proto__: null,
  502. "data:": getDataProtocolModuleFormat,
  503. "file:": getFileProtocolModuleFormat,
  504. "http:": getHttpProtocolModuleFormat,
  505. "https:": getHttpProtocolModuleFormat,
  506. "node:"() {
  507. return "builtin";
  508. }
  509. };
  510. function getDataProtocolModuleFormat(parsed) {
  511. const { 1: mime } = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
  512. parsed.pathname
  513. ) || [null, null, null];
  514. return mimeToFormat(mime);
  515. }
  516. function extname(url) {
  517. const pathname = url.pathname;
  518. let index = pathname.length;
  519. while (index--) {
  520. const code = pathname.codePointAt(index);
  521. if (code === 47) {
  522. return "";
  523. }
  524. if (code === 46) {
  525. return pathname.codePointAt(index - 1) === 47 ? "" : pathname.slice(index);
  526. }
  527. }
  528. return "";
  529. }
  530. function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
  531. const value = extname(url);
  532. if (value === ".js") {
  533. const packageType = getPackageType(url);
  534. if (packageType !== "none") {
  535. return packageType;
  536. }
  537. return "commonjs";
  538. }
  539. if (value === "") {
  540. const packageType = getPackageType(url);
  541. if (packageType === "none" || packageType === "commonjs") {
  542. return "commonjs";
  543. }
  544. return "module";
  545. }
  546. const format2 = extensionFormatMap[value];
  547. if (format2) return format2;
  548. if (ignoreErrors) {
  549. return void 0;
  550. }
  551. const filepath = (0, import_node_url2.fileURLToPath)(url);
  552. throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath);
  553. }
  554. function getHttpProtocolModuleFormat() {
  555. }
  556. function defaultGetFormatWithoutErrors(url, context) {
  557. const protocol = url.protocol;
  558. if (!hasOwnProperty2.call(protocolHandlers, protocol)) {
  559. return null;
  560. }
  561. return protocolHandlers[protocol](url, context, true) || null;
  562. }
  563. // lib/utils.js
  564. var { ERR_INVALID_ARG_VALUE } = codes;
  565. var DEFAULT_CONDITIONS = Object.freeze(["node", "import"]);
  566. var DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS);
  567. function getDefaultConditions() {
  568. return DEFAULT_CONDITIONS;
  569. }
  570. function getDefaultConditionsSet() {
  571. return DEFAULT_CONDITIONS_SET;
  572. }
  573. function getConditionsSet(conditions) {
  574. if (conditions !== void 0 && conditions !== getDefaultConditions()) {
  575. if (!Array.isArray(conditions)) {
  576. throw new ERR_INVALID_ARG_VALUE(
  577. "conditions",
  578. conditions,
  579. "expected an array"
  580. );
  581. }
  582. return new Set(conditions);
  583. }
  584. return getDefaultConditionsSet();
  585. }
  586. // lib/resolve.js
  587. var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
  588. var {
  589. ERR_NETWORK_IMPORT_DISALLOWED,
  590. ERR_INVALID_MODULE_SPECIFIER,
  591. ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG2,
  592. ERR_INVALID_PACKAGE_TARGET,
  593. ERR_MODULE_NOT_FOUND,
  594. ERR_PACKAGE_IMPORT_NOT_DEFINED,
  595. ERR_PACKAGE_PATH_NOT_EXPORTED,
  596. ERR_UNSUPPORTED_DIR_IMPORT,
  597. ERR_UNSUPPORTED_RESOLVE_REQUEST
  598. } = codes;
  599. var own2 = {}.hasOwnProperty;
  600. var 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;
  601. var deprecatedInvalidSegmentRegEx = /(^|\\|\/)((\.|%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;
  602. var invalidPackageNameRegEx = /^\.|%|\\/;
  603. var patternRegEx = /\*/g;
  604. var encodedSeparatorRegEx = /%2f|%5c/i;
  605. var emittedPackageWarnings = /* @__PURE__ */ new Set();
  606. var doubleSlashRegEx = /[/\\]{2}/;
  607. function emitInvalidSegmentDeprecation(target, request, match, packageJsonUrl, internal, base, isTarget) {
  608. if (import_node_process.default.noDeprecation) {
  609. return;
  610. }
  611. const pjsonPath = (0, import_node_url3.fileURLToPath)(packageJsonUrl);
  612. const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
  613. import_node_process.default.emitWarning(
  614. `Use of deprecated ${double ? "double slash" : "leading or trailing slash matching"} resolving "${target}" for module request "${request}" ${request === match ? "" : `matched to "${match}" `}in the "${internal ? "imports" : "exports"}" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, import_node_url3.fileURLToPath)(base)}` : ""}.`,
  615. "DeprecationWarning",
  616. "DEP0166"
  617. );
  618. }
  619. function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
  620. if (import_node_process.default.noDeprecation) {
  621. return;
  622. }
  623. const format2 = defaultGetFormatWithoutErrors(url, { parentURL: base.href });
  624. if (format2 !== "module") return;
  625. const urlPath = (0, import_node_url3.fileURLToPath)(url.href);
  626. const packagePath = (0, import_node_url3.fileURLToPath)(new URL(".", packageJsonUrl));
  627. const basePath = (0, import_node_url3.fileURLToPath)(base);
  628. if (!main) {
  629. import_node_process.default.emitWarning(
  630. `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
  631. packagePath.length
  632. )}", imported from ${basePath}.
  633. Default "index" lookups for the main are deprecated for ES modules.`,
  634. "DeprecationWarning",
  635. "DEP0151"
  636. );
  637. } else if (import_node_path2.default.resolve(packagePath, main) !== urlPath) {
  638. import_node_process.default.emitWarning(
  639. `Package ${packagePath} has a "main" field set to "${main}", excluding the full filename and extension to the resolved file at "${urlPath.slice(
  640. packagePath.length
  641. )}", imported from ${basePath}.
  642. Automatic extension resolution of the "main" field is deprecated for ES modules.`,
  643. "DeprecationWarning",
  644. "DEP0151"
  645. );
  646. }
  647. }
  648. function tryStatSync(path3) {
  649. try {
  650. return (0, import_node_fs2.statSync)(path3);
  651. } catch {
  652. }
  653. }
  654. function fileExists(url) {
  655. const stats = (0, import_node_fs2.statSync)(url, { throwIfNoEntry: false });
  656. const isFile = stats ? stats.isFile() : void 0;
  657. return isFile === null || isFile === void 0 ? false : isFile;
  658. }
  659. function legacyMainResolve(packageJsonUrl, packageConfig, base) {
  660. let guess;
  661. if (packageConfig.main !== void 0) {
  662. guess = new URL(packageConfig.main, packageJsonUrl);
  663. if (fileExists(guess)) return guess;
  664. const tries2 = [
  665. `./${packageConfig.main}.js`,
  666. `./${packageConfig.main}.json`,
  667. `./${packageConfig.main}.node`,
  668. `./${packageConfig.main}/index.js`,
  669. `./${packageConfig.main}/index.json`,
  670. `./${packageConfig.main}/index.node`
  671. ];
  672. let i2 = -1;
  673. while (++i2 < tries2.length) {
  674. guess = new URL(tries2[i2], packageJsonUrl);
  675. if (fileExists(guess)) break;
  676. guess = void 0;
  677. }
  678. if (guess) {
  679. emitLegacyIndexDeprecation(
  680. guess,
  681. packageJsonUrl,
  682. base,
  683. packageConfig.main
  684. );
  685. return guess;
  686. }
  687. }
  688. const tries = ["./index.js", "./index.json", "./index.node"];
  689. let i = -1;
  690. while (++i < tries.length) {
  691. guess = new URL(tries[i], packageJsonUrl);
  692. if (fileExists(guess)) break;
  693. guess = void 0;
  694. }
  695. if (guess) {
  696. emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
  697. return guess;
  698. }
  699. throw new ERR_MODULE_NOT_FOUND(
  700. (0, import_node_url3.fileURLToPath)(new URL(".", packageJsonUrl)),
  701. (0, import_node_url3.fileURLToPath)(base)
  702. );
  703. }
  704. function finalizeResolution(resolved, base, preserveSymlinks) {
  705. if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
  706. throw new ERR_INVALID_MODULE_SPECIFIER(
  707. resolved.pathname,
  708. 'must not include encoded "/" or "\\" characters',
  709. (0, import_node_url3.fileURLToPath)(base)
  710. );
  711. }
  712. let filePath;
  713. try {
  714. filePath = (0, import_node_url3.fileURLToPath)(resolved);
  715. } catch (error) {
  716. const cause = (
  717. /** @type {ErrnoException} */
  718. error
  719. );
  720. Object.defineProperty(cause, "input", { value: String(resolved) });
  721. Object.defineProperty(cause, "module", { value: String(base) });
  722. throw cause;
  723. }
  724. const stats = tryStatSync(
  725. filePath.endsWith("/") ? filePath.slice(-1) : filePath
  726. );
  727. if (stats && stats.isDirectory()) {
  728. const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, (0, import_node_url3.fileURLToPath)(base));
  729. error.url = String(resolved);
  730. throw error;
  731. }
  732. if (!stats || !stats.isFile()) {
  733. const error = new ERR_MODULE_NOT_FOUND(
  734. filePath || resolved.pathname,
  735. base && (0, import_node_url3.fileURLToPath)(base),
  736. true
  737. );
  738. error.url = String(resolved);
  739. throw error;
  740. }
  741. if (!preserveSymlinks) {
  742. const real = (0, import_node_fs2.realpathSync)(filePath);
  743. const { search, hash } = resolved;
  744. resolved = (0, import_node_url3.pathToFileURL)(real + (filePath.endsWith(import_node_path2.default.sep) ? "/" : ""));
  745. resolved.search = search;
  746. resolved.hash = hash;
  747. }
  748. return resolved;
  749. }
  750. function importNotDefined(specifier, packageJsonUrl, base) {
  751. return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
  752. specifier,
  753. packageJsonUrl && (0, import_node_url3.fileURLToPath)(new URL(".", packageJsonUrl)),
  754. (0, import_node_url3.fileURLToPath)(base)
  755. );
  756. }
  757. function exportsNotFound(subpath, packageJsonUrl, base) {
  758. return new ERR_PACKAGE_PATH_NOT_EXPORTED(
  759. (0, import_node_url3.fileURLToPath)(new URL(".", packageJsonUrl)),
  760. subpath,
  761. base && (0, import_node_url3.fileURLToPath)(base)
  762. );
  763. }
  764. function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
  765. const reason = `request is not a valid match in pattern "${match}" for the "${internal ? "imports" : "exports"}" resolution of ${(0, import_node_url3.fileURLToPath)(packageJsonUrl)}`;
  766. throw new ERR_INVALID_MODULE_SPECIFIER(
  767. request,
  768. reason,
  769. base && (0, import_node_url3.fileURLToPath)(base)
  770. );
  771. }
  772. function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
  773. target = typeof target === "object" && target !== null ? JSON.stringify(target, null, "") : `${target}`;
  774. return new ERR_INVALID_PACKAGE_TARGET(
  775. (0, import_node_url3.fileURLToPath)(new URL(".", packageJsonUrl)),
  776. subpath,
  777. target,
  778. internal,
  779. base && (0, import_node_url3.fileURLToPath)(base)
  780. );
  781. }
  782. function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, isPathMap, conditions) {
  783. if (subpath !== "" && !pattern && target[target.length - 1] !== "/")
  784. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
  785. if (!target.startsWith("./")) {
  786. if (internal && !target.startsWith("../") && !target.startsWith("/")) {
  787. let isURL2 = false;
  788. try {
  789. new URL(target);
  790. isURL2 = true;
  791. } catch {
  792. }
  793. if (!isURL2) {
  794. const exportTarget = pattern ? RegExpPrototypeSymbolReplace.call(
  795. patternRegEx,
  796. target,
  797. () => subpath
  798. ) : target + subpath;
  799. return packageResolve(exportTarget, packageJsonUrl, conditions);
  800. }
  801. }
  802. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
  803. }
  804. if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
  805. if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
  806. if (!isPathMap) {
  807. const request = pattern ? match.replace("*", () => subpath) : match + subpath;
  808. const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
  809. patternRegEx,
  810. target,
  811. () => subpath
  812. ) : target;
  813. emitInvalidSegmentDeprecation(
  814. resolvedTarget,
  815. request,
  816. match,
  817. packageJsonUrl,
  818. internal,
  819. base,
  820. true
  821. );
  822. }
  823. } else {
  824. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
  825. }
  826. }
  827. const resolved = new URL(target, packageJsonUrl);
  828. const resolvedPath = resolved.pathname;
  829. const packagePath = new URL(".", packageJsonUrl).pathname;
  830. if (!resolvedPath.startsWith(packagePath))
  831. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base);
  832. if (subpath === "") return resolved;
  833. if (invalidSegmentRegEx.exec(subpath) !== null) {
  834. const request = pattern ? match.replace("*", () => subpath) : match + subpath;
  835. if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
  836. if (!isPathMap) {
  837. const resolvedTarget = pattern ? RegExpPrototypeSymbolReplace.call(
  838. patternRegEx,
  839. target,
  840. () => subpath
  841. ) : target;
  842. emitInvalidSegmentDeprecation(
  843. resolvedTarget,
  844. request,
  845. match,
  846. packageJsonUrl,
  847. internal,
  848. base,
  849. false
  850. );
  851. }
  852. } else {
  853. throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
  854. }
  855. }
  856. if (pattern) {
  857. return new URL(
  858. RegExpPrototypeSymbolReplace.call(
  859. patternRegEx,
  860. resolved.href,
  861. () => subpath
  862. )
  863. );
  864. }
  865. return new URL(subpath, resolved);
  866. }
  867. function isArrayIndex(key) {
  868. const keyNumber = Number(key);
  869. if (`${keyNumber}` !== key) return false;
  870. return keyNumber >= 0 && keyNumber < 4294967295;
  871. }
  872. function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions) {
  873. if (typeof target === "string") {
  874. return resolvePackageTargetString(
  875. target,
  876. subpath,
  877. packageSubpath,
  878. packageJsonUrl,
  879. base,
  880. pattern,
  881. internal,
  882. isPathMap,
  883. conditions
  884. );
  885. }
  886. if (Array.isArray(target)) {
  887. const targetList = target;
  888. if (targetList.length === 0) return null;
  889. let lastException;
  890. let i = -1;
  891. while (++i < targetList.length) {
  892. const targetItem = targetList[i];
  893. let resolveResult;
  894. try {
  895. resolveResult = resolvePackageTarget(
  896. packageJsonUrl,
  897. targetItem,
  898. subpath,
  899. packageSubpath,
  900. base,
  901. pattern,
  902. internal,
  903. isPathMap,
  904. conditions
  905. );
  906. } catch (error) {
  907. const exception = (
  908. /** @type {ErrnoException} */
  909. error
  910. );
  911. lastException = exception;
  912. if (exception.code === "ERR_INVALID_PACKAGE_TARGET") continue;
  913. throw error;
  914. }
  915. if (resolveResult === void 0) continue;
  916. if (resolveResult === null) {
  917. lastException = null;
  918. continue;
  919. }
  920. return resolveResult;
  921. }
  922. if (lastException === void 0 || lastException === null) {
  923. return null;
  924. }
  925. throw lastException;
  926. }
  927. if (typeof target === "object" && target !== null) {
  928. const keys = Object.getOwnPropertyNames(target);
  929. let i = -1;
  930. while (++i < keys.length) {
  931. const key = keys[i];
  932. if (isArrayIndex(key)) {
  933. throw new ERR_INVALID_PACKAGE_CONFIG2(
  934. (0, import_node_url3.fileURLToPath)(packageJsonUrl),
  935. base,
  936. '"exports" cannot contain numeric property keys.'
  937. );
  938. }
  939. }
  940. i = -1;
  941. while (++i < keys.length) {
  942. const key = keys[i];
  943. if (key === "default" || conditions && conditions.has(key)) {
  944. const conditionalTarget = (
  945. /** @type {unknown} */
  946. target[key]
  947. );
  948. const resolveResult = resolvePackageTarget(
  949. packageJsonUrl,
  950. conditionalTarget,
  951. subpath,
  952. packageSubpath,
  953. base,
  954. pattern,
  955. internal,
  956. isPathMap,
  957. conditions
  958. );
  959. if (resolveResult === void 0) continue;
  960. return resolveResult;
  961. }
  962. }
  963. return null;
  964. }
  965. if (target === null) {
  966. return null;
  967. }
  968. throw invalidPackageTarget(
  969. packageSubpath,
  970. target,
  971. packageJsonUrl,
  972. internal,
  973. base
  974. );
  975. }
  976. function isConditionalExportsMainSugar(exports2, packageJsonUrl, base) {
  977. if (typeof exports2 === "string" || Array.isArray(exports2)) return true;
  978. if (typeof exports2 !== "object" || exports2 === null) return false;
  979. const keys = Object.getOwnPropertyNames(exports2);
  980. let isConditionalSugar = false;
  981. let i = 0;
  982. let keyIndex = -1;
  983. while (++keyIndex < keys.length) {
  984. const key = keys[keyIndex];
  985. const currentIsConditionalSugar = key === "" || key[0] !== ".";
  986. if (i++ === 0) {
  987. isConditionalSugar = currentIsConditionalSugar;
  988. } else if (isConditionalSugar !== currentIsConditionalSugar) {
  989. throw new ERR_INVALID_PACKAGE_CONFIG2(
  990. (0, import_node_url3.fileURLToPath)(packageJsonUrl),
  991. base,
  992. `"exports" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`
  993. );
  994. }
  995. }
  996. return isConditionalSugar;
  997. }
  998. function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
  999. if (import_node_process.default.noDeprecation) {
  1000. return;
  1001. }
  1002. const pjsonPath = (0, import_node_url3.fileURLToPath)(pjsonUrl);
  1003. if (emittedPackageWarnings.has(pjsonPath + "|" + match)) return;
  1004. emittedPackageWarnings.add(pjsonPath + "|" + match);
  1005. import_node_process.default.emitWarning(
  1006. `Use of deprecated trailing slash pattern mapping "${match}" in the "exports" field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, import_node_url3.fileURLToPath)(base)}` : ""}. Mapping specifiers ending in "/" is no longer supported.`,
  1007. "DeprecationWarning",
  1008. "DEP0155"
  1009. );
  1010. }
  1011. function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
  1012. let exports2 = packageConfig.exports;
  1013. if (isConditionalExportsMainSugar(exports2, packageJsonUrl, base)) {
  1014. exports2 = { ".": exports2 };
  1015. }
  1016. if (own2.call(exports2, packageSubpath) && !packageSubpath.includes("*") && !packageSubpath.endsWith("/")) {
  1017. const target = exports2[packageSubpath];
  1018. const resolveResult = resolvePackageTarget(
  1019. packageJsonUrl,
  1020. target,
  1021. "",
  1022. packageSubpath,
  1023. base,
  1024. false,
  1025. false,
  1026. false,
  1027. conditions
  1028. );
  1029. if (resolveResult === null || resolveResult === void 0) {
  1030. throw exportsNotFound(packageSubpath, packageJsonUrl, base);
  1031. }
  1032. return resolveResult;
  1033. }
  1034. let bestMatch = "";
  1035. let bestMatchSubpath = "";
  1036. const keys = Object.getOwnPropertyNames(exports2);
  1037. let i = -1;
  1038. while (++i < keys.length) {
  1039. const key = keys[i];
  1040. const patternIndex = key.indexOf("*");
  1041. if (patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex))) {
  1042. if (packageSubpath.endsWith("/")) {
  1043. emitTrailingSlashPatternDeprecation(
  1044. packageSubpath,
  1045. packageJsonUrl,
  1046. base
  1047. );
  1048. }
  1049. const patternTrailer = key.slice(patternIndex + 1);
  1050. if (packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
  1051. bestMatch = key;
  1052. bestMatchSubpath = packageSubpath.slice(
  1053. patternIndex,
  1054. packageSubpath.length - patternTrailer.length
  1055. );
  1056. }
  1057. }
  1058. }
  1059. if (bestMatch) {
  1060. const target = (
  1061. /** @type {unknown} */
  1062. exports2[bestMatch]
  1063. );
  1064. const resolveResult = resolvePackageTarget(
  1065. packageJsonUrl,
  1066. target,
  1067. bestMatchSubpath,
  1068. bestMatch,
  1069. base,
  1070. true,
  1071. false,
  1072. packageSubpath.endsWith("/"),
  1073. conditions
  1074. );
  1075. if (resolveResult === null || resolveResult === void 0) {
  1076. throw exportsNotFound(packageSubpath, packageJsonUrl, base);
  1077. }
  1078. return resolveResult;
  1079. }
  1080. throw exportsNotFound(packageSubpath, packageJsonUrl, base);
  1081. }
  1082. function patternKeyCompare(a, b) {
  1083. const aPatternIndex = a.indexOf("*");
  1084. const bPatternIndex = b.indexOf("*");
  1085. const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
  1086. const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
  1087. if (baseLengthA > baseLengthB) return -1;
  1088. if (baseLengthB > baseLengthA) return 1;
  1089. if (aPatternIndex === -1) return 1;
  1090. if (bPatternIndex === -1) return -1;
  1091. if (a.length > b.length) return -1;
  1092. if (b.length > a.length) return 1;
  1093. return 0;
  1094. }
  1095. function packageImportsResolve(name, base, conditions) {
  1096. if (name === "#" || name.startsWith("#/") || name.endsWith("/")) {
  1097. const reason = "is not a valid internal imports specifier name";
  1098. throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, (0, import_node_url3.fileURLToPath)(base));
  1099. }
  1100. let packageJsonUrl;
  1101. const packageConfig = getPackageScopeConfig(base);
  1102. if (packageConfig.exists) {
  1103. packageJsonUrl = (0, import_node_url3.pathToFileURL)(packageConfig.pjsonPath);
  1104. const imports = packageConfig.imports;
  1105. if (imports) {
  1106. if (own2.call(imports, name) && !name.includes("*")) {
  1107. const resolveResult = resolvePackageTarget(
  1108. packageJsonUrl,
  1109. imports[name],
  1110. "",
  1111. name,
  1112. base,
  1113. false,
  1114. true,
  1115. false,
  1116. conditions
  1117. );
  1118. if (resolveResult !== null && resolveResult !== void 0) {
  1119. return resolveResult;
  1120. }
  1121. } else {
  1122. let bestMatch = "";
  1123. let bestMatchSubpath = "";
  1124. const keys = Object.getOwnPropertyNames(imports);
  1125. let i = -1;
  1126. while (++i < keys.length) {
  1127. const key = keys[i];
  1128. const patternIndex = key.indexOf("*");
  1129. if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
  1130. const patternTrailer = key.slice(patternIndex + 1);
  1131. if (name.length >= key.length && name.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf("*") === patternIndex) {
  1132. bestMatch = key;
  1133. bestMatchSubpath = name.slice(
  1134. patternIndex,
  1135. name.length - patternTrailer.length
  1136. );
  1137. }
  1138. }
  1139. }
  1140. if (bestMatch) {
  1141. const target = imports[bestMatch];
  1142. const resolveResult = resolvePackageTarget(
  1143. packageJsonUrl,
  1144. target,
  1145. bestMatchSubpath,
  1146. bestMatch,
  1147. base,
  1148. true,
  1149. true,
  1150. false,
  1151. conditions
  1152. );
  1153. if (resolveResult !== null && resolveResult !== void 0) {
  1154. return resolveResult;
  1155. }
  1156. }
  1157. }
  1158. }
  1159. }
  1160. throw importNotDefined(name, packageJsonUrl, base);
  1161. }
  1162. function parsePackageName(specifier, base) {
  1163. let separatorIndex = specifier.indexOf("/");
  1164. let validPackageName = true;
  1165. let isScoped = false;
  1166. if (specifier[0] === "@") {
  1167. isScoped = true;
  1168. if (separatorIndex === -1 || specifier.length === 0) {
  1169. validPackageName = false;
  1170. } else {
  1171. separatorIndex = specifier.indexOf("/", separatorIndex + 1);
  1172. }
  1173. }
  1174. const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
  1175. if (invalidPackageNameRegEx.exec(packageName) !== null) {
  1176. validPackageName = false;
  1177. }
  1178. if (!validPackageName) {
  1179. throw new ERR_INVALID_MODULE_SPECIFIER(
  1180. specifier,
  1181. "is not a valid package name",
  1182. (0, import_node_url3.fileURLToPath)(base)
  1183. );
  1184. }
  1185. const packageSubpath = "." + (separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
  1186. return { packageName, packageSubpath, isScoped };
  1187. }
  1188. function packageResolve(specifier, base, conditions) {
  1189. if (import_node_module.builtinModules.includes(specifier)) {
  1190. return new URL("node:" + specifier);
  1191. }
  1192. const { packageName, packageSubpath, isScoped } = parsePackageName(
  1193. specifier,
  1194. base
  1195. );
  1196. const packageConfig = getPackageScopeConfig(base);
  1197. if (packageConfig.exists) {
  1198. const packageJsonUrl2 = (0, import_node_url3.pathToFileURL)(packageConfig.pjsonPath);
  1199. if (packageConfig.name === packageName && packageConfig.exports !== void 0 && packageConfig.exports !== null) {
  1200. return packageExportsResolve(
  1201. packageJsonUrl2,
  1202. packageSubpath,
  1203. packageConfig,
  1204. base,
  1205. conditions
  1206. );
  1207. }
  1208. }
  1209. let packageJsonUrl = new URL(
  1210. "./node_modules/" + packageName + "/package.json",
  1211. base
  1212. );
  1213. let packageJsonPath = (0, import_node_url3.fileURLToPath)(packageJsonUrl);
  1214. let lastPath;
  1215. do {
  1216. const stat = tryStatSync(packageJsonPath.slice(0, -13));
  1217. if (!stat || !stat.isDirectory()) {
  1218. lastPath = packageJsonPath;
  1219. packageJsonUrl = new URL(
  1220. (isScoped ? "../../../../node_modules/" : "../../../node_modules/") + packageName + "/package.json",
  1221. packageJsonUrl
  1222. );
  1223. packageJsonPath = (0, import_node_url3.fileURLToPath)(packageJsonUrl);
  1224. continue;
  1225. }
  1226. const packageConfig2 = read(packageJsonPath, { base, specifier });
  1227. if (packageConfig2.exports !== void 0 && packageConfig2.exports !== null) {
  1228. return packageExportsResolve(
  1229. packageJsonUrl,
  1230. packageSubpath,
  1231. packageConfig2,
  1232. base,
  1233. conditions
  1234. );
  1235. }
  1236. if (packageSubpath === ".") {
  1237. return legacyMainResolve(packageJsonUrl, packageConfig2, base);
  1238. }
  1239. return new URL(packageSubpath, packageJsonUrl);
  1240. } while (packageJsonPath.length !== lastPath.length);
  1241. throw new ERR_MODULE_NOT_FOUND(packageName, (0, import_node_url3.fileURLToPath)(base), false);
  1242. }
  1243. function isRelativeSpecifier(specifier) {
  1244. if (specifier[0] === ".") {
  1245. if (specifier.length === 1 || specifier[1] === "/") return true;
  1246. if (specifier[1] === "." && (specifier.length === 2 || specifier[2] === "/")) {
  1247. return true;
  1248. }
  1249. }
  1250. return false;
  1251. }
  1252. function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
  1253. if (specifier === "") return false;
  1254. if (specifier[0] === "/") return true;
  1255. return isRelativeSpecifier(specifier);
  1256. }
  1257. function moduleResolve(specifier, base, conditions, preserveSymlinks) {
  1258. if (conditions === void 0) {
  1259. conditions = getConditionsSet();
  1260. }
  1261. const protocol = base.protocol;
  1262. const isData = protocol === "data:";
  1263. const isRemote = isData || protocol === "http:" || protocol === "https:";
  1264. let resolved;
  1265. if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
  1266. try {
  1267. resolved = new URL(specifier, base);
  1268. } catch (error_) {
  1269. const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
  1270. error.cause = error_;
  1271. throw error;
  1272. }
  1273. } else if (protocol === "file:" && specifier[0] === "#") {
  1274. resolved = packageImportsResolve(specifier, base, conditions);
  1275. } else {
  1276. try {
  1277. resolved = new URL(specifier);
  1278. } catch (error_) {
  1279. if (isRemote && !import_node_module.builtinModules.includes(specifier)) {
  1280. const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
  1281. error.cause = error_;
  1282. throw error;
  1283. }
  1284. resolved = packageResolve(specifier, base, conditions);
  1285. }
  1286. }
  1287. import_node_assert2.default.ok(resolved !== void 0, "expected to be defined");
  1288. if (resolved.protocol !== "file:") {
  1289. return resolved;
  1290. }
  1291. return finalizeResolution(resolved, base, preserveSymlinks);
  1292. }
  1293. function checkIfDisallowedImport(specifier, parsed, parsedParentURL) {
  1294. if (parsedParentURL) {
  1295. const parentProtocol = parsedParentURL.protocol;
  1296. if (parentProtocol === "http:" || parentProtocol === "https:") {
  1297. if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
  1298. const parsedProtocol = parsed?.protocol;
  1299. if (parsedProtocol && parsedProtocol !== "https:" && parsedProtocol !== "http:") {
  1300. throw new ERR_NETWORK_IMPORT_DISALLOWED(
  1301. specifier,
  1302. parsedParentURL,
  1303. "remote imports cannot import from a local location."
  1304. );
  1305. }
  1306. return { url: parsed?.href || "" };
  1307. }
  1308. if (import_node_module.builtinModules.includes(specifier)) {
  1309. throw new ERR_NETWORK_IMPORT_DISALLOWED(
  1310. specifier,
  1311. parsedParentURL,
  1312. "remote imports cannot import from a local location."
  1313. );
  1314. }
  1315. throw new ERR_NETWORK_IMPORT_DISALLOWED(
  1316. specifier,
  1317. parsedParentURL,
  1318. "only relative and absolute specifiers are supported."
  1319. );
  1320. }
  1321. }
  1322. }
  1323. function isURL(self) {
  1324. return Boolean(
  1325. self && typeof self === "object" && "href" in self && typeof self.href === "string" && "protocol" in self && typeof self.protocol === "string" && self.href && self.protocol
  1326. );
  1327. }
  1328. function throwIfInvalidParentURL(parentURL) {
  1329. if (parentURL === void 0) {
  1330. return;
  1331. }
  1332. if (typeof parentURL !== "string" && !isURL(parentURL)) {
  1333. throw new codes.ERR_INVALID_ARG_TYPE(
  1334. "parentURL",
  1335. ["string", "URL"],
  1336. parentURL
  1337. );
  1338. }
  1339. }
  1340. function defaultResolve(specifier, context = {}) {
  1341. const { parentURL } = context;
  1342. import_node_assert2.default.ok(parentURL !== void 0, "expected `parentURL` to be defined");
  1343. throwIfInvalidParentURL(parentURL);
  1344. let parsedParentURL;
  1345. if (parentURL) {
  1346. try {
  1347. parsedParentURL = new URL(parentURL);
  1348. } catch {
  1349. }
  1350. }
  1351. let parsed;
  1352. let protocol;
  1353. try {
  1354. parsed = shouldBeTreatedAsRelativeOrAbsolutePath(specifier) ? new URL(specifier, parsedParentURL) : new URL(specifier);
  1355. protocol = parsed.protocol;
  1356. if (protocol === "data:") {
  1357. return { url: parsed.href, format: null };
  1358. }
  1359. } catch {
  1360. }
  1361. const maybeReturn = checkIfDisallowedImport(
  1362. specifier,
  1363. parsed,
  1364. parsedParentURL
  1365. );
  1366. if (maybeReturn) return maybeReturn;
  1367. if (protocol === void 0 && parsed) {
  1368. protocol = parsed.protocol;
  1369. }
  1370. if (protocol === "node:") {
  1371. return { url: specifier };
  1372. }
  1373. if (parsed && parsed.protocol === "node:") return { url: specifier };
  1374. const conditions = getConditionsSet(context.conditions);
  1375. const url = moduleResolve(specifier, new URL(parentURL), conditions, false);
  1376. return {
  1377. // Do NOT cast `url` to a string: that will work even when there are real
  1378. // problems, silencing them
  1379. url: url.href,
  1380. format: defaultGetFormatWithoutErrors(url, { parentURL })
  1381. };
  1382. }
  1383. // index.js
  1384. function resolve(specifier, parent) {
  1385. if (!parent) {
  1386. throw new Error(
  1387. "Please pass `parent`: `import-meta-resolve` cannot ponyfill that"
  1388. );
  1389. }
  1390. try {
  1391. return defaultResolve(specifier, { parentURL: parent }).url;
  1392. } catch (error) {
  1393. const exception = (
  1394. /** @type {ErrnoException} */
  1395. error
  1396. );
  1397. if ((exception.code === "ERR_UNSUPPORTED_DIR_IMPORT" || exception.code === "ERR_MODULE_NOT_FOUND") && typeof exception.url === "string") {
  1398. return exception.url;
  1399. }
  1400. throw error;
  1401. }
  1402. }
  1403. // Annotate the CommonJS export names for ESM import in node:
  1404. 0 && (module.exports = {
  1405. moduleResolve,
  1406. resolve
  1407. });