"use strict"; /* TODO: Separate out into module (that can take either a Cheerio instance or a HTML string) */ const rewriteCssUrls = require("rewrite-css-urls"); module.exports = function ($, rewriteUrl) { function rewriteCss(css) { return rewriteCssUrls.findAndReplace(css, { replaceUrl: (ref) => rewriteUrl(ref.url) }); } function patchAttribute(elements, attribute) { elements.get().forEach((element) => { let $element = $(element); let value = $element.attr(attribute); if (value != null) { $element.attr(attribute, rewriteUrl(value)); } }); } patchAttribute($("a"), "href"); patchAttribute($("img"), "src"); patchAttribute($("link"), "href"); patchAttribute($("script"), "src"); patchAttribute($("form"), "action"); patchAttribute($("iframe"), "src"); $("style").get().forEach((element) => { let $element = $(element); $element.text(rewriteCss($element.text())); }); $("*[style]").get().forEach((element) => { let $element = $(element); $element.attr("style", rewriteCss($element.attr("style"))); }); return $; };