All files / lib/internal DependencyTree.js

100% Statements 99/99
95% Branches 38/40
100% Functions 13/13
100% Lines 97/97

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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283    12x 12x 12x 12x                 23631x 23631x 23631x               7230x       276x 276x         12x                 17x 17x 15x 15x   17x                       15x           15x             15x             15x               7666x   7666x 6651x 6651x             6651x 6651x 6651x     7666x                 529x 529x   529x         529x 794x                 806x   806x 806x 806x                     19853x   8637x 8637x 8637x   8637x         8637x 8791x 3x 3x     8788x 8381x   407x 407x                               8094x   8094x 7122x 7122x   7122x         7122x   7152x 7152x       7122x 8062x   8062x 7149x 7149x 7149x       7122x 972x 30x 102x 102x   102x   102x 81x   21x                 8094x 942x 806x 806x   136x 136x 136x                     7666x     7666x   7666x 38165x 19853x 8791x   18312x 6647x 11665x 529x 11136x 8094x             26x 15x 6258x       26x       12x  
"use strict";
 
const fs = require("fs");
const path = require("path");
const assert = require("assert");
const NodeModule = require("./NodeModule");
 
class Dependency {
  /**
   * @param {string} filename
   * @param {string} id
   * @param {string} [internalID]
   */
  constructor(filename, id, internalID = id) {
    this.id = id;
    this.filename = filename;
    this.internalID = internalID;
  }
 
  /**
   * @param {string} id
   * @returns {Dependency}
   */
  setID(id) {
    return new Dependency(this.filename, id, this.internalID);
  }
 
  get source() {
    const chunks = this.filename.split(path.sep);
    return chunks.slice(chunks.lastIndexOf("node_modules") + 1).join("/");
  }
}
 
/** @type {Map<string, DependencyTree>} */
const cache = new Map();
 
class DependencyTree {
  /**
   * @param {import('./NodeModule')} nodeModule
   * @param {import('@babel/core')} babel
   * @returns {DependencyTree}
   */
  static create(nodeModule, babel) {
    let tree = cache.get(nodeModule.id);
    if (!tree) {
      tree = new DependencyTree(nodeModule, babel);
      cache.set(nodeModule.id, tree);
    }
    return tree;
  }
 
  /**
   * @param {import('./NodeModule')} nodeModule
   * @param {import('@babel/core')} babel
   */
  constructor(nodeModule, babel) {
    /**
     * @readonly
     * @protected
     */
    this.babel = babel;
 
    /**
     * @readonly
     * @protected
     */
    this.nodeModule = nodeModule;
 
    /**
     * @type {Map<string, Dependency>}
     * @readonly
     * @protected
     */
    this.items = new Map();
 
    /**
     * @type {Map<string, Array<import('@babel/types').Statement>>}
     * @readonly
     * @protected
     */
    this.fileCache = new Map();
  }
 
  /**
   * @param {string} filename
   * @returns {Array<import('@babel/types').Statement>}
   */
  visitFile(filename) {
    let statements = this.fileCache.get(filename);
 
    if (!statements) {
      const content = fs.readFileSync(filename, "utf-8");
      const ast = this.babel.parse(content, {
        filename,
        ast: true,
        babelrc: false,
        configFile: false,
        sourceType: "module",
      });
      assert.ok(this.babel.types.isFile(ast));
      statements = ast.program.body;
      this.fileCache.set(filename, statements);
    }
 
    return statements;
  }
 
  /**
   * @param {string} filename
   * @param {import('@babel/types').ExportAllDeclaration} node
   * @returns {Generator<Dependency, void, *>}
   */
  *visitExportAllDeclaration(filename, node) {
    const dir = path.dirname(filename);
    const sourcePath = NodeModule.resolve(node.source.value, dir);
 
    assert.ok(
      sourcePath,
      `failed to resolve '${node.source.value}' from '${dir}'`
    );
 
    for (const dependency of this.collectDependencies(sourcePath)) {
      if (dependency.id !== "default") yield dependency;
    }
  }
 
  /**
   * @param {import('@babel/types').VariableDeclaration} node
   * @returns {Generator<string, void, *>}
   */
  *visitVariableDeclaration(node) {
    const { types: t } = this.babel;
 
    for (const declaration of node.declarations) {
      Eif (t.isIdentifier(declaration.id)) {
        yield declaration.id.name;
      }
    }
  }
 
  /**
   * @param {string} filename
   * @param {import('@babel/types').ImportDeclaration} node
   * @returns {Generator<*, void, *>}
   */
  *visitImportDeclaration(filename, node) {
    if (!node.source.value.startsWith(".")) return;
 
    const { types: t } = this.babel;
    const dir = path.dirname(filename);
    const sourcePath = NodeModule.resolve(node.source.value, dir);
 
    assert.ok(
      sourcePath,
      `failed to resolve '${node.source.value}' from '${dir}'`
    );
 
    for (const specifier of node.specifiers) {
      if (t.isImportNamespaceSpecifier(specifier)) {
        yield new Dependency(sourcePath, specifier.local.name, "*");
        break;
      }
 
      if (t.isImportDefaultSpecifier(specifier)) {
        yield new Dependency(sourcePath, specifier.local.name, "default");
      } else {
        assert.ok(t.isIdentifier(specifier.imported));
        yield new Dependency(
          sourcePath,
          specifier.local.name,
          specifier.imported.name
        );
      }
    }
  }
 
  /**
   * @param {string} filename
   * @param {import('@babel/types').ExportNamedDeclaration} node
   * @param {Map<string, Dependency>} imports
   * @returns {Generator<Dependency, void, *>}
   */
  *visitExportNamedDeclaration(filename, node, imports) {
    const { types: t } = this.babel;
 
    if (node.source) {
      const dir = path.dirname(filename);
      const sourcePath = NodeModule.resolve(node.source.value, dir);
 
      assert.ok(
        sourcePath,
        `failed to resolve '${node.source.value}' from '${dir}'`
      );
 
      const specifiers = new Map(
        node.specifiers.map((specifier) => {
          assert.ok(t.isExportSpecifier(specifier));
          return [specifier.local.name, specifier];
        })
      );
 
      for (const dependency of this.collectDependencies(sourcePath)) {
        const specifier = specifiers.get(dependency.id);
 
        if (specifier) {
          specifiers.delete(dependency.id);
          assert.ok(t.isIdentifier(specifier.exported));
          yield dependency.setID(specifier.exported.name);
        }
      }
 
      assert.ok(!specifiers.size);
    } else if (node.specifiers.length) {
      for (const specifier of node.specifiers) {
        assert.ok(t.isExportSpecifier(specifier));
        assert.ok(t.isIdentifier(specifier.exported));
 
        const importedDependency = imports.get(specifier.local.name);
 
        if (importedDependency) {
          yield importedDependency.setID(specifier.exported.name);
        } else {
          yield new Dependency(
            filename,
            specifier.exported.name,
            specifier.local.name
          );
        }
      }
    }
 
    if (node.declaration) {
      if (t.isVariableDeclaration(node.declaration)) {
        for (const id of this.visitVariableDeclaration(node.declaration)) {
          yield new Dependency(filename, id);
        }
      } else Eif (t.isFunctionDeclaration(node.declaration)) {
        assert.ok(node.declaration.id);
        yield new Dependency(filename, node.declaration.id.name);
      }
    }
  }
 
  /**
   * @param {string} filename
   * @returns {Generator<Dependency, void, *>}
   * @protected
   */
  *collectDependencies(filename = this.nodeModule.entry) {
    const { types: t } = this.babel;
 
    /** @type {Map<string, Dependency>} */
    const imports = new Map();
 
    for (const node of this.visitFile(filename)) {
      if (t.isImportDeclaration(node)) {
        for (const dependency of this.visitImportDeclaration(filename, node)) {
          imports.set(dependency.id, dependency);
        }
      } else if (t.isExportDefaultDeclaration(node)) {
        yield new Dependency(filename, "default");
      } else if (t.isExportAllDeclaration(node)) {
        yield* this.visitExportAllDeclaration(filename, node);
      } else if (t.isExportNamedDeclaration(node)) {
        yield* this.visitExportNamedDeclaration(filename, node, imports);
      }
    }
  }
 
  /** @returns {Map<string, Dependency>} */
  get dependencies() {
    if (!this.items.size) {
      for (const dependency of this.collectDependencies()) {
        this.items.set(dependency.id, dependency);
      }
    }
 
    return this.items;
  }
}
 
module.exports = DependencyTree;