index.mjs 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708
  1. import { tokenizer } from 'acorn';
  2. import { builtinModules, createRequire } from 'node:module';
  3. import fs, { realpathSync, statSync, promises } from 'node:fs';
  4. import { joinURL } from 'ufo';
  5. import { normalize, isAbsolute, extname as extname$1 } from 'pathe';
  6. import { readPackageJSON } from 'pkg-types';
  7. import { fileURLToPath as fileURLToPath$1, pathToFileURL as pathToFileURL$1 } from 'node:url';
  8. import assert from 'node:assert';
  9. import process$1 from 'node:process';
  10. import path, { dirname } from 'node:path';
  11. import v8 from 'node:v8';
  12. import { format, inspect } from 'node:util';
  13. const BUILTIN_MODULES = new Set(builtinModules);
  14. function normalizeSlash(path) {
  15. return path.replace(/\\/g, "/");
  16. }
  17. function isObject(value) {
  18. return value !== null && typeof value === "object";
  19. }
  20. function matchAll(regex, string, addition) {
  21. const matches = [];
  22. for (const match of string.matchAll(regex)) {
  23. matches.push({
  24. ...addition,
  25. ...match.groups,
  26. code: match[0],
  27. start: match.index,
  28. end: (match.index || 0) + match[0].length
  29. });
  30. }
  31. return matches;
  32. }
  33. function clearImports(imports) {
  34. return (imports || "").replace(/\/\/[^\n]*\n|\/\*.*\*\//g, "").replace(/\s+/g, " ");
  35. }
  36. function getImportNames(cleanedImports) {
  37. const topLevelImports = cleanedImports.replace(/{[^}]*}/, "");
  38. const namespacedImport = topLevelImports.match(/\* as \s*(\S*)/)?.[1];
  39. const defaultImport = topLevelImports.split(",").find((index) => !/[*{}]/.test(index))?.trim() || void 0;
  40. return {
  41. namespacedImport,
  42. defaultImport
  43. };
  44. }
  45. /**
  46. * @typedef ErrnoExceptionFields
  47. * @property {number | undefined} [errnode]
  48. * @property {string | undefined} [code]
  49. * @property {string | undefined} [path]
  50. * @property {string | undefined} [syscall]
  51. * @property {string | undefined} [url]
  52. *
  53. * @typedef {Error & ErrnoExceptionFields} ErrnoException
  54. */
  55. const own$1 = {}.hasOwnProperty;
  56. const classRegExp = /^([A-Z][a-z\d]*)+$/;
  57. // Sorted by a rough estimate on most frequently used entries.
  58. const kTypes = new Set([
  59. 'string',
  60. 'function',
  61. 'number',
  62. 'object',
  63. // Accept 'Function' and 'Object' as alternative to the lower cased version.
  64. 'Function',
  65. 'Object',
  66. 'boolean',
  67. 'bigint',
  68. 'symbol'
  69. ]);
  70. const codes = {};
  71. /**
  72. * Create a list string in the form like 'A and B' or 'A, B, ..., and Z'.
  73. * We cannot use Intl.ListFormat because it's not available in
  74. * --without-intl builds.
  75. *
  76. * @param {Array<string>} array
  77. * An array of strings.
  78. * @param {string} [type]
  79. * The list type to be inserted before the last element.
  80. * @returns {string}
  81. */
  82. function formatList(array, type = 'and') {
  83. return array.length < 3
  84. ? array.join(` ${type} `)
  85. : `${array.slice(0, -1).join(', ')}, ${type} ${array[array.length - 1]}`
  86. }
  87. /** @type {Map<string, MessageFunction | string>} */
  88. const messages = new Map();
  89. const nodeInternalPrefix = '__node_internal_';
  90. /** @type {number} */
  91. let userStackTraceLimit;
  92. codes.ERR_INVALID_ARG_TYPE = createError(
  93. 'ERR_INVALID_ARG_TYPE',
  94. /**
  95. * @param {string} name
  96. * @param {Array<string> | string} expected
  97. * @param {unknown} actual
  98. */
  99. (name, expected, actual) => {
  100. assert.ok(typeof name === 'string', "'name' must be a string");
  101. if (!Array.isArray(expected)) {
  102. expected = [expected];
  103. }
  104. let message = 'The ';
  105. if (name.endsWith(' argument')) {
  106. // For cases like 'first argument'
  107. message += `${name} `;
  108. } else {
  109. const type = name.includes('.') ? 'property' : 'argument';
  110. message += `"${name}" ${type} `;
  111. }
  112. message += 'must be ';
  113. /** @type {Array<string>} */
  114. const types = [];
  115. /** @type {Array<string>} */
  116. const instances = [];
  117. /** @type {Array<string>} */
  118. const other = [];
  119. for (const value of expected) {
  120. assert.ok(
  121. typeof value === 'string',
  122. 'All expected entries have to be of type string'
  123. );
  124. if (kTypes.has(value)) {
  125. types.push(value.toLowerCase());
  126. } else if (classRegExp.exec(value) === null) {
  127. assert.ok(
  128. value !== 'object',
  129. 'The value "object" should be written as "Object"'
  130. );
  131. other.push(value);
  132. } else {
  133. instances.push(value);
  134. }
  135. }
  136. // Special handle `object` in case other instances are allowed to outline
  137. // the differences between each other.
  138. if (instances.length > 0) {
  139. const pos = types.indexOf('object');
  140. if (pos !== -1) {
  141. types.slice(pos, 1);
  142. instances.push('Object');
  143. }
  144. }
  145. if (types.length > 0) {
  146. message += `${types.length > 1 ? 'one of type' : 'of type'} ${formatList(
  147. types,
  148. 'or'
  149. )}`;
  150. if (instances.length > 0 || other.length > 0) message += ' or ';
  151. }
  152. if (instances.length > 0) {
  153. message += `an instance of ${formatList(instances, 'or')}`;
  154. if (other.length > 0) message += ' or ';
  155. }
  156. if (other.length > 0) {
  157. if (other.length > 1) {
  158. message += `one of ${formatList(other, 'or')}`;
  159. } else {
  160. if (other[0].toLowerCase() !== other[0]) message += 'an ';
  161. message += `${other[0]}`;
  162. }
  163. }
  164. message += `. Received ${determineSpecificType(actual)}`;
  165. return message
  166. },
  167. TypeError
  168. );
  169. codes.ERR_INVALID_MODULE_SPECIFIER = createError(
  170. 'ERR_INVALID_MODULE_SPECIFIER',
  171. /**
  172. * @param {string} request
  173. * @param {string} reason
  174. * @param {string} [base]
  175. */
  176. (request, reason, base = undefined) => {
  177. return `Invalid module "${request}" ${reason}${
  178. base ? ` imported from ${base}` : ''
  179. }`
  180. },
  181. TypeError
  182. );
  183. codes.ERR_INVALID_PACKAGE_CONFIG = createError(
  184. 'ERR_INVALID_PACKAGE_CONFIG',
  185. /**
  186. * @param {string} path
  187. * @param {string} [base]
  188. * @param {string} [message]
  189. */
  190. (path, base, message) => {
  191. return `Invalid package config ${path}${
  192. base ? ` while importing ${base}` : ''
  193. }${message ? `. ${message}` : ''}`
  194. },
  195. Error
  196. );
  197. codes.ERR_INVALID_PACKAGE_TARGET = createError(
  198. 'ERR_INVALID_PACKAGE_TARGET',
  199. /**
  200. * @param {string} packagePath
  201. * @param {string} key
  202. * @param {unknown} target
  203. * @param {boolean} [isImport=false]
  204. * @param {string} [base]
  205. */
  206. (packagePath, key, target, isImport = false, base = undefined) => {
  207. const relatedError =
  208. typeof target === 'string' &&
  209. !isImport &&
  210. target.length > 0 &&
  211. !target.startsWith('./');
  212. if (key === '.') {
  213. assert.ok(isImport === false);
  214. return (
  215. `Invalid "exports" main target ${JSON.stringify(target)} defined ` +
  216. `in the package config ${packagePath}package.json${
  217. base ? ` imported from ${base}` : ''
  218. }${relatedError ? '; targets must start with "./"' : ''}`
  219. )
  220. }
  221. return `Invalid "${
  222. isImport ? 'imports' : 'exports'
  223. }" target ${JSON.stringify(
  224. target
  225. )} defined for '${key}' in the package config ${packagePath}package.json${
  226. base ? ` imported from ${base}` : ''
  227. }${relatedError ? '; targets must start with "./"' : ''}`
  228. },
  229. Error
  230. );
  231. codes.ERR_MODULE_NOT_FOUND = createError(
  232. 'ERR_MODULE_NOT_FOUND',
  233. /**
  234. * @param {string} path
  235. * @param {string} base
  236. * @param {boolean} [exactUrl]
  237. */
  238. (path, base, exactUrl = false) => {
  239. return `Cannot find ${
  240. exactUrl ? 'module' : 'package'
  241. } '${path}' imported from ${base}`
  242. },
  243. Error
  244. );
  245. codes.ERR_NETWORK_IMPORT_DISALLOWED = createError(
  246. 'ERR_NETWORK_IMPORT_DISALLOWED',
  247. "import of '%s' by %s is not supported: %s",
  248. Error
  249. );
  250. codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
  251. 'ERR_PACKAGE_IMPORT_NOT_DEFINED',
  252. /**
  253. * @param {string} specifier
  254. * @param {string} packagePath
  255. * @param {string} base
  256. */
  257. (specifier, packagePath, base) => {
  258. return `Package import specifier "${specifier}" is not defined${
  259. packagePath ? ` in package ${packagePath}package.json` : ''
  260. } imported from ${base}`
  261. },
  262. TypeError
  263. );
  264. codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
  265. 'ERR_PACKAGE_PATH_NOT_EXPORTED',
  266. /**
  267. * @param {string} packagePath
  268. * @param {string} subpath
  269. * @param {string} [base]
  270. */
  271. (packagePath, subpath, base = undefined) => {
  272. if (subpath === '.')
  273. return `No "exports" main defined in ${packagePath}package.json${
  274. base ? ` imported from ${base}` : ''
  275. }`
  276. return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${
  277. base ? ` imported from ${base}` : ''
  278. }`
  279. },
  280. Error
  281. );
  282. codes.ERR_UNSUPPORTED_DIR_IMPORT = createError(
  283. 'ERR_UNSUPPORTED_DIR_IMPORT',
  284. "Directory import '%s' is not supported " +
  285. 'resolving ES modules imported from %s',
  286. Error
  287. );
  288. codes.ERR_UNSUPPORTED_RESOLVE_REQUEST = createError(
  289. 'ERR_UNSUPPORTED_RESOLVE_REQUEST',
  290. 'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.',
  291. TypeError
  292. );
  293. codes.ERR_UNKNOWN_FILE_EXTENSION = createError(
  294. 'ERR_UNKNOWN_FILE_EXTENSION',
  295. /**
  296. * @param {string} extension
  297. * @param {string} path
  298. */
  299. (extension, path) => {
  300. return `Unknown file extension "${extension}" for ${path}`
  301. },
  302. TypeError
  303. );
  304. codes.ERR_INVALID_ARG_VALUE = createError(
  305. 'ERR_INVALID_ARG_VALUE',
  306. /**
  307. * @param {string} name
  308. * @param {unknown} value
  309. * @param {string} [reason='is invalid']
  310. */
  311. (name, value, reason = 'is invalid') => {
  312. let inspected = inspect(value);
  313. if (inspected.length > 128) {
  314. inspected = `${inspected.slice(0, 128)}...`;
  315. }
  316. const type = name.includes('.') ? 'property' : 'argument';
  317. return `The ${type} '${name}' ${reason}. Received ${inspected}`
  318. },
  319. TypeError
  320. // Note: extra classes have been shaken out.
  321. // , RangeError
  322. );
  323. /**
  324. * Utility function for registering the error codes. Only used here. Exported
  325. * *only* to allow for testing.
  326. * @param {string} sym
  327. * @param {MessageFunction | string} value
  328. * @param {ErrorConstructor} constructor
  329. * @returns {new (...parameters: Array<any>) => Error}
  330. */
  331. function createError(sym, value, constructor) {
  332. // Special case for SystemError that formats the error message differently
  333. // The SystemErrors only have SystemError as their base classes.
  334. messages.set(sym, value);
  335. return makeNodeErrorWithCode(constructor, sym)
  336. }
  337. /**
  338. * @param {ErrorConstructor} Base
  339. * @param {string} key
  340. * @returns {ErrorConstructor}
  341. */
  342. function makeNodeErrorWithCode(Base, key) {
  343. // @ts-expect-error It’s a Node error.
  344. return NodeError
  345. /**
  346. * @param {Array<unknown>} parameters
  347. */
  348. function NodeError(...parameters) {
  349. const limit = Error.stackTraceLimit;
  350. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
  351. const error = new Base();
  352. // Reset the limit and setting the name property.
  353. if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
  354. const message = getMessage(key, parameters, error);
  355. Object.defineProperties(error, {
  356. // Note: no need to implement `kIsNodeError` symbol, would be hard,
  357. // probably.
  358. message: {
  359. value: message,
  360. enumerable: false,
  361. writable: true,
  362. configurable: true
  363. },
  364. toString: {
  365. /** @this {Error} */
  366. value() {
  367. return `${this.name} [${key}]: ${this.message}`
  368. },
  369. enumerable: false,
  370. writable: true,
  371. configurable: true
  372. }
  373. });
  374. captureLargerStackTrace(error);
  375. // @ts-expect-error It’s a Node error.
  376. error.code = key;
  377. return error
  378. }
  379. }
  380. /**
  381. * @returns {boolean}
  382. */
  383. function isErrorStackTraceLimitWritable() {
  384. // Do no touch Error.stackTraceLimit as V8 would attempt to install
  385. // it again during deserialization.
  386. try {
  387. if (v8.startupSnapshot.isBuildingSnapshot()) {
  388. return false
  389. }
  390. } catch {}
  391. const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
  392. if (desc === undefined) {
  393. return Object.isExtensible(Error)
  394. }
  395. return own$1.call(desc, 'writable') && desc.writable !== undefined
  396. ? desc.writable
  397. : desc.set !== undefined
  398. }
  399. /**
  400. * This function removes unnecessary frames from Node.js core errors.
  401. * @template {(...parameters: unknown[]) => unknown} T
  402. * @param {T} wrappedFunction
  403. * @returns {T}
  404. */
  405. function hideStackFrames(wrappedFunction) {
  406. // We rename the functions that will be hidden to cut off the stacktrace
  407. // at the outermost one
  408. const hidden = nodeInternalPrefix + wrappedFunction.name;
  409. Object.defineProperty(wrappedFunction, 'name', {value: hidden});
  410. return wrappedFunction
  411. }
  412. const captureLargerStackTrace = hideStackFrames(
  413. /**
  414. * @param {Error} error
  415. * @returns {Error}
  416. */
  417. // @ts-expect-error: fine
  418. function (error) {
  419. const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
  420. if (stackTraceLimitIsWritable) {
  421. userStackTraceLimit = Error.stackTraceLimit;
  422. Error.stackTraceLimit = Number.POSITIVE_INFINITY;
  423. }
  424. Error.captureStackTrace(error);
  425. // Reset the limit
  426. if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
  427. return error
  428. }
  429. );
  430. /**
  431. * @param {string} key
  432. * @param {Array<unknown>} parameters
  433. * @param {Error} self
  434. * @returns {string}
  435. */
  436. function getMessage(key, parameters, self) {
  437. const message = messages.get(key);
  438. assert.ok(message !== undefined, 'expected `message` to be found');
  439. if (typeof message === 'function') {
  440. assert.ok(
  441. message.length <= parameters.length, // Default options do not count.
  442. `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
  443. `match the required ones (${message.length}).`
  444. );
  445. return Reflect.apply(message, self, parameters)
  446. }
  447. const regex = /%[dfijoOs]/g;
  448. let expectedLength = 0;
  449. while (regex.exec(message) !== null) expectedLength++;
  450. assert.ok(
  451. expectedLength === parameters.length,
  452. `Code: ${key}; The provided arguments length (${parameters.length}) does not ` +
  453. `match the required ones (${expectedLength}).`
  454. );
  455. if (parameters.length === 0) return message
  456. parameters.unshift(message);
  457. return Reflect.apply(format, null, parameters)
  458. }
  459. /**
  460. * Determine the specific type of a value for type-mismatch errors.
  461. * @param {unknown} value
  462. * @returns {string}
  463. */
  464. function determineSpecificType(value) {
  465. if (value === null || value === undefined) {
  466. return String(value)
  467. }
  468. if (typeof value === 'function' && value.name) {
  469. return `function ${value.name}`
  470. }
  471. if (typeof value === 'object') {
  472. if (value.constructor && value.constructor.name) {
  473. return `an instance of ${value.constructor.name}`
  474. }
  475. return `${inspect(value, {depth: -1})}`
  476. }
  477. let inspected = inspect(value, {colors: false});
  478. if (inspected.length > 28) {
  479. inspected = `${inspected.slice(0, 25)}...`;
  480. }
  481. return `type ${typeof value} (${inspected})`
  482. }
  483. // Manually “tree shaken” from:
  484. // <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/package_json_reader.js>
  485. // Last checked on: Apr 29, 2024.
  486. // Removed the native dependency.
  487. // Also: no need to cache, we do that in resolve already.
  488. const hasOwnProperty$1 = {}.hasOwnProperty;
  489. const {ERR_INVALID_PACKAGE_CONFIG: ERR_INVALID_PACKAGE_CONFIG$1} = codes;
  490. /** @type {Map<string, PackageConfig>} */
  491. const cache = new Map();
  492. /**
  493. * @param {string} jsonPath
  494. * @param {{specifier: URL | string, base?: URL}} options
  495. * @returns {PackageConfig}
  496. */
  497. function read(jsonPath, {base, specifier}) {
  498. const existing = cache.get(jsonPath);
  499. if (existing) {
  500. return existing
  501. }
  502. /** @type {string | undefined} */
  503. let string;
  504. try {
  505. string = fs.readFileSync(path.toNamespacedPath(jsonPath), 'utf8');
  506. } catch (error) {
  507. const exception = /** @type {ErrnoException} */ (error);
  508. if (exception.code !== 'ENOENT') {
  509. throw exception
  510. }
  511. }
  512. /** @type {PackageConfig} */
  513. const result = {
  514. exists: false,
  515. pjsonPath: jsonPath,
  516. main: undefined,
  517. name: undefined,
  518. type: 'none', // Ignore unknown types for forwards compatibility
  519. exports: undefined,
  520. imports: undefined
  521. };
  522. if (string !== undefined) {
  523. /** @type {Record<string, unknown>} */
  524. let parsed;
  525. try {
  526. parsed = JSON.parse(string);
  527. } catch (error_) {
  528. const cause = /** @type {ErrnoException} */ (error_);
  529. const error = new ERR_INVALID_PACKAGE_CONFIG$1(
  530. jsonPath,
  531. (base ? `"${specifier}" from ` : '') + fileURLToPath$1(base || specifier),
  532. cause.message
  533. );
  534. error.cause = cause;
  535. throw error
  536. }
  537. result.exists = true;
  538. if (
  539. hasOwnProperty$1.call(parsed, 'name') &&
  540. typeof parsed.name === 'string'
  541. ) {
  542. result.name = parsed.name;
  543. }
  544. if (
  545. hasOwnProperty$1.call(parsed, 'main') &&
  546. typeof parsed.main === 'string'
  547. ) {
  548. result.main = parsed.main;
  549. }
  550. if (hasOwnProperty$1.call(parsed, 'exports')) {
  551. // @ts-expect-error: assume valid.
  552. result.exports = parsed.exports;
  553. }
  554. if (hasOwnProperty$1.call(parsed, 'imports')) {
  555. // @ts-expect-error: assume valid.
  556. result.imports = parsed.imports;
  557. }
  558. // Ignore unknown types for forwards compatibility
  559. if (
  560. hasOwnProperty$1.call(parsed, 'type') &&
  561. (parsed.type === 'commonjs' || parsed.type === 'module')
  562. ) {
  563. result.type = parsed.type;
  564. }
  565. }
  566. cache.set(jsonPath, result);
  567. return result
  568. }
  569. /**
  570. * @param {URL | string} resolved
  571. * @returns {PackageConfig}
  572. */
  573. function getPackageScopeConfig(resolved) {
  574. // Note: in Node, this is now a native module.
  575. let packageJSONUrl = new URL('package.json', resolved);
  576. while (true) {
  577. const packageJSONPath = packageJSONUrl.pathname;
  578. if (packageJSONPath.endsWith('node_modules/package.json')) {
  579. break
  580. }
  581. const packageConfig = read(fileURLToPath$1(packageJSONUrl), {
  582. specifier: resolved
  583. });
  584. if (packageConfig.exists) {
  585. return packageConfig
  586. }
  587. const lastPackageJSONUrl = packageJSONUrl;
  588. packageJSONUrl = new URL('../package.json', packageJSONUrl);
  589. // Terminates at root where ../package.json equals ../../package.json
  590. // (can't just check "/package.json" for Windows support).
  591. if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) {
  592. break
  593. }
  594. }
  595. const packageJSONPath = fileURLToPath$1(packageJSONUrl);
  596. // ^^ Note: in Node, this is now a native module.
  597. return {
  598. pjsonPath: packageJSONPath,
  599. exists: false,
  600. type: 'none'
  601. }
  602. }
  603. /**
  604. * Returns the package type for a given URL.
  605. * @param {URL} url - The URL to get the package type for.
  606. * @returns {PackageType}
  607. */
  608. function getPackageType(url) {
  609. // To do @anonrig: Write a C++ function that returns only "type".
  610. return getPackageScopeConfig(url).type
  611. }
  612. // Manually “tree shaken” from:
  613. // <https://github.com/nodejs/node/blob/7c3dce0/lib/internal/modules/esm/get_format.js>
  614. // Last checked on: Apr 29, 2024.
  615. const {ERR_UNKNOWN_FILE_EXTENSION} = codes;
  616. const hasOwnProperty = {}.hasOwnProperty;
  617. /** @type {Record<string, string>} */
  618. const extensionFormatMap = {
  619. // @ts-expect-error: hush.
  620. __proto__: null,
  621. '.cjs': 'commonjs',
  622. '.js': 'module',
  623. '.json': 'json',
  624. '.mjs': 'module'
  625. };
  626. /**
  627. * @param {string | null} mime
  628. * @returns {string | null}
  629. */
  630. function mimeToFormat(mime) {
  631. if (
  632. mime &&
  633. /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i.test(mime)
  634. )
  635. return 'module'
  636. if (mime === 'application/json') return 'json'
  637. return null
  638. }
  639. /**
  640. * @callback ProtocolHandler
  641. * @param {URL} parsed
  642. * @param {{parentURL: string, source?: Buffer}} context
  643. * @param {boolean} ignoreErrors
  644. * @returns {string | null | void}
  645. */
  646. /**
  647. * @type {Record<string, ProtocolHandler>}
  648. */
  649. const protocolHandlers = {
  650. // @ts-expect-error: hush.
  651. __proto__: null,
  652. 'data:': getDataProtocolModuleFormat,
  653. 'file:': getFileProtocolModuleFormat,
  654. 'http:': getHttpProtocolModuleFormat,
  655. 'https:': getHttpProtocolModuleFormat,
  656. 'node:'() {
  657. return 'builtin'
  658. }
  659. };
  660. /**
  661. * @param {URL} parsed
  662. */
  663. function getDataProtocolModuleFormat(parsed) {
  664. const {1: mime} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(
  665. parsed.pathname
  666. ) || [null, null, null];
  667. return mimeToFormat(mime)
  668. }
  669. /**
  670. * Returns the file extension from a URL.
  671. *
  672. * Should give similar result to
  673. * `require('node:path').extname(require('node:url').fileURLToPath(url))`
  674. * when used with a `file:` URL.
  675. *
  676. * @param {URL} url
  677. * @returns {string}
  678. */
  679. function extname(url) {
  680. const pathname = url.pathname;
  681. let index = pathname.length;
  682. while (index--) {
  683. const code = pathname.codePointAt(index);
  684. if (code === 47 /* `/` */) {
  685. return ''
  686. }
  687. if (code === 46 /* `.` */) {
  688. return pathname.codePointAt(index - 1) === 47 /* `/` */
  689. ? ''
  690. : pathname.slice(index)
  691. }
  692. }
  693. return ''
  694. }
  695. /**
  696. * @type {ProtocolHandler}
  697. */
  698. function getFileProtocolModuleFormat(url, _context, ignoreErrors) {
  699. const value = extname(url);
  700. if (value === '.js') {
  701. const packageType = getPackageType(url);
  702. if (packageType !== 'none') {
  703. return packageType
  704. }
  705. return 'commonjs'
  706. }
  707. if (value === '') {
  708. const packageType = getPackageType(url);
  709. // Legacy behavior
  710. if (packageType === 'none' || packageType === 'commonjs') {
  711. return 'commonjs'
  712. }
  713. // Note: we don’t implement WASM, so we don’t need
  714. // `getFormatOfExtensionlessFile` from `formats`.
  715. return 'module'
  716. }
  717. const format = extensionFormatMap[value];
  718. if (format) return format
  719. // Explicit undefined return indicates load hook should rerun format check
  720. if (ignoreErrors) {
  721. return undefined
  722. }
  723. const filepath = fileURLToPath$1(url);
  724. throw new ERR_UNKNOWN_FILE_EXTENSION(value, filepath)
  725. }
  726. function getHttpProtocolModuleFormat() {
  727. // To do: HTTPS imports.
  728. }
  729. /**
  730. * @param {URL} url
  731. * @param {{parentURL: string}} context
  732. * @returns {string | null}
  733. */
  734. function defaultGetFormatWithoutErrors(url, context) {
  735. const protocol = url.protocol;
  736. if (!hasOwnProperty.call(protocolHandlers, protocol)) {
  737. return null
  738. }
  739. return protocolHandlers[protocol](url, context, true) || null
  740. }
  741. // Manually “tree shaken” from:
  742. // <https://github.com/nodejs/node/blob/81a9a97/lib/internal/modules/esm/utils.js>
  743. // Last checked on: Apr 29, 2024.
  744. // In Node itself these values are populated from CLI arguments, before any
  745. // user code runs.
  746. // Here we just define the defaults.
  747. const DEFAULT_CONDITIONS = Object.freeze(['node', 'import']);
  748. const DEFAULT_CONDITIONS_SET$1 = new Set(DEFAULT_CONDITIONS);
  749. /**
  750. * Returns the default conditions for ES module loading, as a Set.
  751. */
  752. function getDefaultConditionsSet() {
  753. return DEFAULT_CONDITIONS_SET$1
  754. }
  755. /**
  756. * @param {Array<string>} [conditions]
  757. * @returns {Set<string>}
  758. */
  759. function getConditionsSet(conditions) {
  760. return getDefaultConditionsSet()
  761. }
  762. // Manually “tree shaken” from:
  763. // <https://github.com/nodejs/node/blob/81a9a97/lib/internal/modules/esm/resolve.js>
  764. // Last checked on: Apr 29, 2024.
  765. const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
  766. const {
  767. ERR_INVALID_MODULE_SPECIFIER,
  768. ERR_INVALID_PACKAGE_CONFIG,
  769. ERR_INVALID_PACKAGE_TARGET,
  770. ERR_MODULE_NOT_FOUND,
  771. ERR_PACKAGE_IMPORT_NOT_DEFINED,
  772. ERR_PACKAGE_PATH_NOT_EXPORTED,
  773. ERR_UNSUPPORTED_DIR_IMPORT,
  774. ERR_UNSUPPORTED_RESOLVE_REQUEST
  775. } = codes;
  776. const own = {}.hasOwnProperty;
  777. const invalidSegmentRegEx =
  778. /(^|\\|\/)((\.|%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;
  779. const deprecatedInvalidSegmentRegEx =
  780. /(^|\\|\/)((\.|%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;
  781. const invalidPackageNameRegEx = /^\.|%|\\/;
  782. const patternRegEx = /\*/g;
  783. const encodedSeparatorRegEx = /%2f|%5c/i;
  784. /** @type {Set<string>} */
  785. const emittedPackageWarnings = new Set();
  786. const doubleSlashRegEx = /[/\\]{2}/;
  787. /**
  788. *
  789. * @param {string} target
  790. * @param {string} request
  791. * @param {string} match
  792. * @param {URL} packageJsonUrl
  793. * @param {boolean} internal
  794. * @param {URL} base
  795. * @param {boolean} isTarget
  796. */
  797. function emitInvalidSegmentDeprecation(
  798. target,
  799. request,
  800. match,
  801. packageJsonUrl,
  802. internal,
  803. base,
  804. isTarget
  805. ) {
  806. // @ts-expect-error: apparently it does exist, TS.
  807. if (process$1.noDeprecation) {
  808. return
  809. }
  810. const pjsonPath = fileURLToPath$1(packageJsonUrl);
  811. const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
  812. process$1.emitWarning(
  813. `Use of deprecated ${
  814. double ? 'double slash' : 'leading or trailing slash matching'
  815. } resolving "${target}" for module ` +
  816. `request "${request}" ${
  817. request === match ? '' : `matched to "${match}" `
  818. }in the "${
  819. internal ? 'imports' : 'exports'
  820. }" field module resolution of the package at ${pjsonPath}${
  821. base ? ` imported from ${fileURLToPath$1(base)}` : ''
  822. }.`,
  823. 'DeprecationWarning',
  824. 'DEP0166'
  825. );
  826. }
  827. /**
  828. * @param {URL} url
  829. * @param {URL} packageJsonUrl
  830. * @param {URL} base
  831. * @param {string} [main]
  832. * @returns {void}
  833. */
  834. function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
  835. // @ts-expect-error: apparently it does exist, TS.
  836. if (process$1.noDeprecation) {
  837. return
  838. }
  839. const format = defaultGetFormatWithoutErrors(url, {parentURL: base.href});
  840. if (format !== 'module') return
  841. const urlPath = fileURLToPath$1(url.href);
  842. const packagePath = fileURLToPath$1(new URL('.', packageJsonUrl));
  843. const basePath = fileURLToPath$1(base);
  844. if (!main) {
  845. process$1.emitWarning(
  846. `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
  847. packagePath.length
  848. )}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`,
  849. 'DeprecationWarning',
  850. 'DEP0151'
  851. );
  852. } else if (path.resolve(packagePath, main) !== urlPath) {
  853. process$1.emitWarning(
  854. `Package ${packagePath} has a "main" field set to "${main}", ` +
  855. `excluding the full filename and extension to the resolved file at "${urlPath.slice(
  856. packagePath.length
  857. )}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is ` +
  858. 'deprecated for ES modules.',
  859. 'DeprecationWarning',
  860. 'DEP0151'
  861. );
  862. }
  863. }
  864. /**
  865. * @param {string} path
  866. * @returns {Stats | undefined}
  867. */
  868. function tryStatSync(path) {
  869. // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.
  870. try {
  871. return statSync(path)
  872. } catch {
  873. // Note: in Node code this returns `new Stats`,
  874. // but in Node 22 that’s marked as a deprecated internal API.
  875. // Which, well, we kinda are, but still to prevent that warning,
  876. // just yield `undefined`.
  877. }
  878. }
  879. /**
  880. * Legacy CommonJS main resolution:
  881. * 1. let M = pkg_url + (json main field)
  882. * 2. TRY(M, M.js, M.json, M.node)
  883. * 3. TRY(M/index.js, M/index.json, M/index.node)
  884. * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
  885. * 5. NOT_FOUND
  886. *
  887. * @param {URL} url
  888. * @returns {boolean}
  889. */
  890. function fileExists(url) {
  891. const stats = statSync(url, {throwIfNoEntry: false});
  892. const isFile = stats ? stats.isFile() : undefined;
  893. return isFile === null || isFile === undefined ? false : isFile
  894. }
  895. /**
  896. * @param {URL} packageJsonUrl
  897. * @param {PackageConfig} packageConfig
  898. * @param {URL} base
  899. * @returns {URL}
  900. */
  901. function legacyMainResolve(packageJsonUrl, packageConfig, base) {
  902. /** @type {URL | undefined} */
  903. let guess;
  904. if (packageConfig.main !== undefined) {
  905. guess = new URL(packageConfig.main, packageJsonUrl);
  906. // Note: fs check redundances will be handled by Descriptor cache here.
  907. if (fileExists(guess)) return guess
  908. const tries = [
  909. `./${packageConfig.main}.js`,
  910. `./${packageConfig.main}.json`,
  911. `./${packageConfig.main}.node`,
  912. `./${packageConfig.main}/index.js`,
  913. `./${packageConfig.main}/index.json`,
  914. `./${packageConfig.main}/index.node`
  915. ];
  916. let i = -1;
  917. while (++i < tries.length) {
  918. guess = new URL(tries[i], packageJsonUrl);
  919. if (fileExists(guess)) break
  920. guess = undefined;
  921. }
  922. if (guess) {
  923. emitLegacyIndexDeprecation(
  924. guess,
  925. packageJsonUrl,
  926. base,
  927. packageConfig.main
  928. );
  929. return guess
  930. }
  931. // Fallthrough.
  932. }
  933. const tries = ['./index.js', './index.json', './index.node'];
  934. let i = -1;
  935. while (++i < tries.length) {
  936. guess = new URL(tries[i], packageJsonUrl);
  937. if (fileExists(guess)) break
  938. guess = undefined;
  939. }
  940. if (guess) {
  941. emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
  942. return guess
  943. }
  944. // Not found.
  945. throw new ERR_MODULE_NOT_FOUND(
  946. fileURLToPath$1(new URL('.', packageJsonUrl)),
  947. fileURLToPath$1(base)
  948. )
  949. }
  950. /**
  951. * @param {URL} resolved
  952. * @param {URL} base
  953. * @param {boolean} [preserveSymlinks]
  954. * @returns {URL}
  955. */
  956. function finalizeResolution(resolved, base, preserveSymlinks) {
  957. if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
  958. throw new ERR_INVALID_MODULE_SPECIFIER(
  959. resolved.pathname,
  960. 'must not include encoded "/" or "\\" characters',
  961. fileURLToPath$1(base)
  962. )
  963. }
  964. /** @type {string} */
  965. let filePath;
  966. try {
  967. filePath = fileURLToPath$1(resolved);
  968. } catch (error) {
  969. const cause = /** @type {ErrnoException} */ (error);
  970. Object.defineProperty(cause, 'input', {value: String(resolved)});
  971. Object.defineProperty(cause, 'module', {value: String(base)});
  972. throw cause
  973. }
  974. const stats = tryStatSync(
  975. filePath.endsWith('/') ? filePath.slice(-1) : filePath
  976. );
  977. if (stats && stats.isDirectory()) {
  978. const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
  979. // @ts-expect-error Add this for `import.meta.resolve`.
  980. error.url = String(resolved);
  981. throw error
  982. }
  983. if (!stats || !stats.isFile()) {
  984. const error = new ERR_MODULE_NOT_FOUND(
  985. filePath || resolved.pathname,
  986. base && fileURLToPath$1(base),
  987. true
  988. );
  989. // @ts-expect-error Add this for `import.meta.resolve`.
  990. error.url = String(resolved);
  991. throw error
  992. }
  993. {
  994. const real = realpathSync(filePath);
  995. const {search, hash} = resolved;
  996. resolved = pathToFileURL$1(real + (filePath.endsWith(path.sep) ? '/' : ''));
  997. resolved.search = search;
  998. resolved.hash = hash;
  999. }
  1000. return resolved
  1001. }
  1002. /**
  1003. * @param {string} specifier
  1004. * @param {URL | undefined} packageJsonUrl
  1005. * @param {URL} base
  1006. * @returns {Error}
  1007. */
  1008. function importNotDefined(specifier, packageJsonUrl, base) {
  1009. return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
  1010. specifier,
  1011. packageJsonUrl && fileURLToPath$1(new URL('.', packageJsonUrl)),
  1012. fileURLToPath$1(base)
  1013. )
  1014. }
  1015. /**
  1016. * @param {string} subpath
  1017. * @param {URL} packageJsonUrl
  1018. * @param {URL} base
  1019. * @returns {Error}
  1020. */
  1021. function exportsNotFound(subpath, packageJsonUrl, base) {
  1022. return new ERR_PACKAGE_PATH_NOT_EXPORTED(
  1023. fileURLToPath$1(new URL('.', packageJsonUrl)),
  1024. subpath,
  1025. base && fileURLToPath$1(base)
  1026. )
  1027. }
  1028. /**
  1029. * @param {string} request
  1030. * @param {string} match
  1031. * @param {URL} packageJsonUrl
  1032. * @param {boolean} internal
  1033. * @param {URL} [base]
  1034. * @returns {never}
  1035. */
  1036. function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
  1037. const reason = `request is not a valid match in pattern "${match}" for the "${
  1038. internal ? 'imports' : 'exports'
  1039. }" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
  1040. throw new ERR_INVALID_MODULE_SPECIFIER(
  1041. request,
  1042. reason,
  1043. base && fileURLToPath$1(base)
  1044. )
  1045. }
  1046. /**
  1047. * @param {string} subpath
  1048. * @param {unknown} target
  1049. * @param {URL} packageJsonUrl
  1050. * @param {boolean} internal
  1051. * @param {URL} [base]
  1052. * @returns {Error}
  1053. */
  1054. function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
  1055. target =
  1056. typeof target === 'object' && target !== null
  1057. ? JSON.stringify(target, null, '')
  1058. : `${target}`;
  1059. return new ERR_INVALID_PACKAGE_TARGET(
  1060. fileURLToPath$1(new URL('.', packageJsonUrl)),
  1061. subpath,
  1062. target,
  1063. internal,
  1064. base && fileURLToPath$1(base)
  1065. )
  1066. }
  1067. /**
  1068. * @param {string} target
  1069. * @param {string} subpath
  1070. * @param {string} match
  1071. * @param {URL} packageJsonUrl
  1072. * @param {URL} base
  1073. * @param {boolean} pattern
  1074. * @param {boolean} internal
  1075. * @param {boolean} isPathMap
  1076. * @param {Set<string> | undefined} conditions
  1077. * @returns {URL}
  1078. */
  1079. function resolvePackageTargetString(
  1080. target,
  1081. subpath,
  1082. match,
  1083. packageJsonUrl,
  1084. base,
  1085. pattern,
  1086. internal,
  1087. isPathMap,
  1088. conditions
  1089. ) {
  1090. if (subpath !== '' && !pattern && target[target.length - 1] !== '/')
  1091. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  1092. if (!target.startsWith('./')) {
  1093. if (internal && !target.startsWith('../') && !target.startsWith('/')) {
  1094. let isURL = false;
  1095. try {
  1096. new URL(target);
  1097. isURL = true;
  1098. } catch {
  1099. // Continue regardless of error.
  1100. }
  1101. if (!isURL) {
  1102. const exportTarget = pattern
  1103. ? RegExpPrototypeSymbolReplace.call(
  1104. patternRegEx,
  1105. target,
  1106. () => subpath
  1107. )
  1108. : target + subpath;
  1109. return packageResolve(exportTarget, packageJsonUrl, conditions)
  1110. }
  1111. }
  1112. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  1113. }
  1114. if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
  1115. if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
  1116. if (!isPathMap) {
  1117. const request = pattern
  1118. ? match.replace('*', () => subpath)
  1119. : match + subpath;
  1120. const resolvedTarget = pattern
  1121. ? RegExpPrototypeSymbolReplace.call(
  1122. patternRegEx,
  1123. target,
  1124. () => subpath
  1125. )
  1126. : target;
  1127. emitInvalidSegmentDeprecation(
  1128. resolvedTarget,
  1129. request,
  1130. match,
  1131. packageJsonUrl,
  1132. internal,
  1133. base,
  1134. true
  1135. );
  1136. }
  1137. } else {
  1138. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  1139. }
  1140. }
  1141. const resolved = new URL(target, packageJsonUrl);
  1142. const resolvedPath = resolved.pathname;
  1143. const packagePath = new URL('.', packageJsonUrl).pathname;
  1144. if (!resolvedPath.startsWith(packagePath))
  1145. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  1146. if (subpath === '') return resolved
  1147. if (invalidSegmentRegEx.exec(subpath) !== null) {
  1148. const request = pattern
  1149. ? match.replace('*', () => subpath)
  1150. : match + subpath;
  1151. if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
  1152. if (!isPathMap) {
  1153. const resolvedTarget = pattern
  1154. ? RegExpPrototypeSymbolReplace.call(
  1155. patternRegEx,
  1156. target,
  1157. () => subpath
  1158. )
  1159. : target;
  1160. emitInvalidSegmentDeprecation(
  1161. resolvedTarget,
  1162. request,
  1163. match,
  1164. packageJsonUrl,
  1165. internal,
  1166. base,
  1167. false
  1168. );
  1169. }
  1170. } else {
  1171. throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
  1172. }
  1173. }
  1174. if (pattern) {
  1175. return new URL(
  1176. RegExpPrototypeSymbolReplace.call(
  1177. patternRegEx,
  1178. resolved.href,
  1179. () => subpath
  1180. )
  1181. )
  1182. }
  1183. return new URL(subpath, resolved)
  1184. }
  1185. /**
  1186. * @param {string} key
  1187. * @returns {boolean}
  1188. */
  1189. function isArrayIndex(key) {
  1190. const keyNumber = Number(key);
  1191. if (`${keyNumber}` !== key) return false
  1192. return keyNumber >= 0 && keyNumber < 0xff_ff_ff_ff
  1193. }
  1194. /**
  1195. * @param {URL} packageJsonUrl
  1196. * @param {unknown} target
  1197. * @param {string} subpath
  1198. * @param {string} packageSubpath
  1199. * @param {URL} base
  1200. * @param {boolean} pattern
  1201. * @param {boolean} internal
  1202. * @param {boolean} isPathMap
  1203. * @param {Set<string> | undefined} conditions
  1204. * @returns {URL | null}
  1205. */
  1206. function resolvePackageTarget(
  1207. packageJsonUrl,
  1208. target,
  1209. subpath,
  1210. packageSubpath,
  1211. base,
  1212. pattern,
  1213. internal,
  1214. isPathMap,
  1215. conditions
  1216. ) {
  1217. if (typeof target === 'string') {
  1218. return resolvePackageTargetString(
  1219. target,
  1220. subpath,
  1221. packageSubpath,
  1222. packageJsonUrl,
  1223. base,
  1224. pattern,
  1225. internal,
  1226. isPathMap,
  1227. conditions
  1228. )
  1229. }
  1230. if (Array.isArray(target)) {
  1231. /** @type {Array<unknown>} */
  1232. const targetList = target;
  1233. if (targetList.length === 0) return null
  1234. /** @type {ErrnoException | null | undefined} */
  1235. let lastException;
  1236. let i = -1;
  1237. while (++i < targetList.length) {
  1238. const targetItem = targetList[i];
  1239. /** @type {URL | null} */
  1240. let resolveResult;
  1241. try {
  1242. resolveResult = resolvePackageTarget(
  1243. packageJsonUrl,
  1244. targetItem,
  1245. subpath,
  1246. packageSubpath,
  1247. base,
  1248. pattern,
  1249. internal,
  1250. isPathMap,
  1251. conditions
  1252. );
  1253. } catch (error) {
  1254. const exception = /** @type {ErrnoException} */ (error);
  1255. lastException = exception;
  1256. if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue
  1257. throw error
  1258. }
  1259. if (resolveResult === undefined) continue
  1260. if (resolveResult === null) {
  1261. lastException = null;
  1262. continue
  1263. }
  1264. return resolveResult
  1265. }
  1266. if (lastException === undefined || lastException === null) {
  1267. return null
  1268. }
  1269. throw lastException
  1270. }
  1271. if (typeof target === 'object' && target !== null) {
  1272. const keys = Object.getOwnPropertyNames(target);
  1273. let i = -1;
  1274. while (++i < keys.length) {
  1275. const key = keys[i];
  1276. if (isArrayIndex(key)) {
  1277. throw new ERR_INVALID_PACKAGE_CONFIG(
  1278. fileURLToPath$1(packageJsonUrl),
  1279. base,
  1280. '"exports" cannot contain numeric property keys.'
  1281. )
  1282. }
  1283. }
  1284. i = -1;
  1285. while (++i < keys.length) {
  1286. const key = keys[i];
  1287. if (key === 'default' || (conditions && conditions.has(key))) {
  1288. // @ts-expect-error: indexable.
  1289. const conditionalTarget = /** @type {unknown} */ (target[key]);
  1290. const resolveResult = resolvePackageTarget(
  1291. packageJsonUrl,
  1292. conditionalTarget,
  1293. subpath,
  1294. packageSubpath,
  1295. base,
  1296. pattern,
  1297. internal,
  1298. isPathMap,
  1299. conditions
  1300. );
  1301. if (resolveResult === undefined) continue
  1302. return resolveResult
  1303. }
  1304. }
  1305. return null
  1306. }
  1307. if (target === null) {
  1308. return null
  1309. }
  1310. throw invalidPackageTarget(
  1311. packageSubpath,
  1312. target,
  1313. packageJsonUrl,
  1314. internal,
  1315. base
  1316. )
  1317. }
  1318. /**
  1319. * @param {unknown} exports
  1320. * @param {URL} packageJsonUrl
  1321. * @param {URL} base
  1322. * @returns {boolean}
  1323. */
  1324. function isConditionalExportsMainSugar(exports$1, packageJsonUrl, base) {
  1325. if (typeof exports$1 === 'string' || Array.isArray(exports$1)) return true
  1326. if (typeof exports$1 !== 'object' || exports$1 === null) return false
  1327. const keys = Object.getOwnPropertyNames(exports$1);
  1328. let isConditionalSugar = false;
  1329. let i = 0;
  1330. let keyIndex = -1;
  1331. while (++keyIndex < keys.length) {
  1332. const key = keys[keyIndex];
  1333. const currentIsConditionalSugar = key === '' || key[0] !== '.';
  1334. if (i++ === 0) {
  1335. isConditionalSugar = currentIsConditionalSugar;
  1336. } else if (isConditionalSugar !== currentIsConditionalSugar) {
  1337. throw new ERR_INVALID_PACKAGE_CONFIG(
  1338. fileURLToPath$1(packageJsonUrl),
  1339. base,
  1340. '"exports" cannot contain some keys starting with \'.\' and some not.' +
  1341. ' The exports object must either be an object of package subpath keys' +
  1342. ' or an object of main entry condition name keys only.'
  1343. )
  1344. }
  1345. }
  1346. return isConditionalSugar
  1347. }
  1348. /**
  1349. * @param {string} match
  1350. * @param {URL} pjsonUrl
  1351. * @param {URL} base
  1352. */
  1353. function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
  1354. // @ts-expect-error: apparently it does exist, TS.
  1355. if (process$1.noDeprecation) {
  1356. return
  1357. }
  1358. const pjsonPath = fileURLToPath$1(pjsonUrl);
  1359. if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return
  1360. emittedPackageWarnings.add(pjsonPath + '|' + match);
  1361. process$1.emitWarning(
  1362. `Use of deprecated trailing slash pattern mapping "${match}" in the ` +
  1363. `"exports" field module resolution of the package at ${pjsonPath}${
  1364. base ? ` imported from ${fileURLToPath$1(base)}` : ''
  1365. }. Mapping specifiers ending in "/" is no longer supported.`,
  1366. 'DeprecationWarning',
  1367. 'DEP0155'
  1368. );
  1369. }
  1370. /**
  1371. * @param {URL} packageJsonUrl
  1372. * @param {string} packageSubpath
  1373. * @param {Record<string, unknown>} packageConfig
  1374. * @param {URL} base
  1375. * @param {Set<string> | undefined} conditions
  1376. * @returns {URL}
  1377. */
  1378. function packageExportsResolve(
  1379. packageJsonUrl,
  1380. packageSubpath,
  1381. packageConfig,
  1382. base,
  1383. conditions
  1384. ) {
  1385. let exports$1 = packageConfig.exports;
  1386. if (isConditionalExportsMainSugar(exports$1, packageJsonUrl, base)) {
  1387. exports$1 = {'.': exports$1};
  1388. }
  1389. if (
  1390. own.call(exports$1, packageSubpath) &&
  1391. !packageSubpath.includes('*') &&
  1392. !packageSubpath.endsWith('/')
  1393. ) {
  1394. // @ts-expect-error: indexable.
  1395. const target = exports$1[packageSubpath];
  1396. const resolveResult = resolvePackageTarget(
  1397. packageJsonUrl,
  1398. target,
  1399. '',
  1400. packageSubpath,
  1401. base,
  1402. false,
  1403. false,
  1404. false,
  1405. conditions
  1406. );
  1407. if (resolveResult === null || resolveResult === undefined) {
  1408. throw exportsNotFound(packageSubpath, packageJsonUrl, base)
  1409. }
  1410. return resolveResult
  1411. }
  1412. let bestMatch = '';
  1413. let bestMatchSubpath = '';
  1414. const keys = Object.getOwnPropertyNames(exports$1);
  1415. let i = -1;
  1416. while (++i < keys.length) {
  1417. const key = keys[i];
  1418. const patternIndex = key.indexOf('*');
  1419. if (
  1420. patternIndex !== -1 &&
  1421. packageSubpath.startsWith(key.slice(0, patternIndex))
  1422. ) {
  1423. // When this reaches EOL, this can throw at the top of the whole function:
  1424. //
  1425. // if (StringPrototypeEndsWith(packageSubpath, '/'))
  1426. // throwInvalidSubpath(packageSubpath)
  1427. //
  1428. // To match "imports" and the spec.
  1429. if (packageSubpath.endsWith('/')) {
  1430. emitTrailingSlashPatternDeprecation(
  1431. packageSubpath,
  1432. packageJsonUrl,
  1433. base
  1434. );
  1435. }
  1436. const patternTrailer = key.slice(patternIndex + 1);
  1437. if (
  1438. packageSubpath.length >= key.length &&
  1439. packageSubpath.endsWith(patternTrailer) &&
  1440. patternKeyCompare(bestMatch, key) === 1 &&
  1441. key.lastIndexOf('*') === patternIndex
  1442. ) {
  1443. bestMatch = key;
  1444. bestMatchSubpath = packageSubpath.slice(
  1445. patternIndex,
  1446. packageSubpath.length - patternTrailer.length
  1447. );
  1448. }
  1449. }
  1450. }
  1451. if (bestMatch) {
  1452. // @ts-expect-error: indexable.
  1453. const target = /** @type {unknown} */ (exports$1[bestMatch]);
  1454. const resolveResult = resolvePackageTarget(
  1455. packageJsonUrl,
  1456. target,
  1457. bestMatchSubpath,
  1458. bestMatch,
  1459. base,
  1460. true,
  1461. false,
  1462. packageSubpath.endsWith('/'),
  1463. conditions
  1464. );
  1465. if (resolveResult === null || resolveResult === undefined) {
  1466. throw exportsNotFound(packageSubpath, packageJsonUrl, base)
  1467. }
  1468. return resolveResult
  1469. }
  1470. throw exportsNotFound(packageSubpath, packageJsonUrl, base)
  1471. }
  1472. /**
  1473. * @param {string} a
  1474. * @param {string} b
  1475. */
  1476. function patternKeyCompare(a, b) {
  1477. const aPatternIndex = a.indexOf('*');
  1478. const bPatternIndex = b.indexOf('*');
  1479. const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
  1480. const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
  1481. if (baseLengthA > baseLengthB) return -1
  1482. if (baseLengthB > baseLengthA) return 1
  1483. if (aPatternIndex === -1) return 1
  1484. if (bPatternIndex === -1) return -1
  1485. if (a.length > b.length) return -1
  1486. if (b.length > a.length) return 1
  1487. return 0
  1488. }
  1489. /**
  1490. * @param {string} name
  1491. * @param {URL} base
  1492. * @param {Set<string>} [conditions]
  1493. * @returns {URL}
  1494. */
  1495. function packageImportsResolve(name, base, conditions) {
  1496. if (name === '#' || name.startsWith('#/') || name.endsWith('/')) {
  1497. const reason = 'is not a valid internal imports specifier name';
  1498. throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base))
  1499. }
  1500. /** @type {URL | undefined} */
  1501. let packageJsonUrl;
  1502. const packageConfig = getPackageScopeConfig(base);
  1503. if (packageConfig.exists) {
  1504. packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
  1505. const imports = packageConfig.imports;
  1506. if (imports) {
  1507. if (own.call(imports, name) && !name.includes('*')) {
  1508. const resolveResult = resolvePackageTarget(
  1509. packageJsonUrl,
  1510. imports[name],
  1511. '',
  1512. name,
  1513. base,
  1514. false,
  1515. true,
  1516. false,
  1517. conditions
  1518. );
  1519. if (resolveResult !== null && resolveResult !== undefined) {
  1520. return resolveResult
  1521. }
  1522. } else {
  1523. let bestMatch = '';
  1524. let bestMatchSubpath = '';
  1525. const keys = Object.getOwnPropertyNames(imports);
  1526. let i = -1;
  1527. while (++i < keys.length) {
  1528. const key = keys[i];
  1529. const patternIndex = key.indexOf('*');
  1530. if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
  1531. const patternTrailer = key.slice(patternIndex + 1);
  1532. if (
  1533. name.length >= key.length &&
  1534. name.endsWith(patternTrailer) &&
  1535. patternKeyCompare(bestMatch, key) === 1 &&
  1536. key.lastIndexOf('*') === patternIndex
  1537. ) {
  1538. bestMatch = key;
  1539. bestMatchSubpath = name.slice(
  1540. patternIndex,
  1541. name.length - patternTrailer.length
  1542. );
  1543. }
  1544. }
  1545. }
  1546. if (bestMatch) {
  1547. const target = imports[bestMatch];
  1548. const resolveResult = resolvePackageTarget(
  1549. packageJsonUrl,
  1550. target,
  1551. bestMatchSubpath,
  1552. bestMatch,
  1553. base,
  1554. true,
  1555. true,
  1556. false,
  1557. conditions
  1558. );
  1559. if (resolveResult !== null && resolveResult !== undefined) {
  1560. return resolveResult
  1561. }
  1562. }
  1563. }
  1564. }
  1565. }
  1566. throw importNotDefined(name, packageJsonUrl, base)
  1567. }
  1568. /**
  1569. * @param {string} specifier
  1570. * @param {URL} base
  1571. */
  1572. function parsePackageName(specifier, base) {
  1573. let separatorIndex = specifier.indexOf('/');
  1574. let validPackageName = true;
  1575. let isScoped = false;
  1576. if (specifier[0] === '@') {
  1577. isScoped = true;
  1578. if (separatorIndex === -1 || specifier.length === 0) {
  1579. validPackageName = false;
  1580. } else {
  1581. separatorIndex = specifier.indexOf('/', separatorIndex + 1);
  1582. }
  1583. }
  1584. const packageName =
  1585. separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
  1586. // Package name cannot have leading . and cannot have percent-encoding or
  1587. // \\ separators.
  1588. if (invalidPackageNameRegEx.exec(packageName) !== null) {
  1589. validPackageName = false;
  1590. }
  1591. if (!validPackageName) {
  1592. throw new ERR_INVALID_MODULE_SPECIFIER(
  1593. specifier,
  1594. 'is not a valid package name',
  1595. fileURLToPath$1(base)
  1596. )
  1597. }
  1598. const packageSubpath =
  1599. '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));
  1600. return {packageName, packageSubpath, isScoped}
  1601. }
  1602. /**
  1603. * @param {string} specifier
  1604. * @param {URL} base
  1605. * @param {Set<string> | undefined} conditions
  1606. * @returns {URL}
  1607. */
  1608. function packageResolve(specifier, base, conditions) {
  1609. if (builtinModules.includes(specifier)) {
  1610. return new URL('node:' + specifier)
  1611. }
  1612. const {packageName, packageSubpath, isScoped} = parsePackageName(
  1613. specifier,
  1614. base
  1615. );
  1616. // ResolveSelf
  1617. const packageConfig = getPackageScopeConfig(base);
  1618. // Can’t test.
  1619. /* c8 ignore next 16 */
  1620. if (packageConfig.exists) {
  1621. const packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
  1622. if (
  1623. packageConfig.name === packageName &&
  1624. packageConfig.exports !== undefined &&
  1625. packageConfig.exports !== null
  1626. ) {
  1627. return packageExportsResolve(
  1628. packageJsonUrl,
  1629. packageSubpath,
  1630. packageConfig,
  1631. base,
  1632. conditions
  1633. )
  1634. }
  1635. }
  1636. let packageJsonUrl = new URL(
  1637. './node_modules/' + packageName + '/package.json',
  1638. base
  1639. );
  1640. let packageJsonPath = fileURLToPath$1(packageJsonUrl);
  1641. /** @type {string} */
  1642. let lastPath;
  1643. do {
  1644. const stat = tryStatSync(packageJsonPath.slice(0, -13));
  1645. if (!stat || !stat.isDirectory()) {
  1646. lastPath = packageJsonPath;
  1647. packageJsonUrl = new URL(
  1648. (isScoped ? '../../../../node_modules/' : '../../../node_modules/') +
  1649. packageName +
  1650. '/package.json',
  1651. packageJsonUrl
  1652. );
  1653. packageJsonPath = fileURLToPath$1(packageJsonUrl);
  1654. continue
  1655. }
  1656. // Package match.
  1657. const packageConfig = read(packageJsonPath, {base, specifier});
  1658. if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
  1659. return packageExportsResolve(
  1660. packageJsonUrl,
  1661. packageSubpath,
  1662. packageConfig,
  1663. base,
  1664. conditions
  1665. )
  1666. }
  1667. if (packageSubpath === '.') {
  1668. return legacyMainResolve(packageJsonUrl, packageConfig, base)
  1669. }
  1670. return new URL(packageSubpath, packageJsonUrl)
  1671. // Cross-platform root check.
  1672. } while (packageJsonPath.length !== lastPath.length)
  1673. throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false)
  1674. }
  1675. /**
  1676. * @param {string} specifier
  1677. * @returns {boolean}
  1678. */
  1679. function isRelativeSpecifier(specifier) {
  1680. if (specifier[0] === '.') {
  1681. if (specifier.length === 1 || specifier[1] === '/') return true
  1682. if (
  1683. specifier[1] === '.' &&
  1684. (specifier.length === 2 || specifier[2] === '/')
  1685. ) {
  1686. return true
  1687. }
  1688. }
  1689. return false
  1690. }
  1691. /**
  1692. * @param {string} specifier
  1693. * @returns {boolean}
  1694. */
  1695. function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
  1696. if (specifier === '') return false
  1697. if (specifier[0] === '/') return true
  1698. return isRelativeSpecifier(specifier)
  1699. }
  1700. /**
  1701. * The “Resolver Algorithm Specification” as detailed in the Node docs (which is
  1702. * sync and slightly lower-level than `resolve`).
  1703. *
  1704. * @param {string} specifier
  1705. * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
  1706. * @param {URL} base
  1707. * Full URL (to a file) that `specifier` is resolved relative from.
  1708. * @param {Set<string>} [conditions]
  1709. * Conditions.
  1710. * @param {boolean} [preserveSymlinks]
  1711. * Keep symlinks instead of resolving them.
  1712. * @returns {URL}
  1713. * A URL object to the found thing.
  1714. */
  1715. function moduleResolve(specifier, base, conditions, preserveSymlinks) {
  1716. // Note: The Node code supports `base` as a string (in this internal API) too,
  1717. // we don’t.
  1718. if (conditions === undefined) {
  1719. conditions = getConditionsSet();
  1720. }
  1721. const protocol = base.protocol;
  1722. const isData = protocol === 'data:';
  1723. const isRemote = isData || protocol === 'http:' || protocol === 'https:';
  1724. // Order swapped from spec for minor perf gain.
  1725. // Ok since relative URLs cannot parse as URLs.
  1726. /** @type {URL | undefined} */
  1727. let resolved;
  1728. if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
  1729. try {
  1730. resolved = new URL(specifier, base);
  1731. } catch (error_) {
  1732. const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
  1733. error.cause = error_;
  1734. throw error
  1735. }
  1736. } else if (protocol === 'file:' && specifier[0] === '#') {
  1737. resolved = packageImportsResolve(specifier, base, conditions);
  1738. } else {
  1739. try {
  1740. resolved = new URL(specifier);
  1741. } catch (error_) {
  1742. // Note: actual code uses `canBeRequiredWithoutScheme`.
  1743. if (isRemote && !builtinModules.includes(specifier)) {
  1744. const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
  1745. error.cause = error_;
  1746. throw error
  1747. }
  1748. resolved = packageResolve(specifier, base, conditions);
  1749. }
  1750. }
  1751. assert.ok(resolved !== undefined, 'expected to be defined');
  1752. if (resolved.protocol !== 'file:') {
  1753. return resolved
  1754. }
  1755. return finalizeResolution(resolved, base)
  1756. }
  1757. function fileURLToPath(id) {
  1758. if (typeof id === "string" && !id.startsWith("file://")) {
  1759. return normalizeSlash(id);
  1760. }
  1761. return normalizeSlash(fileURLToPath$1(id));
  1762. }
  1763. function pathToFileURL(id) {
  1764. return pathToFileURL$1(fileURLToPath(id)).toString();
  1765. }
  1766. const INVALID_CHAR_RE = /[\u0000-\u001F"#$&*+,/:;<=>?@[\]^`{|}\u007F]+/g;
  1767. function sanitizeURIComponent(name = "", replacement = "_") {
  1768. return name.replace(INVALID_CHAR_RE, replacement).replace(/%../g, replacement);
  1769. }
  1770. function sanitizeFilePath(filePath = "") {
  1771. return filePath.replace(/\?.*$/, "").split(/[/\\]/g).map((p) => sanitizeURIComponent(p)).join("/").replace(/^([A-Za-z])_\//, "$1:/");
  1772. }
  1773. function normalizeid(id) {
  1774. if (typeof id !== "string") {
  1775. id = id.toString();
  1776. }
  1777. if (/(?:node|data|http|https|file):/.test(id)) {
  1778. return id;
  1779. }
  1780. if (BUILTIN_MODULES.has(id)) {
  1781. return "node:" + id;
  1782. }
  1783. return "file://" + encodeURI(normalizeSlash(id));
  1784. }
  1785. async function loadURL(url) {
  1786. const code = await promises.readFile(fileURLToPath(url), "utf8");
  1787. return code;
  1788. }
  1789. function toDataURL(code) {
  1790. const base64 = Buffer.from(code).toString("base64");
  1791. return `data:text/javascript;base64,${base64}`;
  1792. }
  1793. function isNodeBuiltin(id = "") {
  1794. id = id.replace(/^node:/, "").split("/", 1)[0];
  1795. return BUILTIN_MODULES.has(id);
  1796. }
  1797. const ProtocolRegex = /^(?<proto>.{2,}?):.+$/;
  1798. function getProtocol(id) {
  1799. const proto = id.match(ProtocolRegex);
  1800. return proto ? proto.groups?.proto : void 0;
  1801. }
  1802. const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
  1803. const DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
  1804. const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
  1805. "ERR_MODULE_NOT_FOUND",
  1806. "ERR_UNSUPPORTED_DIR_IMPORT",
  1807. "MODULE_NOT_FOUND",
  1808. "ERR_PACKAGE_PATH_NOT_EXPORTED"
  1809. ]);
  1810. function _tryModuleResolve(id, url, conditions) {
  1811. try {
  1812. return moduleResolve(id, url, conditions);
  1813. } catch (error) {
  1814. if (!NOT_FOUND_ERRORS.has(error?.code)) {
  1815. throw error;
  1816. }
  1817. }
  1818. }
  1819. function _resolve(id, options = {}) {
  1820. if (typeof id !== "string") {
  1821. if (id instanceof URL) {
  1822. id = fileURLToPath(id);
  1823. } else {
  1824. throw new TypeError("input must be a `string` or `URL`");
  1825. }
  1826. }
  1827. if (/(?:node|data|http|https):/.test(id)) {
  1828. return id;
  1829. }
  1830. if (BUILTIN_MODULES.has(id)) {
  1831. return "node:" + id;
  1832. }
  1833. if (id.startsWith("file://")) {
  1834. id = fileURLToPath(id);
  1835. }
  1836. if (isAbsolute(id)) {
  1837. try {
  1838. const stat = statSync(id);
  1839. if (stat.isFile()) {
  1840. return pathToFileURL(id);
  1841. }
  1842. } catch (error) {
  1843. if (error?.code !== "ENOENT") {
  1844. throw error;
  1845. }
  1846. }
  1847. }
  1848. const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
  1849. const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
  1850. if (_urls.length === 0) {
  1851. _urls.push(new URL(pathToFileURL(process.cwd())));
  1852. }
  1853. const urls = [..._urls];
  1854. for (const url of _urls) {
  1855. if (url.protocol === "file:") {
  1856. urls.push(
  1857. new URL("./", url),
  1858. // If url is directory
  1859. new URL(joinURL(url.pathname, "_index.js"), url),
  1860. // TODO: Remove in next major version?
  1861. new URL("node_modules", url)
  1862. );
  1863. }
  1864. }
  1865. let resolved;
  1866. for (const url of urls) {
  1867. resolved = _tryModuleResolve(id, url, conditionsSet);
  1868. if (resolved) {
  1869. break;
  1870. }
  1871. for (const prefix of ["", "/index"]) {
  1872. for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
  1873. resolved = _tryModuleResolve(
  1874. joinURL(id, prefix) + extension,
  1875. url,
  1876. conditionsSet
  1877. );
  1878. if (resolved) {
  1879. break;
  1880. }
  1881. }
  1882. if (resolved) {
  1883. break;
  1884. }
  1885. }
  1886. if (resolved) {
  1887. break;
  1888. }
  1889. }
  1890. if (!resolved) {
  1891. const error = new Error(
  1892. `Cannot find module ${id} imported from ${urls.join(", ")}`
  1893. );
  1894. error.code = "ERR_MODULE_NOT_FOUND";
  1895. throw error;
  1896. }
  1897. return pathToFileURL(resolved);
  1898. }
  1899. function resolveSync(id, options) {
  1900. return _resolve(id, options);
  1901. }
  1902. function resolve(id, options) {
  1903. try {
  1904. return Promise.resolve(resolveSync(id, options));
  1905. } catch (error) {
  1906. return Promise.reject(error);
  1907. }
  1908. }
  1909. function resolvePathSync(id, options) {
  1910. return fileURLToPath(resolveSync(id, options));
  1911. }
  1912. function resolvePath(id, options) {
  1913. try {
  1914. return Promise.resolve(resolvePathSync(id, options));
  1915. } catch (error) {
  1916. return Promise.reject(error);
  1917. }
  1918. }
  1919. function createResolve(defaults) {
  1920. return (id, url) => {
  1921. return resolve(id, { url, ...defaults });
  1922. };
  1923. }
  1924. const NODE_MODULES_RE = /^(.+\/node_modules\/)([^/@]+|@[^/]+\/[^/]+)(\/?.*?)?$/;
  1925. function parseNodeModulePath(path) {
  1926. if (!path) {
  1927. return {};
  1928. }
  1929. path = normalize(fileURLToPath(path));
  1930. const match = NODE_MODULES_RE.exec(path);
  1931. if (!match) {
  1932. return {};
  1933. }
  1934. const [, dir, name, subpath] = match;
  1935. return {
  1936. dir,
  1937. name,
  1938. subpath: subpath ? `.${subpath}` : void 0
  1939. };
  1940. }
  1941. async function lookupNodeModuleSubpath(path) {
  1942. path = normalize(fileURLToPath(path));
  1943. const { name, subpath } = parseNodeModulePath(path);
  1944. if (!name || !subpath) {
  1945. return subpath;
  1946. }
  1947. const { exports: exports$1 } = await readPackageJSON(path).catch(() => {
  1948. }) || {};
  1949. if (exports$1) {
  1950. const resolvedSubpath = _findSubpath(subpath, exports$1);
  1951. if (resolvedSubpath) {
  1952. return resolvedSubpath;
  1953. }
  1954. }
  1955. return subpath;
  1956. }
  1957. function _findSubpath(subpath, exports$1) {
  1958. if (typeof exports$1 === "string") {
  1959. exports$1 = { ".": exports$1 };
  1960. }
  1961. if (!subpath.startsWith(".")) {
  1962. subpath = subpath.startsWith("/") ? `.${subpath}` : `./${subpath}`;
  1963. }
  1964. if (subpath in (exports$1 || {})) {
  1965. return subpath;
  1966. }
  1967. return _flattenExports(exports$1).find((p) => p.fsPath === subpath)?.subpath;
  1968. }
  1969. function _flattenExports(exports$1 = {}, parentSubpath = "./") {
  1970. return Object.entries(exports$1).flatMap(([key, value]) => {
  1971. const [subpath, condition] = key.startsWith(".") ? [key.slice(1), void 0] : ["", key];
  1972. const _subPath = joinURL(parentSubpath, subpath);
  1973. if (typeof value === "string") {
  1974. return [{ subpath: _subPath, fsPath: value, condition }];
  1975. } else {
  1976. return _flattenExports(value, _subPath);
  1977. }
  1978. });
  1979. }
  1980. const ESM_STATIC_IMPORT_RE = /(?<=\s|^|;|\})import\s*(?:[\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu;
  1981. const DYNAMIC_IMPORT_RE = /import\s*\((?<expression>(?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*)\)/gm;
  1982. const IMPORT_NAMED_TYPE_RE = /(?<=\s|^|;|})import\s*type\s+(?:[\s"']*(?<imports>[\w\t\n\r $*,/{}]+)from\s*)?["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gm;
  1983. const EXPORT_DECAL_RE = /\bexport\s+(?<declaration>(?:async function\s*\*?|function\s*\*?|let|const enum|const|enum|var|class))\s+\*?(?<name>[\w$]+)(?<extraNames>.*,\s*[\s\w:[\]{}]*[\w$\]}]+)*/g;
  1984. const EXPORT_DECAL_TYPE_RE = /\bexport\s+(?<declaration>(?:interface|type|declare (?:async function|function|let|const enum|const|enum|var|class)))\s+(?<name>[\w$]+)/g;
  1985. const EXPORT_NAMED_RE = /\bexport\s*{(?<exports>[^}]+?)[\s,]*}(?:\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
  1986. const EXPORT_NAMED_TYPE_RE = /\bexport\s+type\s*{(?<exports>[^}]+?)[\s,]*}(?:\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
  1987. const EXPORT_NAMED_DESTRUCT = /\bexport\s+(?:let|var|const)\s+(?:{(?<exports1>[^}]+?)[\s,]*}|\[(?<exports2>[^\]]+?)[\s,]*])\s+=/gm;
  1988. const EXPORT_STAR_RE = /\bexport\s*\*(?:\s*as\s+(?<name>[\w$]+)\s+)?\s*(?:\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
  1989. const EXPORT_DEFAULT_RE = /\bexport\s+default\s+(async function|function|class|true|false|\W|\d)|\bexport\s+default\s+(?<defaultName>.*)/g;
  1990. const EXPORT_DEFAULT_CLASS_RE = /\bexport\s+default\s+(?<declaration>class)\s+(?<name>[\w$]+)/g;
  1991. const TYPE_RE = /^\s*?type\s/;
  1992. function findStaticImports(code) {
  1993. return _filterStatement(
  1994. _tryGetLocations(code, "import"),
  1995. matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" })
  1996. );
  1997. }
  1998. function findDynamicImports(code) {
  1999. return _filterStatement(
  2000. _tryGetLocations(code, "import"),
  2001. matchAll(DYNAMIC_IMPORT_RE, code, { type: "dynamic" })
  2002. );
  2003. }
  2004. function findTypeImports(code) {
  2005. return [
  2006. ...matchAll(IMPORT_NAMED_TYPE_RE, code, { type: "type" }),
  2007. ...matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" }).filter(
  2008. (match) => /[^A-Za-z]type\s/.test(match.imports)
  2009. )
  2010. ];
  2011. }
  2012. function parseStaticImport(matched) {
  2013. const cleanedImports = clearImports(matched.imports);
  2014. const namedImports = {};
  2015. const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
  2016. for (const namedImport of _matches) {
  2017. const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/);
  2018. const source = _match?.[1] || namedImport.trim();
  2019. const importName = _match?.[2] || source;
  2020. if (source && !TYPE_RE.test(source)) {
  2021. namedImports[source] = importName;
  2022. }
  2023. }
  2024. const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
  2025. return {
  2026. ...matched,
  2027. defaultImport,
  2028. namespacedImport,
  2029. namedImports
  2030. };
  2031. }
  2032. function parseTypeImport(matched) {
  2033. if (matched.type === "type") {
  2034. return parseStaticImport(matched);
  2035. }
  2036. const cleanedImports = clearImports(matched.imports);
  2037. const namedImports = {};
  2038. const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
  2039. for (const namedImport of _matches) {
  2040. const _match = /\s+as\s+/.test(namedImport) ? namedImport.match(/^\s*type\s+(\S*) as (\S*)\s*$/) : namedImport.match(/^\s*type\s+(\S*)\s*$/);
  2041. const source = _match?.[1] || namedImport.trim();
  2042. const importName = _match?.[2] || source;
  2043. if (source && TYPE_RE.test(namedImport)) {
  2044. namedImports[source] = importName;
  2045. }
  2046. }
  2047. const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
  2048. return {
  2049. ...matched,
  2050. defaultImport,
  2051. namespacedImport,
  2052. namedImports
  2053. };
  2054. }
  2055. function _extractExtraNames(extraNamesStr) {
  2056. const names = [];
  2057. let depth = 0;
  2058. let angleDepth = 0;
  2059. let inString = false;
  2060. let inTypeAnnotation = false;
  2061. for (let i = 0; i < extraNamesStr.length; i++) {
  2062. const char = extraNamesStr[i];
  2063. if (inString) {
  2064. if (char === inString) {
  2065. let backslashCount = 0;
  2066. for (let j = i - 1; j >= 0 && extraNamesStr[j] === "\\"; j--) {
  2067. backslashCount++;
  2068. }
  2069. if (backslashCount % 2 === 0) {
  2070. inString = false;
  2071. }
  2072. }
  2073. continue;
  2074. }
  2075. if (char === '"' || char === "'" || char === "`") {
  2076. inString = char;
  2077. continue;
  2078. }
  2079. if (char === ":" && depth === 0 && angleDepth === 0) {
  2080. inTypeAnnotation = true;
  2081. continue;
  2082. }
  2083. if (char === "=" && extraNamesStr[i + 1] !== ">" && depth === 0 && angleDepth === 0) {
  2084. inTypeAnnotation = false;
  2085. }
  2086. if (inTypeAnnotation && char === "<") {
  2087. angleDepth++;
  2088. continue;
  2089. }
  2090. if (!inTypeAnnotation && char === "<" && depth === 0 && i > 0 && _isIdentifierBeforeAngleBracket(extraNamesStr, i)) {
  2091. angleDepth++;
  2092. continue;
  2093. }
  2094. if (char === ">" && angleDepth > 0 && extraNamesStr[i - 1] !== "=") {
  2095. angleDepth--;
  2096. continue;
  2097. }
  2098. if (char === "(" || char === "[" || char === "{") {
  2099. depth++;
  2100. } else if (char === ")" || char === "]" || char === "}") {
  2101. depth--;
  2102. }
  2103. if (char === "," && depth === 0 && angleDepth === 0) {
  2104. const rest = extraNamesStr.slice(i + 1);
  2105. const match = rest.match(/^\s*([\w$]+)/);
  2106. if (match) {
  2107. names.push(match[1]);
  2108. }
  2109. }
  2110. }
  2111. return names;
  2112. }
  2113. function findExports(code) {
  2114. const declaredExports = matchAll(EXPORT_DECAL_RE, code, {
  2115. type: "declaration"
  2116. });
  2117. for (const declaredExport of declaredExports) {
  2118. if (/^export\s+(?:async\s+)?function/.test(declaredExport.code)) {
  2119. continue;
  2120. }
  2121. const extraNamesStr = declaredExport.extraNames;
  2122. if (extraNamesStr) {
  2123. const extraNames = _extractExtraNames(extraNamesStr);
  2124. if (extraNames.length > 0) {
  2125. declaredExport.names = [declaredExport.name, ...extraNames];
  2126. }
  2127. }
  2128. delete declaredExport.extraNames;
  2129. }
  2130. const namedExports = normalizeNamedExports(
  2131. matchAll(EXPORT_NAMED_RE, code, {
  2132. type: "named"
  2133. })
  2134. );
  2135. const destructuredExports = matchAll(
  2136. EXPORT_NAMED_DESTRUCT,
  2137. code,
  2138. { type: "named" }
  2139. );
  2140. for (const namedExport of destructuredExports) {
  2141. namedExport.exports = namedExport.exports1 || namedExport.exports2;
  2142. namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map(
  2143. (name) => name.replace(/^.*?\s*:\s*/, "").replace(/\s*=\s*.*$/, "").trim()
  2144. );
  2145. }
  2146. const defaultExport = matchAll(EXPORT_DEFAULT_RE, code, {
  2147. type: "default",
  2148. name: "default"
  2149. });
  2150. const defaultClassExports = matchAll(EXPORT_DEFAULT_CLASS_RE, code, {
  2151. type: "declaration"
  2152. });
  2153. const starExports = matchAll(EXPORT_STAR_RE, code, {
  2154. type: "star"
  2155. });
  2156. const exports$1 = normalizeExports([
  2157. ...declaredExports,
  2158. ...namedExports,
  2159. ...destructuredExports,
  2160. ...defaultExport,
  2161. ...defaultClassExports,
  2162. ...starExports
  2163. ]);
  2164. if (exports$1.length === 0) {
  2165. return [];
  2166. }
  2167. const exportLocations = _tryGetLocations(code, "export");
  2168. if (exportLocations && exportLocations.length === 0) {
  2169. return [];
  2170. }
  2171. return (
  2172. // Filter false positive export matches
  2173. _filterStatement(exportLocations, exports$1).filter((exp, index, exports2) => {
  2174. const nextExport = exports2[index + 1];
  2175. return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name;
  2176. })
  2177. );
  2178. }
  2179. function findTypeExports(code) {
  2180. const declaredExports = matchAll(
  2181. EXPORT_DECAL_TYPE_RE,
  2182. code,
  2183. { type: "declaration" }
  2184. );
  2185. const namedExports = normalizeNamedExports(
  2186. matchAll(EXPORT_NAMED_TYPE_RE, code, {
  2187. type: "named"
  2188. })
  2189. );
  2190. const exports$1 = normalizeExports([
  2191. ...declaredExports,
  2192. ...namedExports
  2193. ]);
  2194. if (exports$1.length === 0) {
  2195. return [];
  2196. }
  2197. const exportLocations = _tryGetLocations(code, "export");
  2198. if (exportLocations && exportLocations.length === 0) {
  2199. return [];
  2200. }
  2201. return (
  2202. // Filter false positive export matches
  2203. _filterStatement(exportLocations, exports$1).filter((exp, index, exports2) => {
  2204. const nextExport = exports2[index + 1];
  2205. return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name;
  2206. })
  2207. );
  2208. }
  2209. function normalizeExports(exports$1) {
  2210. for (const exp of exports$1) {
  2211. if (!exp.name && exp.names && exp.names.length === 1) {
  2212. exp.name = exp.names[0];
  2213. }
  2214. if (exp.name === "default" && exp.type !== "default") {
  2215. exp._type = exp.type;
  2216. exp.type = "default";
  2217. }
  2218. if (!exp.names && exp.name) {
  2219. exp.names = [exp.name];
  2220. }
  2221. if (exp.type === "declaration" && exp.declaration) {
  2222. exp.declarationType = exp.declaration.replace(
  2223. /^declare\s*/,
  2224. ""
  2225. );
  2226. }
  2227. }
  2228. return exports$1;
  2229. }
  2230. function normalizeNamedExports(namedExports) {
  2231. for (const namedExport of namedExports) {
  2232. namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map((name) => name.replace(/^.*?\sas\s/, "").trim());
  2233. }
  2234. return namedExports;
  2235. }
  2236. function findExportNames(code) {
  2237. return findExports(code).flatMap((exp) => exp.names).filter(Boolean);
  2238. }
  2239. async function resolveModuleExportNames(id, options) {
  2240. const url = await resolvePath(id, options);
  2241. const code = await loadURL(url);
  2242. const exports$1 = findExports(code);
  2243. const exportNames = new Set(
  2244. exports$1.flatMap((exp) => exp.names).filter(Boolean)
  2245. );
  2246. for (const exp of exports$1) {
  2247. if (exp.type !== "star" || !exp.specifier) {
  2248. continue;
  2249. }
  2250. const subExports = await resolveModuleExportNames(exp.specifier, {
  2251. ...options,
  2252. url
  2253. });
  2254. for (const subExport of subExports) {
  2255. exportNames.add(subExport);
  2256. }
  2257. }
  2258. return [...exportNames];
  2259. }
  2260. function _filterStatement(locations, statements) {
  2261. return statements.filter((exp) => {
  2262. return !locations || locations.some((location) => {
  2263. return exp.start <= location.start && exp.end >= location.end;
  2264. });
  2265. });
  2266. }
  2267. function _tryGetLocations(code, label) {
  2268. try {
  2269. return _getLocations(code, label);
  2270. } catch {
  2271. }
  2272. }
  2273. function _getLocations(code, label) {
  2274. const tokens = tokenizer(code, {
  2275. ecmaVersion: "latest",
  2276. sourceType: "module",
  2277. allowHashBang: true,
  2278. allowAwaitOutsideFunction: true,
  2279. allowImportExportEverywhere: true
  2280. });
  2281. const locations = [];
  2282. for (const token of tokens) {
  2283. if (token.type.label === label) {
  2284. locations.push({
  2285. start: token.start,
  2286. end: token.end
  2287. });
  2288. }
  2289. }
  2290. return locations;
  2291. }
  2292. function _isIdentifierBeforeAngleBracket(str, i) {
  2293. let j = i - 1;
  2294. while (j >= 0 && /[A-Za-z0-9_$]/.test(str[j])) {
  2295. j--;
  2296. }
  2297. const wordStart = j + 1;
  2298. return wordStart < i && /[A-Za-z_$]/.test(str[wordStart]);
  2299. }
  2300. function createCommonJS(url) {
  2301. const __filename = fileURLToPath(url);
  2302. const __dirname = dirname(__filename);
  2303. let _nativeRequire;
  2304. const getNativeRequire = () => {
  2305. if (!_nativeRequire) {
  2306. _nativeRequire = createRequire(url);
  2307. }
  2308. return _nativeRequire;
  2309. };
  2310. function require(id) {
  2311. return getNativeRequire()(id);
  2312. }
  2313. require.resolve = function requireResolve(id, options) {
  2314. return getNativeRequire().resolve(id, options);
  2315. };
  2316. return {
  2317. __filename,
  2318. __dirname,
  2319. require
  2320. };
  2321. }
  2322. function interopDefault(sourceModule, opts = {}) {
  2323. if (!isObject(sourceModule) || !("default" in sourceModule)) {
  2324. return sourceModule;
  2325. }
  2326. const defaultValue = sourceModule.default;
  2327. if (defaultValue === void 0 || defaultValue === null) {
  2328. return sourceModule;
  2329. }
  2330. const _defaultType = typeof defaultValue;
  2331. if (_defaultType !== "object" && !(_defaultType === "function" && !opts.preferNamespace)) {
  2332. return opts.preferNamespace ? sourceModule : defaultValue;
  2333. }
  2334. for (const key in sourceModule) {
  2335. try {
  2336. if (!(key in defaultValue)) {
  2337. Object.defineProperty(defaultValue, key, {
  2338. enumerable: key !== "default",
  2339. configurable: key !== "default",
  2340. get() {
  2341. return sourceModule[key];
  2342. }
  2343. });
  2344. }
  2345. } catch {
  2346. }
  2347. }
  2348. return defaultValue;
  2349. }
  2350. const EVAL_ESM_IMPORT_RE = /(?<=import .* from ["'])[^"']+(?=["'])|(?<=export .* from ["'])[^"']+(?=["'])|(?<=import\s*["'])[^"']+(?=["'])|(?<=import\s*\(["'])[^"']+(?=["']\))/g;
  2351. async function loadModule(id, options = {}) {
  2352. const url = await resolve(id, options);
  2353. const code = await loadURL(url);
  2354. return evalModule(code, { ...options, url });
  2355. }
  2356. async function evalModule(code, options = {}) {
  2357. const transformed = await transformModule(code, options);
  2358. const dataURL = toDataURL(transformed);
  2359. return import(dataURL).catch((error) => {
  2360. error.stack = error.stack.replace(
  2361. new RegExp(dataURL, "g"),
  2362. options.url || "_mlly_eval_"
  2363. );
  2364. throw error;
  2365. });
  2366. }
  2367. function transformModule(code, options = {}) {
  2368. if (options.url && options.url.endsWith(".json")) {
  2369. return Promise.resolve("export default " + code);
  2370. }
  2371. if (options.url) {
  2372. code = code.replace(/import\.meta\.url/g, `'${options.url}'`);
  2373. }
  2374. return Promise.resolve(code);
  2375. }
  2376. async function resolveImports(code, options) {
  2377. const imports = [...code.matchAll(EVAL_ESM_IMPORT_RE)].map((m) => m[0]);
  2378. if (imports.length === 0) {
  2379. return code;
  2380. }
  2381. const uniqueImports = [...new Set(imports)];
  2382. const resolved = /* @__PURE__ */ new Map();
  2383. await Promise.all(
  2384. uniqueImports.map(async (id) => {
  2385. let url = await resolve(id, options);
  2386. if (url.endsWith(".json")) {
  2387. const code2 = await loadURL(url);
  2388. url = toDataURL(await transformModule(code2, { url }));
  2389. }
  2390. resolved.set(id, url);
  2391. })
  2392. );
  2393. const re = new RegExp(
  2394. uniqueImports.map((index) => `(?:${index})`).join("|"),
  2395. "g"
  2396. );
  2397. return code.replace(re, (id) => resolved.get(id));
  2398. }
  2399. const ESM_RE = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m;
  2400. const CJS_RE = /(?:[\s;]|^)(?:module\.exports\b|exports\.\w|require\s*\(|global\.\w)/m;
  2401. const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
  2402. const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]);
  2403. function hasESMSyntax(code, opts = {}) {
  2404. if (opts.stripComments) {
  2405. code = code.replace(COMMENT_RE, "");
  2406. }
  2407. return ESM_RE.test(code);
  2408. }
  2409. function hasCJSSyntax(code, opts = {}) {
  2410. if (opts.stripComments) {
  2411. code = code.replace(COMMENT_RE, "");
  2412. }
  2413. return CJS_RE.test(code);
  2414. }
  2415. function detectSyntax(code, opts = {}) {
  2416. if (opts.stripComments) {
  2417. code = code.replace(COMMENT_RE, "");
  2418. }
  2419. const hasESM = hasESMSyntax(code, {});
  2420. const hasCJS = hasCJSSyntax(code, {});
  2421. return {
  2422. hasESM,
  2423. hasCJS,
  2424. isMixed: hasESM && hasCJS
  2425. };
  2426. }
  2427. const validNodeImportDefaults = {
  2428. allowedProtocols: ["node", "file", "data"]
  2429. };
  2430. async function isValidNodeImport(id, _options = {}) {
  2431. if (isNodeBuiltin(id)) {
  2432. return true;
  2433. }
  2434. const options = { ...validNodeImportDefaults, ..._options };
  2435. const proto = getProtocol(id);
  2436. if (proto && !options.allowedProtocols?.includes(proto)) {
  2437. return false;
  2438. }
  2439. if (proto === "data") {
  2440. return true;
  2441. }
  2442. const resolvedPath = await resolvePath(id, options);
  2443. const extension = extname$1(resolvedPath);
  2444. if (BUILTIN_EXTENSIONS.has(extension)) {
  2445. return true;
  2446. }
  2447. if (extension !== ".js") {
  2448. return false;
  2449. }
  2450. const package_ = await readPackageJSON(resolvedPath).catch(() => {
  2451. });
  2452. if (package_?.type === "module") {
  2453. return true;
  2454. }
  2455. if (/\.(?:\w+-)?esm?(?:-\w+)?\.js$|\/esm?\//.test(resolvedPath)) {
  2456. return false;
  2457. }
  2458. const code = options.code || await promises.readFile(resolvedPath, "utf8").catch(() => {
  2459. }) || "";
  2460. return !hasESMSyntax(code, { stripComments: options.stripComments });
  2461. }
  2462. export { DYNAMIC_IMPORT_RE, ESM_STATIC_IMPORT_RE, EXPORT_DECAL_RE, EXPORT_DECAL_TYPE_RE, createCommonJS, createResolve, detectSyntax, evalModule, fileURLToPath, findDynamicImports, findExportNames, findExports, findStaticImports, findTypeExports, findTypeImports, getProtocol, hasCJSSyntax, hasESMSyntax, interopDefault, isNodeBuiltin, isValidNodeImport, loadModule, loadURL, lookupNodeModuleSubpath, normalizeid, parseNodeModulePath, parseStaticImport, parseTypeImport, pathToFileURL, resolve, resolveImports, resolveModuleExportNames, resolvePath, resolvePathSync, resolveSync, sanitizeFilePath, sanitizeURIComponent, toDataURL, transformModule };