• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// This is expected to be used by test-esm-loader-hooks.mjs via:
2// node --loader ./test/fixtures/es-module-loaders/hooks-input.mjs ./test/fixtures/es-modules/json-modules.mjs
3
4import assert from 'assert';
5import { writeSync } from 'fs';
6import { readFile } from 'fs/promises';
7import { fileURLToPath } from 'url';
8
9
10let resolveCalls = 0;
11let loadCalls = 0;
12
13export async function resolve(specifier, context, next) {
14  resolveCalls++;
15  let url;
16
17  if (resolveCalls === 1) {
18    url = new URL(specifier).href;
19    assert.match(specifier, /json-modules\.mjs$/);
20
21    if (!(/\[eval\d*\]$/).test(context.parentURL)) {
22      assert.strictEqual(context.parentURL, undefined);
23    }
24
25    assert.deepStrictEqual(context.importAttributes, {});
26  } else if (resolveCalls === 2) {
27    url = new URL(specifier, context.parentURL).href;
28    assert.match(specifier, /experimental\.json$/);
29    assert.match(context.parentURL, /json-modules\.mjs$/);
30    assert.deepStrictEqual(context.importAttributes, {
31      type: 'json',
32    });
33  }
34
35  // Ensure `context` has all and only the properties it's supposed to
36  assert.deepStrictEqual(Reflect.ownKeys(context), [
37    'conditions',
38    'importAttributes',
39    'parentURL',
40  ]);
41  assert.ok(Array.isArray(context.conditions));
42  assert.strictEqual(typeof next, 'function');
43
44  const returnValue = {
45    url,
46    format: 'test',
47    shortCircuit: true,
48  }
49
50  writeSync(1, JSON.stringify(returnValue) + '\n'); // For the test to validate when it parses stdout
51
52  return returnValue;
53}
54
55export async function load(url, context, next) {
56  loadCalls++;
57  const source = await readFile(fileURLToPath(url));
58  let format;
59
60  if (loadCalls === 1) {
61    assert.match(url, /json-modules\.mjs$/);
62    assert.deepStrictEqual(context.importAttributes, {});
63    format = 'module';
64  } else if (loadCalls === 2) {
65    assert.match(url, /experimental\.json$/);
66    assert.deepStrictEqual(context.importAttributes, {
67      type: 'json',
68    });
69    format = 'json';
70  }
71
72  assert.ok(new URL(url));
73  // Ensure `context` has all and only the properties it's supposed to
74  assert.deepStrictEqual(Object.keys(context), [
75    'format',
76    'importAttributes',
77  ]);
78  assert.strictEqual(context.format, 'test');
79  assert.strictEqual(typeof next, 'function');
80
81  const returnValue = {
82    source,
83    format,
84    shortCircuit: true,
85  };
86
87  writeSync(1, JSON.stringify(returnValue) + '\n'); // For the test to validate when it parses stdout
88
89  return returnValue;
90}
91