diff --git a/hook.js b/hook.js index 8e534e0..a7c3632 100644 --- a/hook.js +++ b/hook.js @@ -261,7 +261,7 @@ function createHook (meta) { } } - async function getSource (url, context, parentGetSource) { + async function load (url, context, parentLoad) { if (hasIitm(url)) { const realUrl = deleteIitm(url) @@ -269,10 +269,12 @@ function createHook (meta) { const setters = await processModule({ srcUrl: realUrl, context, - parentGetSource, + parentGetSource: parentLoad, parentResolve: cachedResolve }) return { + shortCircuit: true, + format: 'module', source: ` import { register } from '${iitmURL}' import * as namespace from ${JSON.stringify(realUrl)} @@ -310,20 +312,6 @@ register(${JSON.stringify(realUrl)}, _, set, ${JSON.stringify(specifiers.get(rea } } - return parentGetSource(url, context, parentGetSource) - } - - // For Node.js 16.12.0 and higher. - async function load (url, context, parentLoad) { - if (hasIitm(url)) { - const { source } = await getSource(url, context, parentLoad) - return { - source, - shortCircuit: true, - format: 'module' - } - } - return parentLoad(url, context, parentLoad) } @@ -333,7 +321,7 @@ register(${JSON.stringify(realUrl)}, _, set, ${JSON.stringify(specifiers.get(rea return { load, resolve, - getSource, + getSource: load, getFormat (url, context, parentGetFormat) { if (hasIitm(url)) { return { diff --git a/lib/get-exports.js b/lib/get-exports.js index 9a78e8c..b0872c7 100644 --- a/lib/get-exports.js +++ b/lib/get-exports.js @@ -92,23 +92,29 @@ async function getExports (url, context, parentLoad) { source = readFileSync(fileURLToPath(url), 'utf8') } - if (format === 'module') { - return getEsmExports(source) - } + try { + if (format === 'module') { + return getEsmExports(source) + } - if (format === 'commonjs') { - return getCjsExports(url, context, parentLoad, source) - } + if (format === 'commonjs') { + return await getCjsExports(url, context, parentLoad, source) + } - // At this point our `format` is either undefined or not known by us. Fall - // back to parsing as ESM/CJS. - const esmExports = getEsmExports(source) - if (!esmExports.length) { - // TODO(bengl) it's might be possible to get here if somehow the format - // isn't set at first and yet we have an ESM module with no exports. - // I couldn't construct an example that would do this, so maybe it's - // impossible? - return getCjsExports(url, context, parentLoad, source) + // At this point our `format` is either undefined or not known by us. Fall + // back to parsing as ESM/CJS. + const esmExports = getEsmExports(source) + if (!esmExports.length) { + // TODO(bengl) it's might be possible to get here if somehow the format + // isn't set at first and yet we have an ESM module with no exports. + // I couldn't construct an example that would do this, so maybe it's + // impossible? + return await getCjsExports(url, context, parentLoad, source) + } + } catch (cause) { + const err = new Error(`Failed to parse '${url}'`) + err.cause = cause + throw err } }