all files / broccoli-asset-rewrite/ index.js

100% Statements 81/81
91.49% Branches 43/47
100% Functions 12/12
100% Lines 81/81
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   194×     194× 194×     194×   194× 194×                             21×   21×                 22×     22×   28× 28×                   22×     21×     194×                                       194× 194×         194×   194× 30× 30×     28×   24×     28×   194× 194×         21×   21× 97×   97×         97×           97× 97×   97× 16×     97×       21×       58× 47×     11×     10×         610×      
var Filter = require('broccoli-filter');
var path = require('path');
var Cache = require('broccoli-filter/lib/cache');
 
function normalize(str) {
  return str.replace(/[\\\/]+/g, '/');
}
 
function relative(a, b) {
  Eif (/\./.test(path.basename(a))) {
    a = path.dirname(a);
  }
 
  var relativePath = path.relative(a, b);
  // path.relative might have added back \-s on windows
  relativePath = normalize(relativePath);
  return relativePath.charAt(0) !== '.' ? './' + relativePath : relativePath;
}
 
function AssetRewrite(inputNode, options) {
  if (!(this instanceof AssetRewrite)) {
    return new AssetRewrite(inputNode, options);
  }
 
  options = options || {};
 
  Filter.call(this, inputNode, {
    extensions: options.replaceExtensions || ['html', 'css'],
    // We should drop support for `description` in the next major release
    annotation: options.description || options.annotation
  });
 
  this.assetMap = options.assetMap || {};
  this.prepend = options.prepend || '';
  this.ignore = options.ignore || []; // files to ignore
 
  this.assetMapKeys = null;
}
 
AssetRewrite.prototype = Object.create(Filter.prototype);
AssetRewrite.prototype.constructor = AssetRewrite;
 
AssetRewrite.prototype.processAndCacheFile = function (srcDir, destDir, relativePath) {
  this._cache = new Cache();
 
  return Filter.prototype.processAndCacheFile.apply(this, arguments);
}
 
/**
 * Checks that file is not being ignored and destination doesn't already have a file
 * @param relativePath
 * @returns {boolean}
 */
 
AssetRewrite.prototype.canProcessFile = function(relativePath) {
  if (!this.assetMapKeys) {
    this.generateAssetMapKeys();
  }
 
  if (!this.inverseAssetMap) {
    var inverseAssetMap = {};
    var assetMap = this.assetMap;
 
    Object.keys(assetMap).forEach(function(key) {
      var value = assetMap[key];
      inverseAssetMap[value] = key;
    }, this);
 
    this.inverseAssetMap = inverseAssetMap;
  }
 
  /*
   * relativePath can be fingerprinted or not.
   * Check that neither of these variations are being ignored
   */
 
  if (this.ignore.indexOf(relativePath) !== -1 || this.ignore.indexOf(this.inverseAssetMap[relativePath]) !== -1) {
    return false;
  }
 
  return Filter.prototype.canProcessFile.apply(this, arguments);
}
 
AssetRewrite.prototype.rewriteAssetPath = function (string, assetPath, replacementPath) {
  var newString = string;
 
  /*
   * Replace all of the assets with their new fingerprint name
   *
   * Uses a regular expression to find assets in html tags, css backgrounds, handlebars pre-compiled templates, etc.
   *
   * ["\'\\(=]{1} - Match one of "'(= exactly one time
   * \\s* - Any amount of white space
   * ( - Starts the first pattern match
   * [^"\'\\(\\)=]* - Do not match any of ^"'()= 0 or more times
   * /([.*+?^=!:${}()|\[\]\/\\])/g - Replace .*+?^=!:${}()|[]/\ in filenames with an escaped version for an exact name match
   * [^"\'\\(\\)\\\\>=]* - Do not match any of ^"'()\>= 0 or more times - Explicitly add \ here because of handlebars compilation
   * ) - End first pattern match
   * \\s* - Any amount of white space
   * [\\\\]* - Allow any amount of \ - For handlebars compilation (includes \\\)
   * \\s* - Any amount of white space
   * ["\'\\)> ]{1} - Match one of "'( > exactly one time
   */
 
  var re = new RegExp('["\'\\(=]{1}\\s*([^"\'\\(\\)=]*' + escapeRegExp(assetPath) + '[^"\'\\(\\)\\\\>=]*)\\s*[\\\\]*\\s*["\'\\)> ]{1}', 'g');
  var match = null;
  /*
   * This is to ignore matches that should not be changed
   * Any URL encoded match that would be ignored above will be ignored by this: "'()=\
   */
  var ignoreLibraryCode = new RegExp('(%22|%27|%5C|%28|%29|%3D)[^"\'\\(\\)=]*' + escapeRegExp(assetPath));
 
  while (match = re.exec(newString)) {
    var replaceString = '';
    if (ignoreLibraryCode.exec(match[1])) {
      continue;
    }
 
    if (this.prepend && this.prepend !== '') {
      replaceString = this.prepend + replacementPath;
    } else {
      replaceString = match[1].replace(assetPath, replacementPath);
    }
 
    newString = newString.replace(new RegExp(escapeRegExp(match[1]), 'g'), replaceString);
  }
  var self = this;
  return newString.replace(new RegExp('sourceMappingURL=' + escapeRegExp(assetPath)), function(wholeMatch) {
    var replaceString = replacementPath;
    if (self.prepend && self.prepend !== '' && (!/^sourceMappingURL=(http|https|\/\/)/.test(wholeMatch))) {
      replaceString = self.prepend + replacementPath;
    }
    return wholeMatch.replace(assetPath, replaceString);
  });
};
 
AssetRewrite.prototype.processString = function (string, relativePath) {
  var newString = string;
 
  for (var i = 0, keyLength = this.assetMapKeys.length; i < keyLength; i++) {
    var key = this.assetMapKeys[i];
 
    Eif (this.assetMap.hasOwnProperty(key)) {
      /*
       * Rewrite absolute URLs
       */
 
      newString = this.rewriteAssetPath(newString, key, this.assetMap[key]);
 
      /*
       * Rewrite relative URLs. If there is a prepend, use the full absolute path.
       */
 
      var pathDiff = relative(relativePath, key).replace(/^\.\//, "");
      var replacementDiff = relative(relativePath, this.assetMap[key]).replace(/^\.\//, "");
 
      if (this.prepend && this.prepend !== '') {
        replacementDiff = this.assetMap[key];
      }
 
      newString = this.rewriteAssetPath(newString, pathDiff, replacementDiff);
    }
  }
 
  return newString;
};
 
AssetRewrite.prototype.generateAssetMapKeys = function () {
  var keys = Object.keys(this.assetMap);
 
  keys.sort(function (a, b) {
    if (a.length < b.length) {
      return 1;
    }
 
    if (a.length > b.length) {
      return -1;
    }
 
    return 0;
  });
 
  this.assetMapKeys = keys;
};
 
function escapeRegExp(string) {
  return string.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
}
 
module.exports = AssetRewrite;