|
| 1 | +// Flags: --expose-internals |
| 2 | +import { mustCall } from '../common/index.mjs'; |
| 3 | +import esmLoaderModule from 'internal/modules/esm/loader'; |
| 4 | +import assert from 'assert'; |
| 5 | + |
| 6 | +const { ESMLoader } = esmLoaderModule; |
| 7 | + |
| 8 | +/** |
| 9 | + * Verify custom hooks are called with appropriate arguments. |
| 10 | + */ |
| 11 | +{ |
| 12 | + const esmLoader = new ESMLoader(); |
| 13 | + |
| 14 | + const originalSpecifier = 'foo/bar'; |
| 15 | + const importAssertions = Object.assign( |
| 16 | + Object.create(null), |
| 17 | + { type: 'json' }, |
| 18 | + ); |
| 19 | + const parentURL = 'file:///entrypoint.js'; |
| 20 | + const resolvedURL = 'file:///foo/bar.js'; |
| 21 | + const suggestedFormat = 'test'; |
| 22 | + |
| 23 | + function resolve(specifier, context, defaultResolve) { |
| 24 | + assert.strictEqual(specifier, originalSpecifier); |
| 25 | + // Ensure `context` has all and only the properties it's supposed to |
| 26 | + assert.deepStrictEqual(Object.keys(context), [ |
| 27 | + 'conditions', |
| 28 | + 'importAssertions', |
| 29 | + 'parentURL', |
| 30 | + ]); |
| 31 | + assert.ok(Array.isArray(context.conditions)); |
| 32 | + assert.deepStrictEqual(context.importAssertions, importAssertions); |
| 33 | + assert.strictEqual(context.parentURL, parentURL); |
| 34 | + assert.strictEqual(typeof defaultResolve, 'function'); |
| 35 | + |
| 36 | + return { |
| 37 | + format: suggestedFormat, |
| 38 | + url: resolvedURL, |
| 39 | + }; |
| 40 | + } |
| 41 | + |
| 42 | + function load(resolvedURL, context, defaultLoad) { |
| 43 | + assert.strictEqual(resolvedURL, resolvedURL); |
| 44 | + assert.ok(new URL(resolvedURL)); |
| 45 | + // Ensure `context` has all and only the properties it's supposed to |
| 46 | + assert.deepStrictEqual(Object.keys(context), [ |
| 47 | + 'format', |
| 48 | + 'importAssertions', |
| 49 | + ]); |
| 50 | + assert.strictEqual(context.format, suggestedFormat); |
| 51 | + assert.deepStrictEqual(context.importAssertions, importAssertions); |
| 52 | + assert.strictEqual(typeof defaultLoad, 'function'); |
| 53 | + |
| 54 | + // This doesn't matter (just to avoid errors) |
| 55 | + return { |
| 56 | + format: 'module', |
| 57 | + source: '', |
| 58 | + }; |
| 59 | + } |
| 60 | + |
| 61 | + const customLoader = { |
| 62 | + // Ensure ESMLoader actually calls the custom hooks |
| 63 | + resolve: mustCall(resolve), |
| 64 | + load: mustCall(load), |
| 65 | + }; |
| 66 | + |
| 67 | + esmLoader.addCustomLoaders(customLoader); |
| 68 | + |
| 69 | + // Manually trigger hooks (since ESMLoader is not actually running) |
| 70 | + const job = await esmLoader.getModuleJob( |
| 71 | + originalSpecifier, |
| 72 | + parentURL, |
| 73 | + importAssertions, |
| 74 | + ); |
| 75 | + await job.modulePromise; |
| 76 | +} |
0 commit comments