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