All files / source/CaffeineMc ModuleResolver.js

98.2% Statements 109/111
90.63% Branches 58/64
90.91% Functions 10/11
98.2% Lines 109/111

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 284 285 286 287  7x   7x   7x   7x   7x   7x   7x   7x   7x   7x                                               7x                             7x   15x 15x 15x   15x 15x 8x     15x 15x 8x     8x       7x 4x 4x   3x   7x           7x   32x 6x   6x 6x 6x 15x 15x 15x   6x     26x   32x 24x 6x 9x 9x 9x 9x                       24x           7x 19x 19x       7x   7x   32x 32x 31x   32x 32x 28x 28x 28x 28x   32x 32x 32x 45x 16x   29x 29x 12x 2x   12x   17x       32x 18x 18x     2x   18x 9x   18x         14x 14x   8x 8x 8x         8x                                                                                       7x   191x 10x 181x 142x 20x 20x 20x 20x 24x 24x 24x 24x 17x       125x       7x   54x 54x 54x 191x 191x 27x               27x     54x     7x          
// Generated by CoffeeScript 1.12.7
(function() {
  var ErrorWithInfo, ModuleResolver, Path, Promise, cacheable, currentSecond, dashCase, defineModule, dirReader, each, find, findSourceRootSync, log, merge, mergeInto, normalizeName, peek, present, readdirSync, realRequire, ref, ref1, snakeCase, statSync, upperCamelCase, w,
    slice = [].slice;
 
  ref = require('art-standard-lib'), defineModule = ref.defineModule, peek = ref.peek, Promise = ref.Promise, dashCase = ref.dashCase, upperCamelCase = ref.upperCamelCase, ErrorWithInfo = ref.ErrorWithInfo, log = ref.log, merge = ref.merge, present = ref.present, find = ref.find, each = ref.each, w = ref.w, mergeInto = ref.mergeInto, currentSecond = ref.currentSecond, snakeCase = ref.snakeCase;
 
  Path = require('path');
 
  ref1 = require('fs-extra'), statSync = ref1.statSync, readdirSync = ref1.readdirSync;
 
  dirReader = require('./DirReader');
 
  cacheable = require('./WorkingCache').cacheable;
 
  normalizeName = cacheable("normalizeName", upperCamelCase);
 
  realRequire = eval('require');
 
  findSourceRootSync = require('./SourceRoots').findSourceRootSync;
 
 
  /*
  2018-07-21 Optimization TODO:
  
  I think if we simplify the semantics such that matches are defined as:
    normalizeName(dirName) == normalizeName(moduleName)
  AND
     * this is the change:
    normalizeName(fileName.split(".")[0]) == normalizeName(moduleName)
  
  Then we can probably make much better use of caching:
    Read the dir in and create a map:
      normalizedName: name
    (where normalizedName here means for files, we strip the extensions)
  
  Then, we don't have to scan the dir every time!
  
  NOTE: I think if we have >= 2 files which map to the same noramlized name
  we encode that in the map somehow and can therefore raise the same
  exception we already do.
   */
 
  defineModule(module, ModuleResolver = (function() {
    var getMatchingName, maybeCouldHaveCached;
 
    function ModuleResolver() {}
 
 
    /*
    IN:
      moduleBaseName: the string before the first '/'
      modulePathArray: every other sub-string, split by '/'
        This is only used to determine if there is addutional pathing
        that must be resolved. It makes a difference what the
        require path looks like.
     */
 
    ModuleResolver.getNpmPackageName = function(moduleBaseName, modulePathArray) {
      var absolutePath, name, normalizedModuleName, requireString;
      normalizedModuleName = upperCamelCase(moduleBaseName);
      try {
        absolutePath = Path.dirname(realRequire.resolve(name = dashCase(moduleBaseName)));
      } catch (error) {}
      try {
        if (absolutePath == null) {
          absolutePath = Path.dirname(realRequire.resolve(name = snakeCase(moduleBaseName)));
        }
      } catch (error) {}
      try {
        if (absolutePath == null) {
          absolutePath = Path.dirname(realRequire.resolve(name = moduleBaseName));
        }
      } catch (error) {
        throw new ErrorWithInfo("ModuleResolver: Could not find requested npm package: " + moduleBaseName, {
          npmPackageNamesAttempted: [moduleBaseName, dashCase(moduleBaseName)]
        });
      }
      if ((modulePathArray != null ? modulePathArray.length : void 0) > 0) {
        requireString = name.split('/')[0];
        absolutePath = findSourceRootSync(absolutePath);
      } else {
        requireString = name;
      }
      return {
        requireString: requireString,
        absolutePath: absolutePath
      };
    };
 
    ModuleResolver.findModuleSync = function(moduleName, options) {
      var absolutePath, base, denormalizedBase, j, len, matchingName, mod, modulePathArray, out, ref2, ref3, requireString, sub;
      if (/\//.test(moduleName)) {
        ref2 = (function() {
          var j, len, ref2, ref3, results;
          ref3 = (ref2 = moduleName.split("/"), denormalizedBase = ref2[0], ref2);
          results = [];
          for (j = 0, len = ref3.length; j < len; j++) {
            mod = ref3[j];
            out = normalizeName(mod);
            results.push(out);
          }
          return results;
        })(), base = ref2[0], modulePathArray = 2 <= ref2.length ? slice.call(ref2, 1) : [];
      } else {
        denormalizedBase = moduleName;
      }
      ref3 = ModuleResolver._findModuleBaseSync(denormalizedBase, modulePathArray, options), requireString = ref3.requireString, absolutePath = ref3.absolutePath;
      if (modulePathArray) {
        for (j = 0, len = modulePathArray.length; j < len; j++) {
          sub = modulePathArray[j];
          Eif (matchingName = ModuleResolver._matchingNameInDirectorySync(sub, absolutePath, options)) {
            absolutePath = Path.join(absolutePath, matchingName);
            requireString = requireString + "/" + matchingName;
          } else {
            throw new ErrorWithInfo("Could not find pathed submodule inside npm package: " + requireString, {
              npmPackage: requireString,
              localNpmPackageLocation: absolutePath,
              submodulePath: sub,
              normalized: normalizeName(sub),
              dirItems: dirReader.read(absolutePath)
            });
          }
        }
      }
      return {
        requireString: requireString,
        absolutePath: absolutePath
      };
    };
 
    ModuleResolver.findModule = function(moduleName, options) {
      return Promise.then(function() {
        return ModuleResolver.findModuleSync(moduleName, options);
      });
    };
 
    maybeCouldHaveCached = {};
 
    ModuleResolver._findModuleBaseSync = function(moduleBaseName, modulePathArray, options) {
      var absolutePath, absoluteSourceFilePath, directory, e, matchingName, normalizedModuleName, requireString, shouldContinue, sourceDir, sourceFile, sourceFiles, sourceRoot;
      normalizedModuleName = upperCamelCase(moduleBaseName);
      if (options) {
        sourceFile = options.sourceFile, sourceDir = options.sourceDir, sourceFiles = options.sourceFiles, sourceRoot = options.sourceRoot;
      }
      sourceFile || (sourceFile = sourceFiles != null ? sourceFiles[0] : void 0);
      if (sourceFile || sourceDir) {
        directory = sourceDir = dirReader.resolve(sourceDir || Path.dirname(sourceFile));
        sourceRoot || (sourceRoot = findSourceRootSync(sourceDir));
        sourceRoot = sourceRoot && dirReader.resolve(sourceRoot);
        absoluteSourceFilePath = sourceFile && Path.join(sourceDir, Path.parse(sourceFile).name);
      }
      absolutePath = null;
      shouldContinue = present(sourceRoot);
      while (shouldContinue) {
        if ((matchingName = ModuleResolver._matchingNameInDirectorySync(normalizedModuleName, directory, options)) && absoluteSourceFilePath !== (absolutePath = Path.join(directory, matchingName))) {
          shouldContinue = false;
        } else {
          absolutePath = null;
          if (directory === sourceRoot) {
            if (normalizedModuleName === normalizeName(peek(sourceRoot.split("/")))) {
              absolutePath = sourceRoot;
            }
            shouldContinue = false;
          } else {
            directory = Path.dirname(directory);
          }
        }
      }
      if (absolutePath) {
        requireString = Path.relative(sourceDir, absolutePath);
        switch (requireString) {
          case "..":
          case ".":
            requireString = requireString + "/";
        }
        if (!requireString.match(/^\./)) {
          requireString = "./" + requireString;
        }
        return {
          requireString: requireString,
          absolutePath: absolutePath
        };
      } else {
        try {
          return ModuleResolver.getNpmPackageName(moduleBaseName, modulePathArray);
        } catch (error) {
          e = error;
          Eif (e.info) {
            mergeInto(e.info, {
              sourceDir: sourceDir,
              sourceRoot: sourceRoot
            });
          }
          throw e;
        }
      }
    };
 
 
    /*
    Notes about "." names-with-dots.
    
      Essentially, dots are treated as word-boundaries.
    
      Files:
        We need to manage extensions. Current rule:
          Full match example: FooCaf matches foo.caf
          PartialMatch must fully match on dot-boundaries:
            Foo.BarFood.caf does NOT match FooBar, but does match FooBarFood
          PartialMatch must match starting at the first character:
            Foo.BarFood.caf does NOT match BarFood but does match Foo
    
      Dirs:
        Dirs must fully match:
          Art.Foo.Bar matches ArtFooBar BUT NOT ArtFoo
    
    Future:
      I'd like to be able to treat "."s in dir-names as-if they were '/' (slashes)
      Basically, this parallels how NeptuneNamespaces interprets them.
      It should work identically to as-if there were nested dirs.
    
      Given these files:
    
        MyFile1.caf
        Foo/Bar/MyFile2.caf
    
      OR these files:
    
        MyFile1.caf
        Foo.Bar/MyFile2.caf
    
      Then:
         * inside MyFile1.caf
         * this works:
        &Foo/Bar/MyFile2
     */
 
    ModuleResolver.getMatchingName = getMatchingName = function(normalizedModuleName, name, isDir) {
      var foundLegalStop, i, j, len, normalizedTestName, offset, ref2, stop, stops;
      if (normalizedModuleName === (normalizedTestName = normalizeName(name))) {
        return name;
      } else if (!isDir) {
        if (0 === normalizedTestName.indexOf(normalizedModuleName)) {
          foundLegalStop = false;
          offset = 0;
          ref2 = stops = name.split('.');
          for (i = j = 0, len = ref2.length; j < len; i = ++j) {
            stop = ref2[i];
            stop = normalizeName(stop);
            offset += stop.length;
            if (normalizedModuleName.length === offset) {
              return stops.slice(0, i + 1).join('.');
            }
          }
        }
        return false;
      }
    };
 
    ModuleResolver._matchingNameInDirectorySync = function(normalizedModuleName, directory, options) {
      var j, len, matchingName, name, newMatchingName, ref2;
      matchingName = null;
      ref2 = dirReader.read(directory);
      for (j = 0, len = ref2.length; j < len; j++) {
        name = ref2[j];
        if (newMatchingName = getMatchingName(normalizedModuleName, name, dirReader.isDir(Path.join(directory, name)))) {
          Iif (matchingName && matchingName !== newMatchingName) {
            throw new ErrorWithInfo("More than one matching module name with\na) different actual base-names (" + matchingName + " != " + newMatchingName + ") and\nb) for the same normalized name (" + normalizedModuleName + ")", {
              directory: directory,
              firstMatch: matchingName,
              secondMatch: newMatchingName,
              normalizedModuleName: normalizedModuleName
            });
          }
          matchingName = newMatchingName;
        }
      }
      return matchingName;
    };
 
    return ModuleResolver;
 
  })());
 
}).call(this);