index.mjs 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606
  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, URL as URL$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() || undefined;
  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(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(
  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(
  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(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(message !== undefined, 'expected `message` to be found');
  439. if (typeof message === 'function') {
  440. assert(
  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(
  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, 2023.
  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, 2023.
  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/resolve.js>
  743. // Last checked on: Apr 29, 2023.
  744. const RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
  745. const {
  746. ERR_NETWORK_IMPORT_DISALLOWED,
  747. ERR_INVALID_MODULE_SPECIFIER,
  748. ERR_INVALID_PACKAGE_CONFIG,
  749. ERR_INVALID_PACKAGE_TARGET,
  750. ERR_MODULE_NOT_FOUND,
  751. ERR_PACKAGE_IMPORT_NOT_DEFINED,
  752. ERR_PACKAGE_PATH_NOT_EXPORTED,
  753. ERR_UNSUPPORTED_DIR_IMPORT,
  754. ERR_UNSUPPORTED_RESOLVE_REQUEST
  755. } = codes;
  756. const own = {}.hasOwnProperty;
  757. const invalidSegmentRegEx =
  758. /(^|\\|\/)((\.|%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;
  759. const deprecatedInvalidSegmentRegEx =
  760. /(^|\\|\/)((\.|%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;
  761. const invalidPackageNameRegEx = /^\.|%|\\/;
  762. const patternRegEx = /\*/g;
  763. const encodedSeparatorRegEx = /%2f|%5c/i;
  764. /** @type {Set<string>} */
  765. const emittedPackageWarnings = new Set();
  766. const doubleSlashRegEx = /[/\\]{2}/;
  767. /**
  768. *
  769. * @param {string} target
  770. * @param {string} request
  771. * @param {string} match
  772. * @param {URL} packageJsonUrl
  773. * @param {boolean} internal
  774. * @param {URL} base
  775. * @param {boolean} isTarget
  776. */
  777. function emitInvalidSegmentDeprecation(
  778. target,
  779. request,
  780. match,
  781. packageJsonUrl,
  782. internal,
  783. base,
  784. isTarget
  785. ) {
  786. // @ts-expect-error: apparently it does exist, TS.
  787. if (process$1.noDeprecation) {
  788. return
  789. }
  790. const pjsonPath = fileURLToPath$1(packageJsonUrl);
  791. const double = doubleSlashRegEx.exec(isTarget ? target : request) !== null;
  792. process$1.emitWarning(
  793. `Use of deprecated ${
  794. double ? 'double slash' : 'leading or trailing slash matching'
  795. } resolving "${target}" for module ` +
  796. `request "${request}" ${
  797. request === match ? '' : `matched to "${match}" `
  798. }in the "${
  799. internal ? 'imports' : 'exports'
  800. }" field module resolution of the package at ${pjsonPath}${
  801. base ? ` imported from ${fileURLToPath$1(base)}` : ''
  802. }.`,
  803. 'DeprecationWarning',
  804. 'DEP0166'
  805. );
  806. }
  807. /**
  808. * @param {URL} url
  809. * @param {URL} packageJsonUrl
  810. * @param {URL} base
  811. * @param {string} [main]
  812. * @returns {void}
  813. */
  814. function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
  815. // @ts-expect-error: apparently it does exist, TS.
  816. if (process$1.noDeprecation) {
  817. return
  818. }
  819. const format = defaultGetFormatWithoutErrors(url, {parentURL: base.href});
  820. if (format !== 'module') return
  821. const urlPath = fileURLToPath$1(url.href);
  822. const packagePath = fileURLToPath$1(new URL$1('.', packageJsonUrl));
  823. const basePath = fileURLToPath$1(base);
  824. if (!main) {
  825. process$1.emitWarning(
  826. `No "main" or "exports" field defined in the package.json for ${packagePath} resolving the main entry point "${urlPath.slice(
  827. packagePath.length
  828. )}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`,
  829. 'DeprecationWarning',
  830. 'DEP0151'
  831. );
  832. } else if (path.resolve(packagePath, main) !== urlPath) {
  833. process$1.emitWarning(
  834. `Package ${packagePath} has a "main" field set to "${main}", ` +
  835. `excluding the full filename and extension to the resolved file at "${urlPath.slice(
  836. packagePath.length
  837. )}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is ` +
  838. 'deprecated for ES modules.',
  839. 'DeprecationWarning',
  840. 'DEP0151'
  841. );
  842. }
  843. }
  844. /**
  845. * @param {string} path
  846. * @returns {Stats | undefined}
  847. */
  848. function tryStatSync(path) {
  849. // Note: from Node 15 onwards we can use `throwIfNoEntry: false` instead.
  850. try {
  851. return statSync(path)
  852. } catch {
  853. // Note: in Node code this returns `new Stats`,
  854. // but in Node 22 that’s marked as a deprecated internal API.
  855. // Which, well, we kinda are, but still to prevent that warning,
  856. // just yield `undefined`.
  857. }
  858. }
  859. /**
  860. * Legacy CommonJS main resolution:
  861. * 1. let M = pkg_url + (json main field)
  862. * 2. TRY(M, M.js, M.json, M.node)
  863. * 3. TRY(M/index.js, M/index.json, M/index.node)
  864. * 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
  865. * 5. NOT_FOUND
  866. *
  867. * @param {URL} url
  868. * @returns {boolean}
  869. */
  870. function fileExists(url) {
  871. const stats = statSync(url, {throwIfNoEntry: false});
  872. const isFile = stats ? stats.isFile() : undefined;
  873. return isFile === null || isFile === undefined ? false : isFile
  874. }
  875. /**
  876. * @param {URL} packageJsonUrl
  877. * @param {PackageConfig} packageConfig
  878. * @param {URL} base
  879. * @returns {URL}
  880. */
  881. function legacyMainResolve(packageJsonUrl, packageConfig, base) {
  882. /** @type {URL | undefined} */
  883. let guess;
  884. if (packageConfig.main !== undefined) {
  885. guess = new URL$1(packageConfig.main, packageJsonUrl);
  886. // Note: fs check redundances will be handled by Descriptor cache here.
  887. if (fileExists(guess)) return guess
  888. const tries = [
  889. `./${packageConfig.main}.js`,
  890. `./${packageConfig.main}.json`,
  891. `./${packageConfig.main}.node`,
  892. `./${packageConfig.main}/index.js`,
  893. `./${packageConfig.main}/index.json`,
  894. `./${packageConfig.main}/index.node`
  895. ];
  896. let i = -1;
  897. while (++i < tries.length) {
  898. guess = new URL$1(tries[i], packageJsonUrl);
  899. if (fileExists(guess)) break
  900. guess = undefined;
  901. }
  902. if (guess) {
  903. emitLegacyIndexDeprecation(
  904. guess,
  905. packageJsonUrl,
  906. base,
  907. packageConfig.main
  908. );
  909. return guess
  910. }
  911. // Fallthrough.
  912. }
  913. const tries = ['./index.js', './index.json', './index.node'];
  914. let i = -1;
  915. while (++i < tries.length) {
  916. guess = new URL$1(tries[i], packageJsonUrl);
  917. if (fileExists(guess)) break
  918. guess = undefined;
  919. }
  920. if (guess) {
  921. emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
  922. return guess
  923. }
  924. // Not found.
  925. throw new ERR_MODULE_NOT_FOUND(
  926. fileURLToPath$1(new URL$1('.', packageJsonUrl)),
  927. fileURLToPath$1(base)
  928. )
  929. }
  930. /**
  931. * @param {URL} resolved
  932. * @param {URL} base
  933. * @param {boolean} [preserveSymlinks]
  934. * @returns {URL}
  935. */
  936. function finalizeResolution(resolved, base, preserveSymlinks) {
  937. if (encodedSeparatorRegEx.exec(resolved.pathname) !== null) {
  938. throw new ERR_INVALID_MODULE_SPECIFIER(
  939. resolved.pathname,
  940. 'must not include encoded "/" or "\\" characters',
  941. fileURLToPath$1(base)
  942. )
  943. }
  944. /** @type {string} */
  945. let filePath;
  946. try {
  947. filePath = fileURLToPath$1(resolved);
  948. } catch (error) {
  949. const cause = /** @type {ErrnoException} */ (error);
  950. Object.defineProperty(cause, 'input', {value: String(resolved)});
  951. Object.defineProperty(cause, 'module', {value: String(base)});
  952. throw cause
  953. }
  954. const stats = tryStatSync(
  955. filePath.endsWith('/') ? filePath.slice(-1) : filePath
  956. );
  957. if (stats && stats.isDirectory()) {
  958. const error = new ERR_UNSUPPORTED_DIR_IMPORT(filePath, fileURLToPath$1(base));
  959. // @ts-expect-error Add this for `import.meta.resolve`.
  960. error.url = String(resolved);
  961. throw error
  962. }
  963. if (!stats || !stats.isFile()) {
  964. const error = new ERR_MODULE_NOT_FOUND(
  965. filePath || resolved.pathname,
  966. base && fileURLToPath$1(base),
  967. true
  968. );
  969. // @ts-expect-error Add this for `import.meta.resolve`.
  970. error.url = String(resolved);
  971. throw error
  972. }
  973. {
  974. const real = realpathSync(filePath);
  975. const {search, hash} = resolved;
  976. resolved = pathToFileURL$1(real + (filePath.endsWith(path.sep) ? '/' : ''));
  977. resolved.search = search;
  978. resolved.hash = hash;
  979. }
  980. return resolved
  981. }
  982. /**
  983. * @param {string} specifier
  984. * @param {URL | undefined} packageJsonUrl
  985. * @param {URL} base
  986. * @returns {Error}
  987. */
  988. function importNotDefined(specifier, packageJsonUrl, base) {
  989. return new ERR_PACKAGE_IMPORT_NOT_DEFINED(
  990. specifier,
  991. packageJsonUrl && fileURLToPath$1(new URL$1('.', packageJsonUrl)),
  992. fileURLToPath$1(base)
  993. )
  994. }
  995. /**
  996. * @param {string} subpath
  997. * @param {URL} packageJsonUrl
  998. * @param {URL} base
  999. * @returns {Error}
  1000. */
  1001. function exportsNotFound(subpath, packageJsonUrl, base) {
  1002. return new ERR_PACKAGE_PATH_NOT_EXPORTED(
  1003. fileURLToPath$1(new URL$1('.', packageJsonUrl)),
  1004. subpath,
  1005. base && fileURLToPath$1(base)
  1006. )
  1007. }
  1008. /**
  1009. * @param {string} request
  1010. * @param {string} match
  1011. * @param {URL} packageJsonUrl
  1012. * @param {boolean} internal
  1013. * @param {URL} [base]
  1014. * @returns {never}
  1015. */
  1016. function throwInvalidSubpath(request, match, packageJsonUrl, internal, base) {
  1017. const reason = `request is not a valid match in pattern "${match}" for the "${
  1018. internal ? 'imports' : 'exports'
  1019. }" resolution of ${fileURLToPath$1(packageJsonUrl)}`;
  1020. throw new ERR_INVALID_MODULE_SPECIFIER(
  1021. request,
  1022. reason,
  1023. base && fileURLToPath$1(base)
  1024. )
  1025. }
  1026. /**
  1027. * @param {string} subpath
  1028. * @param {unknown} target
  1029. * @param {URL} packageJsonUrl
  1030. * @param {boolean} internal
  1031. * @param {URL} [base]
  1032. * @returns {Error}
  1033. */
  1034. function invalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
  1035. target =
  1036. typeof target === 'object' && target !== null
  1037. ? JSON.stringify(target, null, '')
  1038. : `${target}`;
  1039. return new ERR_INVALID_PACKAGE_TARGET(
  1040. fileURLToPath$1(new URL$1('.', packageJsonUrl)),
  1041. subpath,
  1042. target,
  1043. internal,
  1044. base && fileURLToPath$1(base)
  1045. )
  1046. }
  1047. /**
  1048. * @param {string} target
  1049. * @param {string} subpath
  1050. * @param {string} match
  1051. * @param {URL} packageJsonUrl
  1052. * @param {URL} base
  1053. * @param {boolean} pattern
  1054. * @param {boolean} internal
  1055. * @param {boolean} isPathMap
  1056. * @param {Set<string> | undefined} conditions
  1057. * @returns {URL}
  1058. */
  1059. function resolvePackageTargetString(
  1060. target,
  1061. subpath,
  1062. match,
  1063. packageJsonUrl,
  1064. base,
  1065. pattern,
  1066. internal,
  1067. isPathMap,
  1068. conditions
  1069. ) {
  1070. if (subpath !== '' && !pattern && target[target.length - 1] !== '/')
  1071. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  1072. if (!target.startsWith('./')) {
  1073. if (internal && !target.startsWith('../') && !target.startsWith('/')) {
  1074. let isURL = false;
  1075. try {
  1076. new URL$1(target);
  1077. isURL = true;
  1078. } catch {
  1079. // Continue regardless of error.
  1080. }
  1081. if (!isURL) {
  1082. const exportTarget = pattern
  1083. ? RegExpPrototypeSymbolReplace.call(
  1084. patternRegEx,
  1085. target,
  1086. () => subpath
  1087. )
  1088. : target + subpath;
  1089. return packageResolve(exportTarget, packageJsonUrl, conditions)
  1090. }
  1091. }
  1092. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  1093. }
  1094. if (invalidSegmentRegEx.exec(target.slice(2)) !== null) {
  1095. if (deprecatedInvalidSegmentRegEx.exec(target.slice(2)) === null) {
  1096. if (!isPathMap) {
  1097. const request = pattern
  1098. ? match.replace('*', () => subpath)
  1099. : match + subpath;
  1100. const resolvedTarget = pattern
  1101. ? RegExpPrototypeSymbolReplace.call(
  1102. patternRegEx,
  1103. target,
  1104. () => subpath
  1105. )
  1106. : target;
  1107. emitInvalidSegmentDeprecation(
  1108. resolvedTarget,
  1109. request,
  1110. match,
  1111. packageJsonUrl,
  1112. internal,
  1113. base,
  1114. true
  1115. );
  1116. }
  1117. } else {
  1118. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  1119. }
  1120. }
  1121. const resolved = new URL$1(target, packageJsonUrl);
  1122. const resolvedPath = resolved.pathname;
  1123. const packagePath = new URL$1('.', packageJsonUrl).pathname;
  1124. if (!resolvedPath.startsWith(packagePath))
  1125. throw invalidPackageTarget(match, target, packageJsonUrl, internal, base)
  1126. if (subpath === '') return resolved
  1127. if (invalidSegmentRegEx.exec(subpath) !== null) {
  1128. const request = pattern
  1129. ? match.replace('*', () => subpath)
  1130. : match + subpath;
  1131. if (deprecatedInvalidSegmentRegEx.exec(subpath) === null) {
  1132. if (!isPathMap) {
  1133. const resolvedTarget = pattern
  1134. ? RegExpPrototypeSymbolReplace.call(
  1135. patternRegEx,
  1136. target,
  1137. () => subpath
  1138. )
  1139. : target;
  1140. emitInvalidSegmentDeprecation(
  1141. resolvedTarget,
  1142. request,
  1143. match,
  1144. packageJsonUrl,
  1145. internal,
  1146. base,
  1147. false
  1148. );
  1149. }
  1150. } else {
  1151. throwInvalidSubpath(request, match, packageJsonUrl, internal, base);
  1152. }
  1153. }
  1154. if (pattern) {
  1155. return new URL$1(
  1156. RegExpPrototypeSymbolReplace.call(
  1157. patternRegEx,
  1158. resolved.href,
  1159. () => subpath
  1160. )
  1161. )
  1162. }
  1163. return new URL$1(subpath, resolved)
  1164. }
  1165. /**
  1166. * @param {string} key
  1167. * @returns {boolean}
  1168. */
  1169. function isArrayIndex(key) {
  1170. const keyNumber = Number(key);
  1171. if (`${keyNumber}` !== key) return false
  1172. return keyNumber >= 0 && keyNumber < 0xff_ff_ff_ff
  1173. }
  1174. /**
  1175. * @param {URL} packageJsonUrl
  1176. * @param {unknown} target
  1177. * @param {string} subpath
  1178. * @param {string} packageSubpath
  1179. * @param {URL} base
  1180. * @param {boolean} pattern
  1181. * @param {boolean} internal
  1182. * @param {boolean} isPathMap
  1183. * @param {Set<string> | undefined} conditions
  1184. * @returns {URL | null}
  1185. */
  1186. function resolvePackageTarget(
  1187. packageJsonUrl,
  1188. target,
  1189. subpath,
  1190. packageSubpath,
  1191. base,
  1192. pattern,
  1193. internal,
  1194. isPathMap,
  1195. conditions
  1196. ) {
  1197. if (typeof target === 'string') {
  1198. return resolvePackageTargetString(
  1199. target,
  1200. subpath,
  1201. packageSubpath,
  1202. packageJsonUrl,
  1203. base,
  1204. pattern,
  1205. internal,
  1206. isPathMap,
  1207. conditions
  1208. )
  1209. }
  1210. if (Array.isArray(target)) {
  1211. /** @type {Array<unknown>} */
  1212. const targetList = target;
  1213. if (targetList.length === 0) return null
  1214. /** @type {ErrnoException | null | undefined} */
  1215. let lastException;
  1216. let i = -1;
  1217. while (++i < targetList.length) {
  1218. const targetItem = targetList[i];
  1219. /** @type {URL | null} */
  1220. let resolveResult;
  1221. try {
  1222. resolveResult = resolvePackageTarget(
  1223. packageJsonUrl,
  1224. targetItem,
  1225. subpath,
  1226. packageSubpath,
  1227. base,
  1228. pattern,
  1229. internal,
  1230. isPathMap,
  1231. conditions
  1232. );
  1233. } catch (error) {
  1234. const exception = /** @type {ErrnoException} */ (error);
  1235. lastException = exception;
  1236. if (exception.code === 'ERR_INVALID_PACKAGE_TARGET') continue
  1237. throw error
  1238. }
  1239. if (resolveResult === undefined) continue
  1240. if (resolveResult === null) {
  1241. lastException = null;
  1242. continue
  1243. }
  1244. return resolveResult
  1245. }
  1246. if (lastException === undefined || lastException === null) {
  1247. return null
  1248. }
  1249. throw lastException
  1250. }
  1251. if (typeof target === 'object' && target !== null) {
  1252. const keys = Object.getOwnPropertyNames(target);
  1253. let i = -1;
  1254. while (++i < keys.length) {
  1255. const key = keys[i];
  1256. if (isArrayIndex(key)) {
  1257. throw new ERR_INVALID_PACKAGE_CONFIG(
  1258. fileURLToPath$1(packageJsonUrl),
  1259. base,
  1260. '"exports" cannot contain numeric property keys.'
  1261. )
  1262. }
  1263. }
  1264. i = -1;
  1265. while (++i < keys.length) {
  1266. const key = keys[i];
  1267. if (key === 'default' || (conditions && conditions.has(key))) {
  1268. // @ts-expect-error: indexable.
  1269. const conditionalTarget = /** @type {unknown} */ (target[key]);
  1270. const resolveResult = resolvePackageTarget(
  1271. packageJsonUrl,
  1272. conditionalTarget,
  1273. subpath,
  1274. packageSubpath,
  1275. base,
  1276. pattern,
  1277. internal,
  1278. isPathMap,
  1279. conditions
  1280. );
  1281. if (resolveResult === undefined) continue
  1282. return resolveResult
  1283. }
  1284. }
  1285. return null
  1286. }
  1287. if (target === null) {
  1288. return null
  1289. }
  1290. throw invalidPackageTarget(
  1291. packageSubpath,
  1292. target,
  1293. packageJsonUrl,
  1294. internal,
  1295. base
  1296. )
  1297. }
  1298. /**
  1299. * @param {unknown} exports
  1300. * @param {URL} packageJsonUrl
  1301. * @param {URL} base
  1302. * @returns {boolean}
  1303. */
  1304. function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
  1305. if (typeof exports === 'string' || Array.isArray(exports)) return true
  1306. if (typeof exports !== 'object' || exports === null) return false
  1307. const keys = Object.getOwnPropertyNames(exports);
  1308. let isConditionalSugar = false;
  1309. let i = 0;
  1310. let keyIndex = -1;
  1311. while (++keyIndex < keys.length) {
  1312. const key = keys[keyIndex];
  1313. const currentIsConditionalSugar = key === '' || key[0] !== '.';
  1314. if (i++ === 0) {
  1315. isConditionalSugar = currentIsConditionalSugar;
  1316. } else if (isConditionalSugar !== currentIsConditionalSugar) {
  1317. throw new ERR_INVALID_PACKAGE_CONFIG(
  1318. fileURLToPath$1(packageJsonUrl),
  1319. base,
  1320. '"exports" cannot contain some keys starting with \'.\' and some not.' +
  1321. ' The exports object must either be an object of package subpath keys' +
  1322. ' or an object of main entry condition name keys only.'
  1323. )
  1324. }
  1325. }
  1326. return isConditionalSugar
  1327. }
  1328. /**
  1329. * @param {string} match
  1330. * @param {URL} pjsonUrl
  1331. * @param {URL} base
  1332. */
  1333. function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) {
  1334. // @ts-expect-error: apparently it does exist, TS.
  1335. if (process$1.noDeprecation) {
  1336. return
  1337. }
  1338. const pjsonPath = fileURLToPath$1(pjsonUrl);
  1339. if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return
  1340. emittedPackageWarnings.add(pjsonPath + '|' + match);
  1341. process$1.emitWarning(
  1342. `Use of deprecated trailing slash pattern mapping "${match}" in the ` +
  1343. `"exports" field module resolution of the package at ${pjsonPath}${
  1344. base ? ` imported from ${fileURLToPath$1(base)}` : ''
  1345. }. Mapping specifiers ending in "/" is no longer supported.`,
  1346. 'DeprecationWarning',
  1347. 'DEP0155'
  1348. );
  1349. }
  1350. /**
  1351. * @param {URL} packageJsonUrl
  1352. * @param {string} packageSubpath
  1353. * @param {Record<string, unknown>} packageConfig
  1354. * @param {URL} base
  1355. * @param {Set<string> | undefined} conditions
  1356. * @returns {URL}
  1357. */
  1358. function packageExportsResolve(
  1359. packageJsonUrl,
  1360. packageSubpath,
  1361. packageConfig,
  1362. base,
  1363. conditions
  1364. ) {
  1365. let exports = packageConfig.exports;
  1366. if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) {
  1367. exports = {'.': exports};
  1368. }
  1369. if (
  1370. own.call(exports, packageSubpath) &&
  1371. !packageSubpath.includes('*') &&
  1372. !packageSubpath.endsWith('/')
  1373. ) {
  1374. // @ts-expect-error: indexable.
  1375. const target = exports[packageSubpath];
  1376. const resolveResult = resolvePackageTarget(
  1377. packageJsonUrl,
  1378. target,
  1379. '',
  1380. packageSubpath,
  1381. base,
  1382. false,
  1383. false,
  1384. false,
  1385. conditions
  1386. );
  1387. if (resolveResult === null || resolveResult === undefined) {
  1388. throw exportsNotFound(packageSubpath, packageJsonUrl, base)
  1389. }
  1390. return resolveResult
  1391. }
  1392. let bestMatch = '';
  1393. let bestMatchSubpath = '';
  1394. const keys = Object.getOwnPropertyNames(exports);
  1395. let i = -1;
  1396. while (++i < keys.length) {
  1397. const key = keys[i];
  1398. const patternIndex = key.indexOf('*');
  1399. if (
  1400. patternIndex !== -1 &&
  1401. packageSubpath.startsWith(key.slice(0, patternIndex))
  1402. ) {
  1403. // When this reaches EOL, this can throw at the top of the whole function:
  1404. //
  1405. // if (StringPrototypeEndsWith(packageSubpath, '/'))
  1406. // throwInvalidSubpath(packageSubpath)
  1407. //
  1408. // To match "imports" and the spec.
  1409. if (packageSubpath.endsWith('/')) {
  1410. emitTrailingSlashPatternDeprecation(
  1411. packageSubpath,
  1412. packageJsonUrl,
  1413. base
  1414. );
  1415. }
  1416. const patternTrailer = key.slice(patternIndex + 1);
  1417. if (
  1418. packageSubpath.length >= key.length &&
  1419. packageSubpath.endsWith(patternTrailer) &&
  1420. patternKeyCompare(bestMatch, key) === 1 &&
  1421. key.lastIndexOf('*') === patternIndex
  1422. ) {
  1423. bestMatch = key;
  1424. bestMatchSubpath = packageSubpath.slice(
  1425. patternIndex,
  1426. packageSubpath.length - patternTrailer.length
  1427. );
  1428. }
  1429. }
  1430. }
  1431. if (bestMatch) {
  1432. // @ts-expect-error: indexable.
  1433. const target = /** @type {unknown} */ (exports[bestMatch]);
  1434. const resolveResult = resolvePackageTarget(
  1435. packageJsonUrl,
  1436. target,
  1437. bestMatchSubpath,
  1438. bestMatch,
  1439. base,
  1440. true,
  1441. false,
  1442. packageSubpath.endsWith('/'),
  1443. conditions
  1444. );
  1445. if (resolveResult === null || resolveResult === undefined) {
  1446. throw exportsNotFound(packageSubpath, packageJsonUrl, base)
  1447. }
  1448. return resolveResult
  1449. }
  1450. throw exportsNotFound(packageSubpath, packageJsonUrl, base)
  1451. }
  1452. /**
  1453. * @param {string} a
  1454. * @param {string} b
  1455. */
  1456. function patternKeyCompare(a, b) {
  1457. const aPatternIndex = a.indexOf('*');
  1458. const bPatternIndex = b.indexOf('*');
  1459. const baseLengthA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
  1460. const baseLengthB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
  1461. if (baseLengthA > baseLengthB) return -1
  1462. if (baseLengthB > baseLengthA) return 1
  1463. if (aPatternIndex === -1) return 1
  1464. if (bPatternIndex === -1) return -1
  1465. if (a.length > b.length) return -1
  1466. if (b.length > a.length) return 1
  1467. return 0
  1468. }
  1469. /**
  1470. * @param {string} name
  1471. * @param {URL} base
  1472. * @param {Set<string>} [conditions]
  1473. * @returns {URL}
  1474. */
  1475. function packageImportsResolve(name, base, conditions) {
  1476. if (name === '#' || name.startsWith('#/') || name.endsWith('/')) {
  1477. const reason = 'is not a valid internal imports specifier name';
  1478. throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath$1(base))
  1479. }
  1480. /** @type {URL | undefined} */
  1481. let packageJsonUrl;
  1482. const packageConfig = getPackageScopeConfig(base);
  1483. if (packageConfig.exists) {
  1484. packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
  1485. const imports = packageConfig.imports;
  1486. if (imports) {
  1487. if (own.call(imports, name) && !name.includes('*')) {
  1488. const resolveResult = resolvePackageTarget(
  1489. packageJsonUrl,
  1490. imports[name],
  1491. '',
  1492. name,
  1493. base,
  1494. false,
  1495. true,
  1496. false,
  1497. conditions
  1498. );
  1499. if (resolveResult !== null && resolveResult !== undefined) {
  1500. return resolveResult
  1501. }
  1502. } else {
  1503. let bestMatch = '';
  1504. let bestMatchSubpath = '';
  1505. const keys = Object.getOwnPropertyNames(imports);
  1506. let i = -1;
  1507. while (++i < keys.length) {
  1508. const key = keys[i];
  1509. const patternIndex = key.indexOf('*');
  1510. if (patternIndex !== -1 && name.startsWith(key.slice(0, -1))) {
  1511. const patternTrailer = key.slice(patternIndex + 1);
  1512. if (
  1513. name.length >= key.length &&
  1514. name.endsWith(patternTrailer) &&
  1515. patternKeyCompare(bestMatch, key) === 1 &&
  1516. key.lastIndexOf('*') === patternIndex
  1517. ) {
  1518. bestMatch = key;
  1519. bestMatchSubpath = name.slice(
  1520. patternIndex,
  1521. name.length - patternTrailer.length
  1522. );
  1523. }
  1524. }
  1525. }
  1526. if (bestMatch) {
  1527. const target = imports[bestMatch];
  1528. const resolveResult = resolvePackageTarget(
  1529. packageJsonUrl,
  1530. target,
  1531. bestMatchSubpath,
  1532. bestMatch,
  1533. base,
  1534. true,
  1535. true,
  1536. false,
  1537. conditions
  1538. );
  1539. if (resolveResult !== null && resolveResult !== undefined) {
  1540. return resolveResult
  1541. }
  1542. }
  1543. }
  1544. }
  1545. }
  1546. throw importNotDefined(name, packageJsonUrl, base)
  1547. }
  1548. /**
  1549. * @param {string} specifier
  1550. * @param {URL} base
  1551. */
  1552. function parsePackageName(specifier, base) {
  1553. let separatorIndex = specifier.indexOf('/');
  1554. let validPackageName = true;
  1555. let isScoped = false;
  1556. if (specifier[0] === '@') {
  1557. isScoped = true;
  1558. if (separatorIndex === -1 || specifier.length === 0) {
  1559. validPackageName = false;
  1560. } else {
  1561. separatorIndex = specifier.indexOf('/', separatorIndex + 1);
  1562. }
  1563. }
  1564. const packageName =
  1565. separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
  1566. // Package name cannot have leading . and cannot have percent-encoding or
  1567. // \\ separators.
  1568. if (invalidPackageNameRegEx.exec(packageName) !== null) {
  1569. validPackageName = false;
  1570. }
  1571. if (!validPackageName) {
  1572. throw new ERR_INVALID_MODULE_SPECIFIER(
  1573. specifier,
  1574. 'is not a valid package name',
  1575. fileURLToPath$1(base)
  1576. )
  1577. }
  1578. const packageSubpath =
  1579. '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));
  1580. return {packageName, packageSubpath, isScoped}
  1581. }
  1582. /**
  1583. * @param {string} specifier
  1584. * @param {URL} base
  1585. * @param {Set<string> | undefined} conditions
  1586. * @returns {URL}
  1587. */
  1588. function packageResolve(specifier, base, conditions) {
  1589. if (builtinModules.includes(specifier)) {
  1590. return new URL$1('node:' + specifier)
  1591. }
  1592. const {packageName, packageSubpath, isScoped} = parsePackageName(
  1593. specifier,
  1594. base
  1595. );
  1596. // ResolveSelf
  1597. const packageConfig = getPackageScopeConfig(base);
  1598. // Can’t test.
  1599. /* c8 ignore next 16 */
  1600. if (packageConfig.exists) {
  1601. const packageJsonUrl = pathToFileURL$1(packageConfig.pjsonPath);
  1602. if (
  1603. packageConfig.name === packageName &&
  1604. packageConfig.exports !== undefined &&
  1605. packageConfig.exports !== null
  1606. ) {
  1607. return packageExportsResolve(
  1608. packageJsonUrl,
  1609. packageSubpath,
  1610. packageConfig,
  1611. base,
  1612. conditions
  1613. )
  1614. }
  1615. }
  1616. let packageJsonUrl = new URL$1(
  1617. './node_modules/' + packageName + '/package.json',
  1618. base
  1619. );
  1620. let packageJsonPath = fileURLToPath$1(packageJsonUrl);
  1621. /** @type {string} */
  1622. let lastPath;
  1623. do {
  1624. const stat = tryStatSync(packageJsonPath.slice(0, -13));
  1625. if (!stat || !stat.isDirectory()) {
  1626. lastPath = packageJsonPath;
  1627. packageJsonUrl = new URL$1(
  1628. (isScoped ? '../../../../node_modules/' : '../../../node_modules/') +
  1629. packageName +
  1630. '/package.json',
  1631. packageJsonUrl
  1632. );
  1633. packageJsonPath = fileURLToPath$1(packageJsonUrl);
  1634. continue
  1635. }
  1636. // Package match.
  1637. const packageConfig = read(packageJsonPath, {base, specifier});
  1638. if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
  1639. return packageExportsResolve(
  1640. packageJsonUrl,
  1641. packageSubpath,
  1642. packageConfig,
  1643. base,
  1644. conditions
  1645. )
  1646. }
  1647. if (packageSubpath === '.') {
  1648. return legacyMainResolve(packageJsonUrl, packageConfig, base)
  1649. }
  1650. return new URL$1(packageSubpath, packageJsonUrl)
  1651. // Cross-platform root check.
  1652. } while (packageJsonPath.length !== lastPath.length)
  1653. throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath$1(base), false)
  1654. }
  1655. /**
  1656. * @param {string} specifier
  1657. * @returns {boolean}
  1658. */
  1659. function isRelativeSpecifier(specifier) {
  1660. if (specifier[0] === '.') {
  1661. if (specifier.length === 1 || specifier[1] === '/') return true
  1662. if (
  1663. specifier[1] === '.' &&
  1664. (specifier.length === 2 || specifier[2] === '/')
  1665. ) {
  1666. return true
  1667. }
  1668. }
  1669. return false
  1670. }
  1671. /**
  1672. * @param {string} specifier
  1673. * @returns {boolean}
  1674. */
  1675. function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
  1676. if (specifier === '') return false
  1677. if (specifier[0] === '/') return true
  1678. return isRelativeSpecifier(specifier)
  1679. }
  1680. /**
  1681. * The “Resolver Algorithm Specification” as detailed in the Node docs (which is
  1682. * sync and slightly lower-level than `resolve`).
  1683. *
  1684. * @param {string} specifier
  1685. * `/example.js`, `./example.js`, `../example.js`, `some-package`, `fs`, etc.
  1686. * @param {URL} base
  1687. * Full URL (to a file) that `specifier` is resolved relative from.
  1688. * @param {Set<string>} [conditions]
  1689. * Conditions.
  1690. * @param {boolean} [preserveSymlinks]
  1691. * Keep symlinks instead of resolving them.
  1692. * @returns {URL}
  1693. * A URL object to the found thing.
  1694. */
  1695. function moduleResolve(specifier, base, conditions, preserveSymlinks) {
  1696. // Note: The Node code supports `base` as a string (in this internal API) too,
  1697. // we don’t.
  1698. const protocol = base.protocol;
  1699. const isData = protocol === 'data:';
  1700. const isRemote = isData || protocol === 'http:' || protocol === 'https:';
  1701. // Order swapped from spec for minor perf gain.
  1702. // Ok since relative URLs cannot parse as URLs.
  1703. /** @type {URL | undefined} */
  1704. let resolved;
  1705. if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
  1706. try {
  1707. resolved = new URL$1(specifier, base);
  1708. } catch (error_) {
  1709. const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
  1710. error.cause = error_;
  1711. throw error
  1712. }
  1713. } else if (protocol === 'file:' && specifier[0] === '#') {
  1714. resolved = packageImportsResolve(specifier, base, conditions);
  1715. } else {
  1716. try {
  1717. resolved = new URL$1(specifier);
  1718. } catch (error_) {
  1719. // Note: actual code uses `canBeRequiredWithoutScheme`.
  1720. if (isRemote && !builtinModules.includes(specifier)) {
  1721. const error = new ERR_UNSUPPORTED_RESOLVE_REQUEST(specifier, base);
  1722. error.cause = error_;
  1723. throw error
  1724. }
  1725. resolved = packageResolve(specifier, base, conditions);
  1726. }
  1727. }
  1728. assert(resolved !== undefined, 'expected to be defined');
  1729. if (resolved.protocol !== 'file:') {
  1730. return resolved
  1731. }
  1732. return finalizeResolution(resolved, base)
  1733. }
  1734. function fileURLToPath(id) {
  1735. if (typeof id === "string" && !id.startsWith("file://")) {
  1736. return normalizeSlash(id);
  1737. }
  1738. return normalizeSlash(fileURLToPath$1(id));
  1739. }
  1740. function pathToFileURL(id) {
  1741. return pathToFileURL$1(fileURLToPath(id)).toString();
  1742. }
  1743. const INVALID_CHAR_RE = /[\u0000-\u001F"#$&*+,/:;<=>?@[\]^`{|}\u007F]+/g;
  1744. function sanitizeURIComponent(name = "", replacement = "_") {
  1745. return name.replace(INVALID_CHAR_RE, replacement).replace(/%../g, replacement);
  1746. }
  1747. function sanitizeFilePath(filePath = "") {
  1748. return filePath.replace(/\?.*$/, "").split(/[/\\]/g).map((p) => sanitizeURIComponent(p)).join("/").replace(/^([A-Za-z])_\//, "$1:/");
  1749. }
  1750. function normalizeid(id) {
  1751. if (typeof id !== "string") {
  1752. id = id.toString();
  1753. }
  1754. if (/(node|data|http|https|file):/.test(id)) {
  1755. return id;
  1756. }
  1757. if (BUILTIN_MODULES.has(id)) {
  1758. return "node:" + id;
  1759. }
  1760. return "file://" + encodeURI(normalizeSlash(id));
  1761. }
  1762. async function loadURL(url) {
  1763. const code = await promises.readFile(fileURLToPath(url), "utf8");
  1764. return code;
  1765. }
  1766. function toDataURL(code) {
  1767. const base64 = Buffer.from(code).toString("base64");
  1768. return `data:text/javascript;base64,${base64}`;
  1769. }
  1770. function isNodeBuiltin(id = "") {
  1771. id = id.replace(/^node:/, "").split("/")[0];
  1772. return BUILTIN_MODULES.has(id);
  1773. }
  1774. const ProtocolRegex = /^(?<proto>.{2,}?):.+$/;
  1775. function getProtocol(id) {
  1776. const proto = id.match(ProtocolRegex);
  1777. return proto ? proto.groups?.proto : undefined;
  1778. }
  1779. const DEFAULT_CONDITIONS_SET = /* @__PURE__ */ new Set(["node", "import"]);
  1780. const DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
  1781. const NOT_FOUND_ERRORS = /* @__PURE__ */ new Set([
  1782. "ERR_MODULE_NOT_FOUND",
  1783. "ERR_UNSUPPORTED_DIR_IMPORT",
  1784. "MODULE_NOT_FOUND",
  1785. "ERR_PACKAGE_PATH_NOT_EXPORTED"
  1786. ]);
  1787. function _tryModuleResolve(id, url, conditions) {
  1788. try {
  1789. return moduleResolve(id, url, conditions);
  1790. } catch (error) {
  1791. if (!NOT_FOUND_ERRORS.has(error?.code)) {
  1792. throw error;
  1793. }
  1794. }
  1795. }
  1796. function _resolve(id, options = {}) {
  1797. if (typeof id !== "string") {
  1798. if (id instanceof URL) {
  1799. id = fileURLToPath(id);
  1800. } else {
  1801. throw new TypeError("input must be a `string` or `URL`");
  1802. }
  1803. }
  1804. if (/(node|data|http|https):/.test(id)) {
  1805. return id;
  1806. }
  1807. if (BUILTIN_MODULES.has(id)) {
  1808. return "node:" + id;
  1809. }
  1810. if (id.startsWith("file://")) {
  1811. id = fileURLToPath(id);
  1812. }
  1813. if (isAbsolute(id)) {
  1814. try {
  1815. const stat = statSync(id);
  1816. if (stat.isFile()) {
  1817. return pathToFileURL(id);
  1818. }
  1819. } catch (error) {
  1820. if (error?.code !== "ENOENT") {
  1821. throw error;
  1822. }
  1823. }
  1824. }
  1825. const conditionsSet = options.conditions ? new Set(options.conditions) : DEFAULT_CONDITIONS_SET;
  1826. const _urls = (Array.isArray(options.url) ? options.url : [options.url]).filter(Boolean).map((url) => new URL(normalizeid(url.toString())));
  1827. if (_urls.length === 0) {
  1828. _urls.push(new URL(pathToFileURL(process.cwd())));
  1829. }
  1830. const urls = [..._urls];
  1831. for (const url of _urls) {
  1832. if (url.protocol === "file:") {
  1833. urls.push(
  1834. new URL("./", url),
  1835. // If url is directory
  1836. new URL(joinURL(url.pathname, "_index.js"), url),
  1837. // TODO: Remove in next major version?
  1838. new URL("node_modules", url)
  1839. );
  1840. }
  1841. }
  1842. let resolved;
  1843. for (const url of urls) {
  1844. resolved = _tryModuleResolve(id, url, conditionsSet);
  1845. if (resolved) {
  1846. break;
  1847. }
  1848. for (const prefix of ["", "/index"]) {
  1849. for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
  1850. resolved = _tryModuleResolve(
  1851. joinURL(id, prefix) + extension,
  1852. url,
  1853. conditionsSet
  1854. );
  1855. if (resolved) {
  1856. break;
  1857. }
  1858. }
  1859. if (resolved) {
  1860. break;
  1861. }
  1862. }
  1863. if (resolved) {
  1864. break;
  1865. }
  1866. }
  1867. if (!resolved) {
  1868. const error = new Error(
  1869. `Cannot find module ${id} imported from ${urls.join(", ")}`
  1870. );
  1871. error.code = "ERR_MODULE_NOT_FOUND";
  1872. throw error;
  1873. }
  1874. return pathToFileURL(resolved);
  1875. }
  1876. function resolveSync(id, options) {
  1877. return _resolve(id, options);
  1878. }
  1879. function resolve(id, options) {
  1880. try {
  1881. return Promise.resolve(resolveSync(id, options));
  1882. } catch (error) {
  1883. return Promise.reject(error);
  1884. }
  1885. }
  1886. function resolvePathSync(id, options) {
  1887. return fileURLToPath(resolveSync(id, options));
  1888. }
  1889. function resolvePath(id, options) {
  1890. try {
  1891. return Promise.resolve(resolvePathSync(id, options));
  1892. } catch (error) {
  1893. return Promise.reject(error);
  1894. }
  1895. }
  1896. function createResolve(defaults) {
  1897. return (id, url) => {
  1898. return resolve(id, { url, ...defaults });
  1899. };
  1900. }
  1901. const NODE_MODULES_RE = /^(.+\/node_modules\/)([^/@]+|@[^/]+\/[^/]+)(\/?.*?)?$/;
  1902. function parseNodeModulePath(path) {
  1903. if (!path) {
  1904. return {};
  1905. }
  1906. path = normalize(fileURLToPath(path));
  1907. const match = NODE_MODULES_RE.exec(path);
  1908. if (!match) {
  1909. return {};
  1910. }
  1911. const [, dir, name, subpath] = match;
  1912. return {
  1913. dir,
  1914. name,
  1915. subpath: subpath ? `.${subpath}` : undefined
  1916. };
  1917. }
  1918. async function lookupNodeModuleSubpath(path) {
  1919. path = normalize(fileURLToPath(path));
  1920. const { name, subpath } = parseNodeModulePath(path);
  1921. if (!name || !subpath) {
  1922. return subpath;
  1923. }
  1924. const { exports } = await readPackageJSON(path).catch(() => {
  1925. }) || {};
  1926. if (exports) {
  1927. const resolvedSubpath = _findSubpath(subpath, exports);
  1928. if (resolvedSubpath) {
  1929. return resolvedSubpath;
  1930. }
  1931. }
  1932. return subpath;
  1933. }
  1934. function _findSubpath(subpath, exports) {
  1935. if (typeof exports === "string") {
  1936. exports = { ".": exports };
  1937. }
  1938. if (!subpath.startsWith(".")) {
  1939. subpath = subpath.startsWith("/") ? `.${subpath}` : `./${subpath}`;
  1940. }
  1941. if (subpath in (exports || {})) {
  1942. return subpath;
  1943. }
  1944. return _flattenExports(exports).find((p) => p.fsPath === subpath)?.subpath;
  1945. }
  1946. function _flattenExports(exports = {}, parentSubpath = "./") {
  1947. return Object.entries(exports).flatMap(([key, value]) => {
  1948. const [subpath, condition] = key.startsWith(".") ? [key.slice(1), undefined] : ["", key];
  1949. const _subPath = joinURL(parentSubpath, subpath);
  1950. if (typeof value === "string") {
  1951. return [{ subpath: _subPath, fsPath: value, condition }];
  1952. } else {
  1953. return _flattenExports(value, _subPath);
  1954. }
  1955. });
  1956. }
  1957. 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;
  1958. const DYNAMIC_IMPORT_RE = /import\s*\((?<expression>(?:[^()]+|\((?:[^()]+|\([^()]*\))*\))*)\)/gm;
  1959. 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;
  1960. 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;
  1961. 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;
  1962. const EXPORT_NAMED_RE = /\bexport\s*{(?<exports>[^}]+?)[\s,]*}(\s*from\s*["']\s*(?<specifier>(?<="\s*)[^"]*[^\s"](?=\s*")|(?<='\s*)[^']*[^\s'](?=\s*'))\s*["'][^\n;]*)?/g;
  1963. 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;
  1964. const EXPORT_NAMED_DESTRUCT = /\bexport\s+(let|var|const)\s+(?:{(?<exports1>[^}]+?)[\s,]*}|\[(?<exports2>[^\]]+?)[\s,]*])\s+=/gm;
  1965. 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;
  1966. const EXPORT_DEFAULT_RE = /\bexport\s+default\s+(async function|function|class|true|false|\W|\d)|\bexport\s+default\s+(?<defaultName>.*)/g;
  1967. const TYPE_RE = /^\s*?type\s/;
  1968. function findStaticImports(code) {
  1969. return _filterStatement(
  1970. _tryGetLocations(code, "import"),
  1971. matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" })
  1972. );
  1973. }
  1974. function findDynamicImports(code) {
  1975. return _filterStatement(
  1976. _tryGetLocations(code, "import"),
  1977. matchAll(DYNAMIC_IMPORT_RE, code, { type: "dynamic" })
  1978. );
  1979. }
  1980. function findTypeImports(code) {
  1981. return [
  1982. ...matchAll(IMPORT_NAMED_TYPE_RE, code, { type: "type" }),
  1983. ...matchAll(ESM_STATIC_IMPORT_RE, code, { type: "static" }).filter(
  1984. (match) => /[^A-Za-z]type\s/.test(match.imports)
  1985. )
  1986. ];
  1987. }
  1988. function parseStaticImport(matched) {
  1989. const cleanedImports = clearImports(matched.imports);
  1990. const namedImports = {};
  1991. const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
  1992. for (const namedImport of _matches) {
  1993. const _match = namedImport.match(/^\s*(\S*) as (\S*)\s*$/);
  1994. const source = _match?.[1] || namedImport.trim();
  1995. const importName = _match?.[2] || source;
  1996. if (source && !TYPE_RE.test(source)) {
  1997. namedImports[source] = importName;
  1998. }
  1999. }
  2000. const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
  2001. return {
  2002. ...matched,
  2003. defaultImport,
  2004. namespacedImport,
  2005. namedImports
  2006. };
  2007. }
  2008. function parseTypeImport(matched) {
  2009. if (matched.type === "type") {
  2010. return parseStaticImport(matched);
  2011. }
  2012. const cleanedImports = clearImports(matched.imports);
  2013. const namedImports = {};
  2014. const _matches = cleanedImports.match(/{([^}]*)}/)?.[1]?.split(",") || [];
  2015. for (const namedImport of _matches) {
  2016. const _match = /\s+as\s+/.test(namedImport) ? namedImport.match(/^\s*type\s+(\S*) as (\S*)\s*$/) : namedImport.match(/^\s*type\s+(\S*)\s*$/);
  2017. const source = _match?.[1] || namedImport.trim();
  2018. const importName = _match?.[2] || source;
  2019. if (source && TYPE_RE.test(namedImport)) {
  2020. namedImports[source] = importName;
  2021. }
  2022. }
  2023. const { namespacedImport, defaultImport } = getImportNames(cleanedImports);
  2024. return {
  2025. ...matched,
  2026. defaultImport,
  2027. namespacedImport,
  2028. namedImports
  2029. };
  2030. }
  2031. function findExports(code) {
  2032. const declaredExports = matchAll(EXPORT_DECAL_RE, code, {
  2033. type: "declaration"
  2034. });
  2035. for (const declaredExport of declaredExports) {
  2036. const extraNamesStr = declaredExport.extraNames;
  2037. if (extraNamesStr) {
  2038. const extraNames = matchAll(
  2039. /({.*?})|(\[.*?])|(,\s*(?<name>\w+))/g,
  2040. extraNamesStr,
  2041. {}
  2042. ).map((m) => m.name).filter(Boolean);
  2043. declaredExport.names = [declaredExport.name, ...extraNames];
  2044. }
  2045. delete declaredExport.extraNames;
  2046. }
  2047. const namedExports = normalizeNamedExports(
  2048. matchAll(EXPORT_NAMED_RE, code, {
  2049. type: "named"
  2050. })
  2051. );
  2052. const destructuredExports = matchAll(
  2053. EXPORT_NAMED_DESTRUCT,
  2054. code,
  2055. { type: "named" }
  2056. );
  2057. for (const namedExport of destructuredExports) {
  2058. namedExport.exports = namedExport.exports1 || namedExport.exports2;
  2059. namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map(
  2060. (name) => name.replace(/^.*?\s*:\s*/, "").replace(/\s*=\s*.*$/, "").trim()
  2061. );
  2062. }
  2063. const defaultExport = matchAll(EXPORT_DEFAULT_RE, code, {
  2064. type: "default",
  2065. name: "default"
  2066. });
  2067. const starExports = matchAll(EXPORT_STAR_RE, code, {
  2068. type: "star"
  2069. });
  2070. const exports = normalizeExports([
  2071. ...declaredExports,
  2072. ...namedExports,
  2073. ...destructuredExports,
  2074. ...defaultExport,
  2075. ...starExports
  2076. ]);
  2077. if (exports.length === 0) {
  2078. return [];
  2079. }
  2080. const exportLocations = _tryGetLocations(code, "export");
  2081. if (exportLocations && exportLocations.length === 0) {
  2082. return [];
  2083. }
  2084. return (
  2085. // Filter false positive export matches
  2086. _filterStatement(exportLocations, exports).filter((exp, index, exports2) => {
  2087. const nextExport = exports2[index + 1];
  2088. return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name;
  2089. })
  2090. );
  2091. }
  2092. function findTypeExports(code) {
  2093. const declaredExports = matchAll(
  2094. EXPORT_DECAL_TYPE_RE,
  2095. code,
  2096. { type: "declaration" }
  2097. );
  2098. const namedExports = normalizeNamedExports(
  2099. matchAll(EXPORT_NAMED_TYPE_RE, code, {
  2100. type: "named"
  2101. })
  2102. );
  2103. const exports = normalizeExports([
  2104. ...declaredExports,
  2105. ...namedExports
  2106. ]);
  2107. if (exports.length === 0) {
  2108. return [];
  2109. }
  2110. const exportLocations = _tryGetLocations(code, "export");
  2111. if (exportLocations && exportLocations.length === 0) {
  2112. return [];
  2113. }
  2114. return (
  2115. // Filter false positive export matches
  2116. _filterStatement(exportLocations, exports).filter((exp, index, exports2) => {
  2117. const nextExport = exports2[index + 1];
  2118. return !nextExport || exp.type !== nextExport.type || !exp.name || exp.name !== nextExport.name;
  2119. })
  2120. );
  2121. }
  2122. function normalizeExports(exports) {
  2123. for (const exp of exports) {
  2124. if (!exp.name && exp.names && exp.names.length === 1) {
  2125. exp.name = exp.names[0];
  2126. }
  2127. if (exp.name === "default" && exp.type !== "default") {
  2128. exp._type = exp.type;
  2129. exp.type = "default";
  2130. }
  2131. if (!exp.names && exp.name) {
  2132. exp.names = [exp.name];
  2133. }
  2134. if (exp.type === "declaration" && exp.declaration) {
  2135. exp.declarationType = exp.declaration.replace(
  2136. /^declare\s*/,
  2137. ""
  2138. );
  2139. }
  2140. }
  2141. return exports;
  2142. }
  2143. function normalizeNamedExports(namedExports) {
  2144. for (const namedExport of namedExports) {
  2145. namedExport.names = namedExport.exports.replace(/^\r?\n?/, "").split(/\s*,\s*/g).filter((name) => !TYPE_RE.test(name)).map((name) => name.replace(/^.*?\sas\s/, "").trim());
  2146. }
  2147. return namedExports;
  2148. }
  2149. function findExportNames(code) {
  2150. return findExports(code).flatMap((exp) => exp.names).filter(Boolean);
  2151. }
  2152. async function resolveModuleExportNames(id, options) {
  2153. const url = await resolvePath(id, options);
  2154. const code = await loadURL(url);
  2155. const exports = findExports(code);
  2156. const exportNames = new Set(
  2157. exports.flatMap((exp) => exp.names).filter(Boolean)
  2158. );
  2159. for (const exp of exports) {
  2160. if (exp.type !== "star" || !exp.specifier) {
  2161. continue;
  2162. }
  2163. const subExports = await resolveModuleExportNames(exp.specifier, {
  2164. ...options,
  2165. url
  2166. });
  2167. for (const subExport of subExports) {
  2168. exportNames.add(subExport);
  2169. }
  2170. }
  2171. return [...exportNames];
  2172. }
  2173. function _filterStatement(locations, statements) {
  2174. return statements.filter((exp) => {
  2175. return !locations || locations.some((location) => {
  2176. return exp.start <= location.start && exp.end >= location.end;
  2177. });
  2178. });
  2179. }
  2180. function _tryGetLocations(code, label) {
  2181. try {
  2182. return _getLocations(code, label);
  2183. } catch {
  2184. }
  2185. }
  2186. function _getLocations(code, label) {
  2187. const tokens = tokenizer(code, {
  2188. ecmaVersion: "latest",
  2189. sourceType: "module",
  2190. allowHashBang: true,
  2191. allowAwaitOutsideFunction: true,
  2192. allowImportExportEverywhere: true
  2193. });
  2194. const locations = [];
  2195. for (const token of tokens) {
  2196. if (token.type.label === label) {
  2197. locations.push({
  2198. start: token.start,
  2199. end: token.end
  2200. });
  2201. }
  2202. }
  2203. return locations;
  2204. }
  2205. function createCommonJS(url) {
  2206. const __filename = fileURLToPath(url);
  2207. const __dirname = dirname(__filename);
  2208. let _nativeRequire;
  2209. const getNativeRequire = () => {
  2210. if (!_nativeRequire) {
  2211. _nativeRequire = createRequire(url);
  2212. }
  2213. return _nativeRequire;
  2214. };
  2215. function require(id) {
  2216. return getNativeRequire()(id);
  2217. }
  2218. require.resolve = function requireResolve(id, options) {
  2219. return getNativeRequire().resolve(id, options);
  2220. };
  2221. return {
  2222. __filename,
  2223. __dirname,
  2224. require
  2225. };
  2226. }
  2227. function interopDefault(sourceModule, opts = {}) {
  2228. if (!isObject(sourceModule) || !("default" in sourceModule)) {
  2229. return sourceModule;
  2230. }
  2231. const defaultValue = sourceModule.default;
  2232. if (defaultValue === undefined || defaultValue === null) {
  2233. return sourceModule;
  2234. }
  2235. const _defaultType = typeof defaultValue;
  2236. if (_defaultType !== "object" && !(_defaultType === "function" && !opts.preferNamespace)) {
  2237. return opts.preferNamespace ? sourceModule : defaultValue;
  2238. }
  2239. for (const key in sourceModule) {
  2240. try {
  2241. if (!(key in defaultValue)) {
  2242. Object.defineProperty(defaultValue, key, {
  2243. enumerable: key !== "default",
  2244. configurable: key !== "default",
  2245. get() {
  2246. return sourceModule[key];
  2247. }
  2248. });
  2249. }
  2250. } catch {
  2251. }
  2252. }
  2253. return defaultValue;
  2254. }
  2255. const EVAL_ESM_IMPORT_RE = /(?<=import .* from ["'])([^"']+)(?=["'])|(?<=export .* from ["'])([^"']+)(?=["'])|(?<=import\s*["'])([^"']+)(?=["'])|(?<=import\s*\(["'])([^"']+)(?=["']\))/g;
  2256. async function loadModule(id, options = {}) {
  2257. const url = await resolve(id, options);
  2258. const code = await loadURL(url);
  2259. return evalModule(code, { ...options, url });
  2260. }
  2261. async function evalModule(code, options = {}) {
  2262. const transformed = await transformModule(code, options);
  2263. const dataURL = toDataURL(transformed);
  2264. return import(dataURL).catch((error) => {
  2265. error.stack = error.stack.replace(
  2266. new RegExp(dataURL, "g"),
  2267. options.url || "_mlly_eval_"
  2268. );
  2269. throw error;
  2270. });
  2271. }
  2272. function transformModule(code, options = {}) {
  2273. if (options.url && options.url.endsWith(".json")) {
  2274. return Promise.resolve("export default " + code);
  2275. }
  2276. if (options.url) {
  2277. code = code.replace(/import\.meta\.url/g, `'${options.url}'`);
  2278. }
  2279. return Promise.resolve(code);
  2280. }
  2281. async function resolveImports(code, options) {
  2282. const imports = [...code.matchAll(EVAL_ESM_IMPORT_RE)].map((m) => m[0]);
  2283. if (imports.length === 0) {
  2284. return code;
  2285. }
  2286. const uniqueImports = [...new Set(imports)];
  2287. const resolved = /* @__PURE__ */ new Map();
  2288. await Promise.all(
  2289. uniqueImports.map(async (id) => {
  2290. let url = await resolve(id, options);
  2291. if (url.endsWith(".json")) {
  2292. const code2 = await loadURL(url);
  2293. url = toDataURL(await transformModule(code2, { url }));
  2294. }
  2295. resolved.set(id, url);
  2296. })
  2297. );
  2298. const re = new RegExp(
  2299. uniqueImports.map((index) => `(${index})`).join("|"),
  2300. "g"
  2301. );
  2302. return code.replace(re, (id) => resolved.get(id));
  2303. }
  2304. 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;
  2305. const CJS_RE = /([\s;]|^)(module.exports\b|exports\.\w|require\s*\(|global\.\w)/m;
  2306. const COMMENT_RE = /\/\*.+?\*\/|\/\/.*(?=[nr])/g;
  2307. const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]);
  2308. function hasESMSyntax(code, opts = {}) {
  2309. if (opts.stripComments) {
  2310. code = code.replace(COMMENT_RE, "");
  2311. }
  2312. return ESM_RE.test(code);
  2313. }
  2314. function hasCJSSyntax(code, opts = {}) {
  2315. if (opts.stripComments) {
  2316. code = code.replace(COMMENT_RE, "");
  2317. }
  2318. return CJS_RE.test(code);
  2319. }
  2320. function detectSyntax(code, opts = {}) {
  2321. if (opts.stripComments) {
  2322. code = code.replace(COMMENT_RE, "");
  2323. }
  2324. const hasESM = hasESMSyntax(code, {});
  2325. const hasCJS = hasCJSSyntax(code, {});
  2326. return {
  2327. hasESM,
  2328. hasCJS,
  2329. isMixed: hasESM && hasCJS
  2330. };
  2331. }
  2332. const validNodeImportDefaults = {
  2333. allowedProtocols: ["node", "file", "data"]
  2334. };
  2335. async function isValidNodeImport(id, _options = {}) {
  2336. if (isNodeBuiltin(id)) {
  2337. return true;
  2338. }
  2339. const options = { ...validNodeImportDefaults, ..._options };
  2340. const proto = getProtocol(id);
  2341. if (proto && !options.allowedProtocols?.includes(proto)) {
  2342. return false;
  2343. }
  2344. if (proto === "data") {
  2345. return true;
  2346. }
  2347. const resolvedPath = await resolvePath(id, options);
  2348. const extension = extname$1(resolvedPath);
  2349. if (BUILTIN_EXTENSIONS.has(extension)) {
  2350. return true;
  2351. }
  2352. if (extension !== ".js") {
  2353. return false;
  2354. }
  2355. const package_ = await readPackageJSON(resolvedPath).catch(() => {
  2356. });
  2357. if (package_?.type === "module") {
  2358. return true;
  2359. }
  2360. if (/\.(\w+-)?esm?(-\w+)?\.js$|\/(esm?)\//.test(resolvedPath)) {
  2361. return false;
  2362. }
  2363. const code = options.code || await promises.readFile(resolvedPath, "utf8").catch(() => {
  2364. }) || "";
  2365. return !hasESMSyntax(code, { stripComments: options.stripComments });
  2366. }
  2367. 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 };