All files link-replacer.js

96.55% Statements 84/87
75% Branches 39/52
100% Functions 16/16
96.47% Lines 82/85

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 1721x 1x   1x       1x     39x     39x   1x   33x 33x 21x                   33x 33x 33x 33x 21x   12x     3x 3x 3x 3x 3x 3x 3x   3x     16x 16x 16x 1x 1x   16x 18x 2x   18x         18x 18x 17x   17x   1x           6x 6x 56x 48x   8x 8x 8x 6x 6x 6x   2x 2x 2x           6x       9x         9x   9x 1x         9x 3x 3x 3x 3x     9x 1x 1x 1x         9x 2x 2x 2x 2x     9x 2x 2x 2x 2x 2x                                         9x 1x 1x 1x 1x     9x      
const cheerio = require('cheerio');
const csstree = require('css-tree');
// const { URL } = require('url');
const Generator = require('./dom-link-renamer');
 
// let generator;
 
const CSS_REPLACE_RE = /url\(['"]?(?!["']?data)(.+?)['"]?\)/g;
 
function makeUrl(url, baseUrl) {
  Iif (baseUrl && (baseUrl.indexOf('blob:') === 0 || url.indexOf('blob:') === 0)) {
    return url;
  }
  return new URL(url, baseUrl).toString();
}
module.exports = {
  html(domBuffer, resourcesMap, baseUrl) {
    const gotString = typeof domBuffer === 'string';
    if (gotString) {
      domBuffer = Buffer.from(domBuffer);
    }
    // if (generator) {
    //   generator.reset(domBuffer, resourcesMap, baseUrl);
    // } else {
    //   generator = new Generator(domBuffer, resourcesMap, baseUrl);
    //   generator.cssProcessor = module.exports.css;
    // }
 
    // new generator instead of resusing because of function's recursive calls
    const generator = new Generator(domBuffer, resourcesMap, baseUrl);
    generator.cssProcessor = module.exports.css;
    generator.parse();
    if (gotString) {
      return generator.result().toString();
    }
    return generator.result().slice();
  },
  svg(svgString, resourcesMap, baseUrl) {
    const $ = cheerio.load(svgString, { xmlMode: true });
    $('[href],[xlink\\:href]').each((i, el) => {
      el = $(el);
      const link = makeUrl(el.attr('href') || el.attr('xlink:href'), baseUrl);
      const mapped = resourcesMap.get(link) || link;
      el.removeAttr('xlink:href');
      el.attr('href', mapped);
    });
    return $.html();
  },
  css(cssString, resourcesMap, baseUrl, inAttribute = false) {
    let start = "url('";
    let end = "')";
    if (inAttribute) {
      start = 'url("';
      end = '")';
    }
    return cssString.toString().replace(CSS_REPLACE_RE, (whole, match) => {
      if (match.charAt(0) === '/' && match.charAt(1) === '/') { // protocol agnostic URL
        match = `http:${match}`;
      }
      Iif (match.charAt(0) === '&') {
        if (match.indexOf('"') === 0 && match.indexOf('"', 1) !== -1) {
          match = match.slice(6, match.length - 6);
        }
      }
      try {
        const link = makeUrl(match, baseUrl);
        const mapped = resourcesMap.get(link) || link;
        /* eslint-disable prefer-template */ // hot point
        return start + mapped + end;
      } catch (e) {
        return whole;
      }
    });
  },
  cssWithAst(cssString, resourcesMap, baseUrl) {
    // currently 2x times slower than the RE
    const ast = csstree.parse(cssString, { parseRulePrelude: false });
    csstree.walk(ast, function walker(node) {
      if (this.declaration === null || node.type !== 'Url') {
        return;
      }
      const { value } = node;
      try {
        if (value.type === 'Raw') {
          const link = makeUrl(value.value, baseUrl);
          const mapped = resourcesMap.get(link) || link;
          value.value = `'${mapped}'`;
        } else {
          const link = makeUrl(value.value.substr(1, value.value.length - 2), baseUrl);
          const mapped = resourcesMap.get(link) || link;
          value.value = `'${mapped}'`;
        }
      } catch (e) {
        // ignore unable to map
      }
    });
    return csstree.generate(ast);
  },
  htmlWithCheerio(domBuffer, resourcesMap, baseUrl) {
    // slower and currently unused with Cheerio which is way more allocation happy
    const $ = cheerio.load(domBuffer.toString(), {
      _useHtmlParser2: true, // cheerio 1 uses parse5 by default which is half the speed
      lowerCaseTags: false,
    });
 
    const pageBase = $('base[href]').attr('href');
 
    if (pageBase) {
      baseUrl = makeUrl(pageBase, baseUrl);
    }
 
    // img, picture, audio, video, script, source, iframe
 
    $('[src]').each((i, el) => {
      el = $(el);
      const link = makeUrl(el.attr('src'), baseUrl);
      const mapped = resourcesMap.get(link) || link;
      el.attr('src', mapped);
    });
 
    $('[srcset]').each((i, el) => {
      el = $(el);
      const sources = el.attr('srcset').split(' ');
      el.attr('srcset', sources.map((src) => makeUrl(src, baseUrl)).map((m) => resourcesMap.get(m) || m));
    });
 
    // css imports and link rel prefetch/prerender
 
    $('link[href]').each((i, el) => {
      el = $(el);
      const link = makeUrl(el.attr('href'), baseUrl);
      const mapped = resourcesMap.get(link) || link;
      el.attr('href', mapped);
    });
 
    $('svg').find('[href],[xlink\\:href]').each((i, el) => {
      el = $(el);
      const link = makeUrl(el.attr('href') || el.attr('xlink:href'), baseUrl);
      const mapped = resourcesMap.get(link) || link;
      el.removeAttr('xlink:href');
      el.attr('href', mapped);
    });
 
    // old and deprecated stuff, skipped
 
    // $('meta[http-equiv=refresh]').each((i, el) => {
    //   el = $(el);
    //   const re = /(\d)+; ?URL='?([^']*)'?/gi;
    //   const [, seconds, url] = re.exec(el.attr('content'));
    //   const link = new URL(url, baseUrl).toString();
    //   const mapped = resourcesMap.get(link) || link;
    //   el.attr('content', `${seconds}; url=${mapped}`);
    // });
 
    // $('object[data]').each((i, el) => {
    //   el = $(el);
    //   const link = new URL(el.attr('data'), baseUrl).toString();
    //   const mapped = resourcesMap.get(link) || link;
    //   el.attr('data', mapped);
    // });
 
    $('applet[code]').each((i, el) => {
      el = $(el);
      const link = makeUrl(el.attr('code'), baseUrl);
      const mapped = resourcesMap.get(link) || link;
      el.attr('code', mapped);
    });
 
    return $.html();
  },
};