611d5fb5b1fb897c5db3dab7a31fb2644f860d6b1d679bb8920ab23e172e4d90749ab6428ad50739246d8fa09a50b7743d683363feb1da96e70e2f1a1d5320 71 KB

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