All files / lib/internal NodeModule.js

100% Statements 19/19
100% Branches 10/10
100% Functions 4/4
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    14x 14x     14x                 16312x 16312x     18079x             2x       1x     1x                 23x   23x 20x 20x 20x 20x     23x                 20x 20x       14x  
"use strict";
 
const assert = require("assert");
const resolve = require("resolve");
 
/** @type {Map<string, NodeModule>} */
const cache = new Map();
 
class NodeModule {
  /**
   * @param {string} id
   * @param {string} [basedir]
   * @returns {null | string}
   */
  static resolve(id, basedir) {
    try {
      return resolve.sync(id, {
        basedir,
        packageFilter(pkg) {
          return {
            ...pkg,
            main: pkg.module || pkg.esnext || pkg["jsnext:main"] || pkg.main,
          };
        },
      });
    } catch (error) {
      if (
        error instanceof Error &&
        /** @type {NodeJS.ErrnoException} */ (error).code === "MODULE_NOT_FOUND"
      ) {
        return null;
      }
 
      throw error;
    }
  }
 
  /**
   * @param {string} id
   * @returns {NodeModule}
   */
  static get(id) {
    let module = cache.get(id);
 
    if (!module) {
      const entry = this.resolve(id);
      assert.ok(entry, `failed to find entry file of '${id}'.`);
      module = new NodeModule(id, entry);
      cache.set(id, module);
    }
 
    return module;
  }
 
  /**
   * @param {string} id
   * @param {string} entry
   * @protected
   */
  constructor(id, entry) {
    this.id = id;
    this.entry = entry;
  }
}
 
module.exports = NodeModule;