a2089aa726415362a8f23a1809a18b4fdbe36b0e101e7464356e74555fc209d1b1fd17fed1970d1550d3e69781bef9caec5532c86e496badacd7343f9b1510 73 KB

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