Code coverage report for father/lib/package.js

Statements: 100% (140 / 140)      Branches: 100% (60 / 60)      Functions: 96% (24 / 25)      Lines: 100% (134 / 134)      Ignored: none     

All files » father/lib/ » package.js
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    1 1 1 1 1 1 1 1 1 1 1 1   1                 1                   1         52 51 51 51 51 51 51 51       46 14   32 31         113 28   85 85       3 1   2 2       51 51 357   112 112 14 14 19 19   14   98           357           52 52 52 48     48 48     46 46 46 46       48 48   40 40 30 30   40   48       48 48 48   48   1 90 90 12 12     90 1   89         89 89     89 89 88   1 1       88 88 88 73     73 3       70 38 38 1   37       32 32   17 3 3 3   31       86 128     86   86     86                       1     1 88   65   8   15     1 70         1 48 48     48       48 1       48 16     48   66       1 48   8     1 81 81 162 297     81    
'use strict';
 
var fs = require('fs');
var path = require('path');
var join = path.join;
var dirname = path.dirname;
var extname = path.extname;
var relative = path.relative;
var requires = require('requires');
var imports = require('css-imports');
var Class = require('arale').Class;
var Events = require('arale').Events;
var debug = require('debug')('father:package');
var util = require('./util');
 
var defaults = {
  // config an extension as key, when that extension is found,
  // value will be added to deps
  extraDeps: {},
 
  // another entry point for parse
  entry: []
};
 
var properties = [
  'name',
  'version',
  'main',
  'origin',
  'dependencies',
  'files',
  'output'
];
 
var Package = Class.create({
 
  Implements: [Events],
 
  initialize: function(dir, options) {
    if (!dir) throw new Error('miss the first argument');
    options = extend({}, defaults, options);
    this.father = options.father;
    this.options = options;
    this.dest = dir;
    this._packages = {};
    this._dependencies = [];
    this._exportProperty(properties);
  },
 
  set: function(pkg) {
    if (this.father) {
      return this.father.set(pkg);
    }
    if (!this._packages[pkg.id]) {
      this._packages[pkg.id] = pkg;
    }
  },
 
  get: function(id) {
    if (this.father) {
      return this.father.get(id);
    }
    if (!this._parsed && !this._parsing) this._parse();
    return id === this.id ? this : this._packages[id];
  },
 
  getPackages: function() {
    if (this.father) {
      return this.father.getPackages();
    }
    if (!this._parsed && !this._parsing) this._parse();
    return this._packages;
  },
 
  _exportProperty: function(keys) {
    var that = this;
    keys.forEach(function(key) {
      var prop = {
        get: function() {
          if (!that._parsed && !that._parsing) that._parse();
          if (key === 'dependencies') {
            var deps = {};
            that._dependencies.forEach(function(id) {
              var pkg = that.get(id);
              deps[pkg.name] = pkg;
            });
            return deps;
          } else {
            return that._pkg[key];
          }
        },
        configurable: true
      };
 
      Object.defineProperty(that, key, prop);
    });
  },
 
  _parse: function() {
    // start
    debug('*start parse %s', this.dest);
    this._parsing = true;
    this._pkg = this.readPackage();
    this.id = this._pkg.id;
 
    // parsing
    this._parsePkgDeps();
    this._parseFiles();
 
    // end
    this._parsed = true;
    this._parsing = false;
    debug('* end  parse %s', this.dest);
    return this;
  },
 
  _parsePkgDeps: function() {
    var Self = this.constructor, deps = this._pkg.dependencies;
    Object.keys(deps)
      .forEach(function(name) {
        var sub = deps[name];
        if (!this.get(sub.id)) {
          var opt = extend({}, this.options, {father: this});
          this.set(new Self(sub.dest, opt)._parse());
        }
        this._dependencies.push(sub.id);
      }.bind(this));
    debug('_parsePkgDeps of pkg(%s) [%s]', this.id, Object.keys(deps));
  },
 
  _parseFiles: function() {
    var dest = this.dest, options = this.options;
    var pkg = this._pkg, files = pkg.files = {};
    var extraVal = getExtraVal(options.extraDeps);
 
    getEntry(this, options).forEach(lookupFiles);
 
    function lookupFiles(src, entry) {
      var deps = [], ext = extname(src).substring(1);
      if (!ext) {
        src = src + '.js';
        ext = 'js';
      }
 
      if (files[src]) {
        return files[src].dependencies;
      } else {
        files[src] = {};
      }
 
      // extension in extraDeps will be added to deps
      // E.g. a.handlebars should require `handlebars`
      var extraDeps = options.extraDeps;
      if (extraDeps[ext]) deps.push(extraDeps[ext]);
 
      // file dependencies
      try {
        var data = fs.readFileSync(join(dest, src)).toString();
        deps = deps.concat(getFileDeps(data, ext, options));
      } catch(e) {
        debug('%s not found with err %s', src, e);
        throw new Error(src + ' not found');
      }
 
      // conbime with the dependencies of the dependent file
      var fileDeps = deps;
      deps = [];
      fileDeps.forEach(function(name) {
        deps.push(name);
 
        // ignore extraDeps, E.g. hanldebars
        if (~extraVal.indexOf(name)) {
          return deps.push(name);
        }
 
        // dependent packages
        if (!util.isRelative(name)) {
          var pkg_ = pkg.dependencies[name];
          if (!pkg_) {
            throw new Error(name + ' not found but required');
          }
          return deps.push(name);
        }
 
        // relative files
        name = util.resolvePath(name, src);
        var deps_ = lookupFiles(name, src)
          .map(function(it) {
            if (!util.isRelative(it)) return it;
            it = util.resolvePath(it, name);
            it = relative(dirname(src), it);
            return util.isRelative(it) ? it : './' + it;
          });
        deps = deps.concat(deps_);
      });
 
      // unique
      deps = deps.filter(function(item, index, arr) {
        return index === arr.indexOf(item);
      });
 
      files[src].dependencies = deps;
 
      debug('_parseFiles of pkg(%s): file %s, deps [%s]', pkg.id, src, deps);
 
      // css which is required by js don't return deps
      return extname(entry) === '.js' && ext === 'css' ? [] : deps;
    }
  },
 
  /*
    Method below can be overridden
  */
 
  readPackage: function() {}
 
});
 
module.exports = Package;
 
 
function getFileDeps(code, ext) {
  switch(ext) {
    case 'js':
      return requires(code).map(transform);
    case 'css':
      return imports(code).map(transform);
    default:
      return [];
  }
 
  function transform(item) {
    return item.path.replace(/\.js$/, '');
  }
}
 
// entry point of package
function getEntry(pkg, options) {
  var isFather = !pkg.father;
  pkg = pkg._pkg;
 
  // base on pkg.main
  var entry = [pkg.main];
 
  // base on options.entry
  // only father package will concat this option
  if (isFather && Array.isArray(options.entry) && options.entry.length) {
    entry = entry.concat(options.entry);
  }
 
  // base on pkg.output
  if (Array.isArray(pkg.output) && pkg.output.length) {
    entry = entry.concat(pkg.output);
  }
 
  return entry
    .filter(function(item, index, arr) {
      return index === arr.indexOf(item);
    });
}
 
function getExtraVal(extraDeps) {
  return Object.keys(extraDeps)
    .map(function(key) {
      return extraDeps[key];
    });
}
function extend(target) {
  var args = [].slice.call(arguments, 1);
  args.forEach(function(obj) {
    for (var i in obj) {
      target[i] = obj[i];
    }
  });
  return target;
}