1import { pathToFileURL } from 'node:url'; 2import count from '../es-modules/stateful.mjs'; 3 4 5// Arbitrary instance of manipulating a module's internal state 6// used to assert node-land and user-land have different contexts 7count(); 8 9export function resolve(specifier, { importAssertions }, next) { 10 let format = ''; 11 12 if (specifier === 'esmHook/format.false') { 13 format = false; 14 } 15 if (specifier === 'esmHook/format.true') { 16 format = true; 17 } 18 if (specifier === 'esmHook/preknownFormat.pre') { 19 format = 'module'; 20 } 21 22 if (specifier.startsWith('esmHook')) { 23 return { 24 format, 25 shortCircuit: true, 26 url: pathToFileURL(specifier).href, 27 importAssertions, 28 }; 29 } 30 31 return next(specifier); 32} 33 34/** 35 * @param {string} url A fully resolved file url. 36 * @param {object} context Additional info. 37 * @param {function} next for now, next is defaultLoad a wrapper for 38 * defaultGetFormat + defaultGetSource 39 * @returns {{ format: string, source: (string|SharedArrayBuffer|Uint8Array) }} 40 */ 41export function load(url, context, next) { 42 // Load all .js files as ESM, regardless of package scope 43 if (url.endsWith('.js')) { 44 return next(url, { 45 ...context, 46 format: 'module', 47 }); 48 } 49 50 if (url.endsWith('.ext')) { 51 return next(url, { 52 ...context, 53 format: 'module', 54 }); 55 } 56 57 if (url.endsWith('esmHook/badReturnVal.mjs')) { 58 return 'export function returnShouldBeObject() {}'; 59 } 60 61 if (url.endsWith('esmHook/badReturnFormatVal.mjs')) { 62 return { 63 format: Array(0), 64 shortCircuit: true, 65 source: '', 66 }; 67 } 68 if (url.endsWith('esmHook/unsupportedReturnFormatVal.mjs')) { 69 return { 70 format: 'foo', // Not one of the allowable inputs: no translator named 'foo' 71 shortCircuit: true, 72 source: '', 73 }; 74 } 75 76 if (url.endsWith('esmHook/badReturnSourceVal.mjs')) { 77 return { 78 format: 'module', 79 shortCircuit: true, 80 source: Array(0), 81 }; 82 } 83 84 if (url.endsWith('esmHook/preknownFormat.pre')) { 85 return { 86 format: context.format, 87 shortCircuit: true, 88 source: `const msg = 'hello world'; export default msg;` 89 }; 90 } 91 92 if (url.endsWith('esmHook/virtual.mjs')) { 93 return { 94 format: 'module', 95 shortCircuit: true, 96 source: `export const message = 'Woohoo!'.toUpperCase();`, 97 }; 98 } 99 100 return next(url); 101} 102