All files / src/utils resolveToModule.js

83.33% Statements 15/18
73.33% Branches 11/15
100% Functions 1/1
83.33% Lines 15/18
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                                  13x               1067x 1067x             246x 241x   5x   416x 416x 413x   3x   158x   247x 256x   247x 247x        
/*
 * Copyright (c) 2015, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 *
 */
 
 
import match from './match';
import recast from 'recast';
import resolveToValue from './resolveToValue';
 
var {types: {namedTypes: types}} = recast;
 
/**
 * Given a path (e.g. call expression, member expression or identifier),
 * this function tries to find the name of module from which the "root value"
 * was imported.
 */
export default function resolveToModule(path: NodePath): ?string {
  var node = path.node;
  switch (node.type) {
    case types.VariableDeclarator.name:
      if (node.init) {
        return resolveToModule(path.get('init'));
      }
      break;
    case types.CallExpression.name:
      if (match(node.callee, {type: types.Identifier.name, name: 'require'})) {
        return node.arguments[0].value;
      }
      return resolveToModule(path.get('callee'));
    case types.Identifier.name:
      var valuePath = resolveToValue(path);
      if (valuePath !== path) {
        return resolveToModule(valuePath);
      }
      break;
    case types.ImportDeclaration.name:
      return node.source.value;
    case types.MemberExpression.name:
      while (path && types.MemberExpression.check(path.node)) {
        path = path.get('object');
      }
      Eif (path) {
        return resolveToModule(path);
      }
  }
}