版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

2217 lines
60 KiB

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