• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const {
4  ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING,
5} = require('internal/errors').codes;
6const { Loader } = require('internal/modules/esm/loader');
7const {
8  hasUncaughtExceptionCaptureCallback,
9} = require('internal/process/execution');
10const { pathToFileURL } = require('internal/url');
11const {
12  getModuleFromWrap,
13} = require('internal/vm/module');
14
15exports.initializeImportMetaObject = function(wrap, meta) {
16  const { callbackMap } = internalBinding('module_wrap');
17  if (callbackMap.has(wrap)) {
18    const { initializeImportMeta } = callbackMap.get(wrap);
19    if (initializeImportMeta !== undefined) {
20      initializeImportMeta(meta, getModuleFromWrap(wrap) || wrap);
21    }
22  }
23};
24
25exports.importModuleDynamicallyCallback = async function(wrap, specifier) {
26  const { callbackMap } = internalBinding('module_wrap');
27  if (callbackMap.has(wrap)) {
28    const { importModuleDynamically } = callbackMap.get(wrap);
29    if (importModuleDynamically !== undefined) {
30      return importModuleDynamically(
31        specifier, getModuleFromWrap(wrap) || wrap);
32    }
33  }
34  throw new ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING();
35};
36
37let ESMLoader = new Loader();
38exports.ESMLoader = ESMLoader;
39
40async function initializeLoader() {
41  const { getOptionValue } = require('internal/options');
42  const userLoader = getOptionValue('--experimental-loader');
43  if (!userLoader)
44    return;
45  let cwd;
46  try {
47    cwd = process.cwd() + '/';
48  } catch {
49    cwd = 'file:///';
50  }
51  // If --experimental-loader is specified, create a loader with user hooks.
52  // Otherwise create the default loader.
53  const { emitExperimentalWarning } = require('internal/util');
54  emitExperimentalWarning('--experimental-loader');
55  return (async () => {
56    const hooks =
57        await ESMLoader.import(userLoader, pathToFileURL(cwd).href);
58    ESMLoader = new Loader();
59    ESMLoader.hook(hooks);
60    ESMLoader.runGlobalPreloadCode();
61    return exports.ESMLoader = ESMLoader;
62  })();
63}
64
65exports.loadESM = async function loadESM(callback) {
66  try {
67    await initializeLoader();
68    await callback(ESMLoader);
69  } catch (err) {
70    if (hasUncaughtExceptionCaptureCallback()) {
71      process._fatalException(err);
72      return;
73    }
74    internalBinding('errors').triggerUncaughtException(
75      err,
76      true /* fromPromise */
77    );
78  }
79};
80