esm.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.createEsmHooks = exports.registerAndCreateEsmHooks = exports.filterHooksByAPIVersion = void 0;
  4. const index_1 = require("./index");
  5. const url_1 = require("url");
  6. const path_1 = require("path");
  7. const assert = require("assert");
  8. const util_1 = require("./util");
  9. const module_1 = require("module");
  10. // The hooks API changed in node version X so we need to check for backwards compatibility.
  11. const newHooksAPI = (0, util_1.versionGteLt)(process.versions.node, '16.12.0');
  12. /** @internal */
  13. function filterHooksByAPIVersion(hooks) {
  14. const { getFormat, load, resolve, transformSource } = hooks;
  15. // Explicit return type to avoid TS's non-ideal inferred type
  16. const hooksAPI = newHooksAPI
  17. ? { resolve, load, getFormat: undefined, transformSource: undefined }
  18. : { resolve, getFormat, transformSource, load: undefined };
  19. return hooksAPI;
  20. }
  21. exports.filterHooksByAPIVersion = filterHooksByAPIVersion;
  22. /** @internal */
  23. function registerAndCreateEsmHooks(opts) {
  24. // Automatically performs registration just like `-r ts-node/register`
  25. const tsNodeInstance = (0, index_1.register)(opts);
  26. return createEsmHooks(tsNodeInstance);
  27. }
  28. exports.registerAndCreateEsmHooks = registerAndCreateEsmHooks;
  29. function createEsmHooks(tsNodeService) {
  30. tsNodeService.enableExperimentalEsmLoaderInterop();
  31. // Custom implementation that considers additional file extensions and automatically adds file extensions
  32. const nodeResolveImplementation = tsNodeService.getNodeEsmResolver();
  33. const nodeGetFormatImplementation = tsNodeService.getNodeEsmGetFormat();
  34. const extensions = tsNodeService.extensions;
  35. const hooksAPI = filterHooksByAPIVersion({
  36. resolve,
  37. load,
  38. getFormat,
  39. transformSource,
  40. });
  41. function isFileUrlOrNodeStyleSpecifier(parsed) {
  42. // We only understand file:// URLs, but in node, the specifier can be a node-style `./foo` or `foo`
  43. const { protocol } = parsed;
  44. return protocol === null || protocol === 'file:';
  45. }
  46. /**
  47. * Named "probably" as a reminder that this is a guess.
  48. * node does not explicitly tell us if we're resolving the entrypoint or not.
  49. */
  50. function isProbablyEntrypoint(specifier, parentURL) {
  51. return parentURL === undefined && specifier.startsWith('file://');
  52. }
  53. // Side-channel between `resolve()` and `load()` hooks
  54. const rememberIsProbablyEntrypoint = new Set();
  55. const rememberResolvedViaCommonjsFallback = new Set();
  56. async function resolve(specifier, context, defaultResolve) {
  57. const defer = async () => {
  58. const r = await defaultResolve(specifier, context, defaultResolve);
  59. return r;
  60. };
  61. // See: https://github.com/nodejs/node/discussions/41711
  62. // nodejs will likely implement a similar fallback. Till then, we can do our users a favor and fallback today.
  63. async function entrypointFallback(cb) {
  64. try {
  65. const resolution = await cb();
  66. if ((resolution === null || resolution === void 0 ? void 0 : resolution.url) &&
  67. isProbablyEntrypoint(specifier, context.parentURL))
  68. rememberIsProbablyEntrypoint.add(resolution.url);
  69. return resolution;
  70. }
  71. catch (esmResolverError) {
  72. if (!isProbablyEntrypoint(specifier, context.parentURL))
  73. throw esmResolverError;
  74. try {
  75. let cjsSpecifier = specifier;
  76. // Attempt to convert from ESM file:// to CommonJS path
  77. try {
  78. if (specifier.startsWith('file://'))
  79. cjsSpecifier = (0, url_1.fileURLToPath)(specifier);
  80. }
  81. catch { }
  82. const resolution = (0, url_1.pathToFileURL)((0, module_1.createRequire)(process.cwd()).resolve(cjsSpecifier)).toString();
  83. rememberIsProbablyEntrypoint.add(resolution);
  84. rememberResolvedViaCommonjsFallback.add(resolution);
  85. return { url: resolution, format: 'commonjs' };
  86. }
  87. catch (commonjsResolverError) {
  88. throw esmResolverError;
  89. }
  90. }
  91. }
  92. return addShortCircuitFlag(async () => {
  93. const parsed = (0, url_1.parse)(specifier);
  94. const { pathname, protocol, hostname } = parsed;
  95. if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
  96. return entrypointFallback(defer);
  97. }
  98. if (protocol !== null && protocol !== 'file:') {
  99. return entrypointFallback(defer);
  100. }
  101. // Malformed file:// URL? We should always see `null` or `''`
  102. if (hostname) {
  103. // TODO file://./foo sets `hostname` to `'.'`. Perhaps we should special-case this.
  104. return entrypointFallback(defer);
  105. }
  106. // pathname is the path to be resolved
  107. return entrypointFallback(() => nodeResolveImplementation.defaultResolve(specifier, context, defaultResolve));
  108. });
  109. }
  110. // `load` from new loader hook API (See description at the top of this file)
  111. async function load(url, context, defaultLoad) {
  112. return addShortCircuitFlag(async () => {
  113. var _a;
  114. // If we get a format hint from resolve() on the context then use it
  115. // otherwise call the old getFormat() hook using node's old built-in defaultGetFormat() that ships with ts-node
  116. const format = (_a = context.format) !== null && _a !== void 0 ? _a : (await getFormat(url, context, nodeGetFormatImplementation.defaultGetFormat)).format;
  117. let source = undefined;
  118. if (format !== 'builtin' && format !== 'commonjs') {
  119. // Call the new defaultLoad() to get the source
  120. const { source: rawSource } = await defaultLoad(url, {
  121. ...context,
  122. format,
  123. }, defaultLoad);
  124. if (rawSource === undefined || rawSource === null) {
  125. throw new Error(`Failed to load raw source: Format was '${format}' and url was '${url}''.`);
  126. }
  127. // Emulate node's built-in old defaultTransformSource() so we can re-use the old transformSource() hook
  128. const defaultTransformSource = async (source, _context, _defaultTransformSource) => ({ source });
  129. // Call the old hook
  130. const { source: transformedSource } = await transformSource(rawSource, { url, format }, defaultTransformSource);
  131. source = transformedSource;
  132. }
  133. return { format, source };
  134. });
  135. }
  136. async function getFormat(url, context, defaultGetFormat) {
  137. const defer = (overrideUrl = url) => defaultGetFormat(overrideUrl, context, defaultGetFormat);
  138. // See: https://github.com/nodejs/node/discussions/41711
  139. // nodejs will likely implement a similar fallback. Till then, we can do our users a favor and fallback today.
  140. async function entrypointFallback(cb) {
  141. try {
  142. return await cb();
  143. }
  144. catch (getFormatError) {
  145. if (!rememberIsProbablyEntrypoint.has(url))
  146. throw getFormatError;
  147. return { format: 'commonjs' };
  148. }
  149. }
  150. const parsed = (0, url_1.parse)(url);
  151. if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
  152. return entrypointFallback(defer);
  153. }
  154. const { pathname } = parsed;
  155. assert(pathname !== null, 'ESM getFormat() hook: URL should never have null pathname');
  156. const nativePath = (0, url_1.fileURLToPath)(url);
  157. let nodeSays;
  158. // If file has extension not understood by node, then ask node how it would treat the emitted extension.
  159. // E.g. .mts compiles to .mjs, so ask node how to classify an .mjs file.
  160. const ext = (0, path_1.extname)(nativePath);
  161. const tsNodeIgnored = tsNodeService.ignored(nativePath);
  162. const nodeEquivalentExt = extensions.nodeEquivalents.get(ext);
  163. if (nodeEquivalentExt && !tsNodeIgnored) {
  164. nodeSays = await entrypointFallback(() => defer((0, url_1.format)((0, url_1.pathToFileURL)(nativePath + nodeEquivalentExt))));
  165. }
  166. else {
  167. try {
  168. nodeSays = await entrypointFallback(defer);
  169. }
  170. catch (e) {
  171. if (e instanceof Error &&
  172. tsNodeIgnored &&
  173. extensions.nodeDoesNotUnderstand.includes(ext)) {
  174. e.message +=
  175. `\n\n` +
  176. `Hint:\n` +
  177. `ts-node is configured to ignore this file.\n` +
  178. `If you want ts-node to handle this file, consider enabling the "skipIgnore" option or adjusting your "ignore" patterns.\n` +
  179. `https://typestrong.org/ts-node/docs/scope\n`;
  180. }
  181. throw e;
  182. }
  183. }
  184. // For files compiled by ts-node that node believes are either CJS or ESM, check if we should override that classification
  185. if (!tsNodeService.ignored(nativePath) &&
  186. (nodeSays.format === 'commonjs' || nodeSays.format === 'module')) {
  187. const { moduleType } = tsNodeService.moduleTypeClassifier.classifyModuleByModuleTypeOverrides((0, util_1.normalizeSlashes)(nativePath));
  188. if (moduleType === 'cjs') {
  189. return { format: 'commonjs' };
  190. }
  191. else if (moduleType === 'esm') {
  192. return { format: 'module' };
  193. }
  194. }
  195. return nodeSays;
  196. }
  197. async function transformSource(source, context, defaultTransformSource) {
  198. if (source === null || source === undefined) {
  199. throw new Error('No source');
  200. }
  201. const defer = () => defaultTransformSource(source, context, defaultTransformSource);
  202. const sourceAsString = typeof source === 'string' ? source : source.toString('utf8');
  203. const { url } = context;
  204. const parsed = (0, url_1.parse)(url);
  205. if (!isFileUrlOrNodeStyleSpecifier(parsed)) {
  206. return defer();
  207. }
  208. const nativePath = (0, url_1.fileURLToPath)(url);
  209. if (tsNodeService.ignored(nativePath)) {
  210. return defer();
  211. }
  212. const emittedJs = tsNodeService.compile(sourceAsString, nativePath);
  213. return { source: emittedJs };
  214. }
  215. return hooksAPI;
  216. }
  217. exports.createEsmHooks = createEsmHooks;
  218. async function addShortCircuitFlag(fn) {
  219. const ret = await fn();
  220. // Not sure if this is necessary; being lazy. Can revisit in the future.
  221. if (ret == null)
  222. return ret;
  223. return {
  224. ...ret,
  225. shortCircuit: true,
  226. };
  227. }
  228. //# sourceMappingURL=esm.js.map