htmlnano 2.0.2 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +2 -2
  3. package/docs/docs/010-introduction.md +4 -4
  4. package/docs/docs/020-usage.md +63 -23
  5. package/docs/docs/030-config.md +1 -1
  6. package/docs/docs/050-modules.md +500 -483
  7. package/docs/package-lock.json +289 -95
  8. package/docs/versioned_docs/version-1.1.1/010-introduction.md +4 -4
  9. package/docs/versioned_docs/version-1.1.1/030-config.md +1 -1
  10. package/docs/versioned_docs/version-2.0.0/010-introduction.md +4 -4
  11. package/docs/versioned_docs/version-2.0.0/030-config.md +2 -2
  12. package/index.d.ts +93 -0
  13. package/lib/helpers.js +4 -11
  14. package/lib/htmlnano.js +11 -36
  15. package/lib/modules/collapseAttributeWhitespace.js +11 -12
  16. package/lib/modules/collapseBooleanAttributes.js +33 -9
  17. package/lib/modules/collapseWhitespace.js +17 -19
  18. package/lib/modules/custom.js +0 -3
  19. package/lib/modules/deduplicateAttributeValues.js +3 -5
  20. package/lib/modules/mergeScripts.js +0 -11
  21. package/lib/modules/mergeStyles.js +2 -8
  22. package/lib/modules/minifyConditionalComments.js +4 -15
  23. package/lib/modules/minifyCss.js +5 -16
  24. package/lib/modules/minifyJs.js +8 -28
  25. package/lib/modules/minifyJson.js +2 -3
  26. package/lib/modules/minifySvg.js +13 -5
  27. package/lib/modules/minifyUrls.js +18 -34
  28. package/lib/modules/normalizeAttributeValues.js +85 -2
  29. package/lib/modules/removeAttributeQuotes.js +0 -2
  30. package/lib/modules/removeComments.js +10 -28
  31. package/lib/modules/removeEmptyAttributes.js +6 -6
  32. package/lib/modules/removeOptionalTags.js +9 -46
  33. package/lib/modules/removeRedundantAttributes.js +20 -68
  34. package/lib/modules/removeUnusedCss.js +7 -18
  35. package/lib/modules/sortAttributes.js +10 -25
  36. package/lib/modules/sortAttributesWithLists.js +7 -29
  37. package/lib/presets/ampSafe.js +2 -5
  38. package/lib/presets/max.js +2 -5
  39. package/lib/presets/safe.js +32 -15
  40. package/package.json +9 -15
  41. package/test.js +0 -48
@@ -4,9 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.onAttrs = onAttrs;
7
-
8
7
  var _collapseAttributeWhitespace = require("./collapseAttributeWhitespace");
9
-
10
8
  /** Deduplicate values inside list-like attributes (e.g. class, rel) */
11
9
  function onAttrs() {
12
10
  return attrs => {
@@ -15,7 +13,9 @@ function onAttrs() {
15
13
  if (!_collapseAttributeWhitespace.attributesWithLists.has(attrName)) {
16
14
  return;
17
15
  }
18
-
16
+ if (typeof attrs[attrName] !== 'string') {
17
+ return;
18
+ }
19
19
  const attrValues = attrs[attrName].split(/\s/);
20
20
  const uniqeAttrValues = new Set();
21
21
  const deduplicatedAttrValues = [];
@@ -25,11 +25,9 @@ function onAttrs() {
25
25
  deduplicatedAttrValues.push('');
26
26
  return;
27
27
  }
28
-
29
28
  if (uniqeAttrValues.has(attrValue)) {
30
29
  return;
31
30
  }
32
-
33
31
  deduplicatedAttrValues.push(attrValue);
34
32
  uniqeAttrValues.add(attrValue);
35
33
  });
@@ -4,7 +4,6 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = mergeScripts;
7
-
8
7
  /* Merge multiple <script> into one */
9
8
  function mergeScripts(tree) {
10
9
  let scriptNodesIndex = {};
@@ -13,18 +12,14 @@ function mergeScripts(tree) {
13
12
  tag: 'script'
14
13
  }, node => {
15
14
  const nodeAttrs = node.attrs || {};
16
-
17
15
  if (nodeAttrs.src) {
18
16
  scriptSrcIndex++;
19
17
  return node;
20
18
  }
21
-
22
19
  const scriptType = nodeAttrs.type || 'text/javascript';
23
-
24
20
  if (scriptType !== 'text/javascript' && scriptType !== 'application/javascript') {
25
21
  return node;
26
22
  }
27
-
28
23
  const scriptKey = JSON.stringify({
29
24
  id: nodeAttrs.id,
30
25
  class: nodeAttrs.class,
@@ -33,31 +28,25 @@ function mergeScripts(tree) {
33
28
  async: nodeAttrs.async !== undefined,
34
29
  index: scriptSrcIndex
35
30
  });
36
-
37
31
  if (!scriptNodesIndex[scriptKey]) {
38
32
  scriptNodesIndex[scriptKey] = [];
39
33
  }
40
-
41
34
  scriptNodesIndex[scriptKey].push(node);
42
35
  return node;
43
36
  });
44
-
45
37
  for (const scriptNodes of Object.values(scriptNodesIndex)) {
46
38
  let lastScriptNode = scriptNodes.pop();
47
39
  scriptNodes.reverse().forEach(scriptNode => {
48
40
  let scriptContent = (scriptNode.content || []).join(' ');
49
41
  scriptContent = scriptContent.trim();
50
-
51
42
  if (scriptContent.slice(-1) !== ';') {
52
43
  scriptContent += ';';
53
44
  }
54
-
55
45
  lastScriptNode.content = lastScriptNode.content || [];
56
46
  lastScriptNode.content.unshift(scriptContent);
57
47
  scriptNode.tag = false;
58
48
  scriptNode.content = [];
59
49
  });
60
50
  }
61
-
62
51
  return tree;
63
52
  }
@@ -4,36 +4,30 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = mergeStyles;
7
-
8
7
  var _helpers = require("../helpers");
9
-
10
8
  /* Merge multiple <style> into one */
11
9
  function mergeStyles(tree) {
12
10
  const styleNodes = {};
13
11
  tree.match({
14
12
  tag: 'style'
15
13
  }, node => {
16
- const nodeAttrs = node.attrs || {}; // Skip <style scoped></style>
14
+ const nodeAttrs = node.attrs || {};
15
+ // Skip <style scoped></style>
17
16
  // https://developer.mozilla.org/en/docs/Web/HTML/Element/style
18
-
19
17
  if (nodeAttrs.scoped !== undefined) {
20
18
  return node;
21
19
  }
22
-
23
20
  if ((0, _helpers.isAmpBoilerplate)(node)) {
24
21
  return node;
25
22
  }
26
-
27
23
  const styleType = nodeAttrs.type || 'text/css';
28
24
  const styleMedia = nodeAttrs.media || 'all';
29
25
  const styleKey = styleType + '_' + styleMedia;
30
-
31
26
  if (styleNodes[styleKey]) {
32
27
  const styleContent = (node.content || []).join(' ');
33
28
  styleNodes[styleKey].content.push(' ' + styleContent);
34
29
  return '';
35
30
  }
36
-
37
31
  node.content = node.content || [];
38
32
  styleNodes[styleKey] = node;
39
33
  return node;
@@ -4,55 +4,44 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = minifyConditionalComments;
7
-
8
7
  var _htmlnano = _interopRequireDefault(require("../htmlnano"));
9
-
10
8
  var _helpers = require("../helpers");
11
-
12
9
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
-
14
10
  // Spec: https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/ms537512(v=vs.85)
15
11
  const CONDITIONAL_COMMENT_REGEXP = /(<!--\[if\s+?[^<>[\]]+?]>)([\s\S]+?)(<!\[endif\]-->)/gm;
16
- /** Minify content inside conditional comments */
17
12
 
13
+ /** Minify content inside conditional comments */
18
14
  async function minifyConditionalComments(tree, htmlnanoOptions) {
19
15
  // forEach, tree.walk, tree.match just don't support Promise.
20
16
  for (let i = 0, len = tree.length; i < len; i++) {
21
17
  const node = tree[i];
22
-
23
18
  if (typeof node === 'string' && (0, _helpers.isConditionalComment)(node)) {
24
19
  tree[i] = await minifycontentInsideConditionalComments(node, htmlnanoOptions);
25
20
  }
26
-
27
21
  if (node.content && node.content.length) {
28
22
  tree[i].content = await minifyConditionalComments(node.content, htmlnanoOptions);
29
23
  }
30
24
  }
31
-
32
25
  return tree;
33
26
  }
34
-
35
27
  async function minifycontentInsideConditionalComments(text, htmlnanoOptions) {
36
28
  let match;
37
- const matches = []; // FIXME!
38
- // String#matchAll is supported since Node.js 12
29
+ const matches = [];
39
30
 
31
+ // FIXME!
32
+ // String#matchAll is supported since Node.js 12
40
33
  while ((match = CONDITIONAL_COMMENT_REGEXP.exec(text)) !== null) {
41
34
  matches.push([match[1], match[2], match[3]]);
42
35
  }
43
-
44
36
  if (!matches.length) {
45
37
  return Promise.resolve(text);
46
38
  }
47
-
48
39
  return Promise.all(matches.map(async match => {
49
40
  const result = await _htmlnano.default.process(match[1], htmlnanoOptions, {}, {});
50
41
  let minified = result.html;
51
-
52
42
  if (match[1].includes('<html') && minified.includes('</html>')) {
53
43
  minified = minified.replace('</html>', '');
54
44
  }
55
-
56
45
  return match[0] + minified + match[2];
57
46
  }));
58
47
  }
@@ -4,9 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = minifyCss;
7
-
8
7
  var _helpers = require("../helpers");
9
-
10
8
  const cssnano = (0, _helpers.optionalRequire)('cssnano');
11
9
  const postcss = (0, _helpers.optionalRequire)('postcss');
12
10
  const postcssOptions = {
@@ -15,13 +13,12 @@ const postcssOptions = {
15
13
  // > Set it to CSS file path or to `undefined` to prevent this warning.
16
14
  from: undefined
17
15
  };
18
- /** Minify CSS with cssnano */
19
16
 
17
+ /** Minify CSS with cssnano */
20
18
  function minifyCss(tree, options, cssnanoOptions) {
21
19
  if (!cssnano || !postcss) {
22
20
  return tree;
23
21
  }
24
-
25
22
  let promises = [];
26
23
  tree.walk(node => {
27
24
  if ((0, _helpers.isStyleNode)(node)) {
@@ -29,32 +26,27 @@ function minifyCss(tree, options, cssnanoOptions) {
29
26
  } else if (node.attrs && node.attrs.style) {
30
27
  promises.push(processStyleAttr(node, cssnanoOptions));
31
28
  }
32
-
33
29
  return node;
34
30
  });
35
31
  return Promise.all(promises).then(() => tree);
36
32
  }
37
-
38
33
  function processStyleNode(styleNode, cssnanoOptions) {
39
- let css = (0, _helpers.extractCssFromStyleNode)(styleNode); // Improve performance by avoiding calling stripCdata again and again
34
+ let css = (0, _helpers.extractCssFromStyleNode)(styleNode);
40
35
 
36
+ // Improve performance by avoiding calling stripCdata again and again
41
37
  let isCdataWrapped = false;
42
-
43
38
  if (css.includes('CDATA')) {
44
39
  const strippedCss = stripCdata(css);
45
40
  isCdataWrapped = css !== strippedCss;
46
41
  css = strippedCss;
47
42
  }
48
-
49
43
  return postcss([cssnano(cssnanoOptions)]).process(css, postcssOptions).then(result => {
50
44
  if (isCdataWrapped) {
51
45
  return styleNode.content = ['<![CDATA[' + result + ']]>'];
52
46
  }
53
-
54
47
  return styleNode.content = [result.css];
55
48
  });
56
49
  }
57
-
58
50
  function processStyleAttr(node, cssnanoOptions) {
59
51
  // CSS "color: red;" is invalid. Therefore it should be wrapped inside some selector:
60
52
  // a{color: red;}
@@ -62,19 +54,16 @@ function processStyleAttr(node, cssnanoOptions) {
62
54
  const wrapperEnd = '}';
63
55
  const wrappedStyle = wrapperStart + (node.attrs.style || '') + wrapperEnd;
64
56
  return postcss([cssnano(cssnanoOptions)]).process(wrappedStyle, postcssOptions).then(result => {
65
- const minifiedCss = result.css; // Remove wrapperStart at the start and wrapperEnd at the end of minifiedCss
66
-
57
+ const minifiedCss = result.css;
58
+ // Remove wrapperStart at the start and wrapperEnd at the end of minifiedCss
67
59
  node.attrs.style = minifiedCss.substring(wrapperStart.length, minifiedCss.length - wrapperEnd.length);
68
60
  });
69
61
  }
70
-
71
62
  function stripCdata(css) {
72
63
  const leftStrippedCss = css.replace('<![CDATA[', '');
73
-
74
64
  if (leftStrippedCss === css) {
75
65
  return css;
76
66
  }
77
-
78
67
  const strippedCss = leftStrippedCss.replace(']]>', '');
79
68
  return leftStrippedCss === strippedCss ? css : strippedCss;
80
69
  }
@@ -4,14 +4,11 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = minifyJs;
7
-
8
7
  var _helpers = require("../helpers");
9
-
10
8
  var _removeRedundantAttributes = require("./removeRedundantAttributes");
11
-
12
9
  const terser = (0, _helpers.optionalRequire)('terser');
13
- /** Minify JS with Terser */
14
10
 
11
+ /** Minify JS with Terser */
15
12
  function minifyJs(tree, options, terserOptions) {
16
13
  if (!terser) return tree;
17
14
  let promises = [];
@@ -19,81 +16,65 @@ function minifyJs(tree, options, terserOptions) {
19
16
  if (node.tag && node.tag === 'script') {
20
17
  const nodeAttrs = node.attrs || {};
21
18
  const mimeType = nodeAttrs.type || 'text/javascript';
22
-
23
19
  if (_removeRedundantAttributes.redundantScriptTypes.has(mimeType) || mimeType === 'module') {
24
20
  promises.push(processScriptNode(node, terserOptions));
25
21
  }
26
22
  }
27
-
28
23
  if (node.attrs) {
29
24
  promises = promises.concat(processNodeWithOnAttrs(node, terserOptions));
30
25
  }
31
-
32
26
  return node;
33
27
  });
34
28
  return Promise.all(promises).then(() => tree);
35
29
  }
36
-
37
30
  function stripCdata(js) {
38
31
  const leftStrippedJs = js.replace(/\/\/\s*<!\[CDATA\[/, '').replace(/\/\*\s*<!\[CDATA\[\s*\*\//, '');
39
-
40
32
  if (leftStrippedJs === js) {
41
33
  return js;
42
34
  }
43
-
44
35
  const strippedJs = leftStrippedJs.replace(/\/\/\s*\]\]>/, '').replace(/\/\*\s*\]\]>\s*\*\//, '');
45
36
  return leftStrippedJs === strippedJs ? js : strippedJs;
46
37
  }
47
-
48
38
  function processScriptNode(scriptNode, terserOptions) {
49
39
  let js = (scriptNode.content || []).join('').trim();
50
-
51
40
  if (!js) {
52
41
  return scriptNode;
53
- } // Improve performance by avoiding calling stripCdata again and again
54
-
42
+ }
55
43
 
44
+ // Improve performance by avoiding calling stripCdata again and again
56
45
  let isCdataWrapped = false;
57
-
58
46
  if (js.includes('CDATA')) {
59
47
  const strippedJs = stripCdata(js);
60
48
  isCdataWrapped = js !== strippedJs;
61
49
  js = strippedJs;
62
50
  }
63
-
64
51
  return terser.minify(js, terserOptions).then(result => {
65
52
  if (result.error) {
66
53
  throw new Error(result.error);
67
54
  }
68
-
69
55
  if (result.code === undefined) {
70
56
  return;
71
57
  }
72
-
73
58
  let content = result.code;
74
-
75
59
  if (isCdataWrapped) {
76
60
  content = '/*<![CDATA[*/' + content + '/*]]>*/';
77
61
  }
78
-
79
62
  scriptNode.content = [content];
80
63
  });
81
64
  }
82
-
83
65
  function processNodeWithOnAttrs(node, terserOptions) {
84
- const jsWrapperStart = 'function a(){';
85
- const jsWrapperEnd = '}a();';
66
+ const jsWrapperStart = 'a=function(){';
67
+ const jsWrapperEnd = '};a();';
86
68
  const promises = [];
87
-
88
69
  for (const attrName of Object.keys(node.attrs || {})) {
89
70
  if (!(0, _helpers.isEventHandler)(attrName)) {
90
71
  continue;
91
- } // For example onclick="return false" is valid,
72
+ }
73
+
74
+ // For example onclick="return false" is valid,
92
75
  // but "return false;" is invalid (error: 'return' outside of function)
93
76
  // Therefore the attribute's code should be wrapped inside function:
94
77
  // "function _(){return false;}"
95
-
96
-
97
78
  let wrappedJs = jsWrapperStart + node.attrs[attrName] + jsWrapperEnd;
98
79
  let promise = terser.minify(wrappedJs, terserOptions).then(({
99
80
  code
@@ -103,6 +84,5 @@ function processNodeWithOnAttrs(node, terserOptions) {
103
84
  });
104
85
  promises.push(promise);
105
86
  }
106
-
107
87
  return promises;
108
88
  }
@@ -5,17 +5,16 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.onContent = onContent;
7
7
  const rNodeAttrsTypeJson = /(\/|\+)json/;
8
-
9
8
  function onContent() {
10
9
  return (content, node) => {
11
10
  if (node.attrs && node.attrs.type && rNodeAttrsTypeJson.test(node.attrs.type)) {
12
11
  try {
13
12
  // cast minified JSON to an array
14
13
  return [JSON.stringify(JSON.parse((content || []).join('')))];
15
- } catch (error) {// Invalid JSON
14
+ } catch (error) {
15
+ // Invalid JSON
16
16
  }
17
17
  }
18
-
19
18
  return content;
20
19
  };
21
20
  }
@@ -4,12 +4,10 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = minifySvg;
7
-
8
7
  var _helpers = require("../helpers");
9
-
10
8
  const svgo = (0, _helpers.optionalRequire)('svgo');
11
- /** Minify SVG with SVGO */
12
9
 
10
+ /** Minify SVG with SVGO */
13
11
  function minifySvg(tree, options, svgoOptions = {}) {
14
12
  if (!svgo) return tree;
15
13
  tree.match({
@@ -20,9 +18,19 @@ function minifySvg(tree, options, svgoOptions = {}) {
20
18
  quoteAllAttributes: true
21
19
  });
22
20
  const result = svgo.optimize(svgStr, svgoOptions);
23
- node.tag = false;
24
- node.attrs = {}; // result.data is a string, we need to cast it to an array
21
+ if (result.error) {
22
+ console.error('htmlnano fails to minify the svg:');
23
+ console.error(result.error);
24
+ if (result.modernError) {
25
+ console.error(result.modernError);
26
+ }
25
27
 
28
+ // We return the node as-is
29
+ return node;
30
+ }
31
+ node.tag = false;
32
+ node.attrs = {};
33
+ // result.data is a string, we need to cast it to an array
26
34
  node.content = [result.data];
27
35
  return node;
28
36
  });
@@ -4,13 +4,12 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = minifyUrls;
7
-
8
7
  var _helpers = require("../helpers");
9
-
10
8
  const RelateUrl = (0, _helpers.optionalRequire)('relateurl');
11
9
  const srcset = (0, _helpers.optionalRequire)('srcset');
12
- const terser = (0, _helpers.optionalRequire)('terser'); // Adopts from https://github.com/kangax/html-minifier/blob/51ce10f4daedb1de483ffbcccecc41be1c873da2/src/htmlminifier.js#L209-L221
10
+ const terser = (0, _helpers.optionalRequire)('terser');
13
11
 
12
+ // Adopts from https://github.com/kangax/html-minifier/blob/51ce10f4daedb1de483ffbcccecc41be1c873da2/src/htmlminifier.js#L209-L221
14
13
  const tagsHaveUriValuesForAttributes = new Set(['a', 'area', 'link', 'base', 'object', 'blockquote', 'q', 'del', 'ins', 'form', 'input', 'head', 'audio', 'embed', 'iframe', 'img', 'script', 'track', 'video']);
15
14
  const tagsHasHrefAttributes = new Set(['a', 'area', 'link', 'base']);
16
15
  const attributesOfImgTagHasUriValues = new Set(['src', 'longdesc', 'usemap']);
@@ -24,15 +23,12 @@ const tagsHasSrcAttributes = new Set(['audio', 'embed', 'iframe', 'img', 'input'
24
23
  * but technically it does comply with HTML Standard.
25
24
  */
26
25
  'source']);
27
-
28
26
  const isUriTypeAttribute = (tag, attr) => {
29
27
  return tagsHasHrefAttributes.has(tag) && attr === 'href' || tag === 'img' && attributesOfImgTagHasUriValues.has(attr) || tag === 'object' && attributesOfObjectTagHasUriValues.has(attr) || tagsHasCiteAttributes.has(tag) && attr === 'cite' || tag === 'form' && attr === 'action' || tag === 'input' && attr === 'usemap' || tag === 'head' && attr === 'profile' || tag === 'script' && attr === 'for' || tagsHasSrcAttributes.has(tag) && attr === 'src';
30
28
  };
31
-
32
29
  const isSrcsetAttribute = (tag, attr) => {
33
30
  return tag === 'source' && attr === 'srcset' || tag === 'img' && attr === 'srcset' || tag === 'link' && attr === 'imagesrcset';
34
31
  };
35
-
36
32
  const processModuleOptions = options => {
37
33
  // FIXME!
38
34
  // relateurl@1.0.0-alpha only supports URL while stable version (0.2.7) only supports string
@@ -41,57 +37,51 @@ const processModuleOptions = options => {
41
37
  if (options instanceof URL) return options.toString();
42
38
  return false;
43
39
  };
44
-
45
40
  const isLinkRelCanonical = ({
46
41
  tag,
47
42
  attrs
48
43
  }) => {
49
44
  // Return false early for non-"link" tag
50
45
  if (tag !== 'link') return false;
51
-
52
46
  for (const [attrName, attrValue] of Object.entries(attrs)) {
53
47
  if (attrName.toLowerCase() === 'rel' && attrValue === 'canonical') return true;
54
48
  }
55
-
56
49
  return false;
57
50
  };
58
-
59
51
  const JAVASCRIPT_URL_PROTOCOL = 'javascript:';
60
52
  let relateUrlInstance;
61
53
  let STORED_URL_BASE;
62
- /** Convert absolute url into relative url */
63
54
 
55
+ /** Convert absolute url into relative url */
64
56
  function minifyUrls(tree, options, moduleOptions) {
65
57
  let promises = [];
66
- const urlBase = processModuleOptions(moduleOptions); // Invalid configuration, return tree directly
58
+ const urlBase = processModuleOptions(moduleOptions);
67
59
 
60
+ // Invalid configuration, return tree directly
68
61
  if (!urlBase) return tree;
62
+
69
63
  /** Bring up a reusable RelateUrl instances (only once)
70
64
  *
71
65
  * STORED_URL_BASE is used to invalidate RelateUrl instances,
72
66
  * avoiding require.cache acrossing multiple htmlnano instance with different configuration,
73
67
  * e.g. unit tests cases.
74
68
  */
75
-
76
69
  if (!relateUrlInstance || STORED_URL_BASE !== urlBase) {
77
70
  if (RelateUrl) {
78
71
  relateUrlInstance = new RelateUrl(urlBase);
79
72
  }
80
-
81
73
  STORED_URL_BASE = urlBase;
82
74
  }
83
-
84
75
  tree.walk(node => {
85
76
  if (!node.attrs) return node;
86
77
  if (!node.tag) return node;
87
- if (!tagsHaveUriValuesForAttributes.has(node.tag)) return node; // Prevent link[rel=canonical] being processed
88
- // Can't be excluded by isUriTypeAttribute()
78
+ if (!tagsHaveUriValuesForAttributes.has(node.tag)) return node;
89
79
 
80
+ // Prevent link[rel=canonical] being processed
81
+ // Can't be excluded by isUriTypeAttribute()
90
82
  if (isLinkRelCanonical(node)) return node;
91
-
92
83
  for (const [attrName, attrValue] of Object.entries(node.attrs)) {
93
84
  const attrNameLower = attrName.toLowerCase();
94
-
95
85
  if (isUriTypeAttribute(node.tag, attrNameLower)) {
96
86
  if (isJavaScriptUrl(attrValue)) {
97
87
  promises.push(minifyJavaScriptUrl(node, attrName));
@@ -104,55 +94,49 @@ function minifyUrls(tree, options, moduleOptions) {
104
94
  node.attrs[attrName] = relateUrlInstance.relate(attrValue);
105
95
  }
106
96
  }
107
-
108
97
  continue;
109
98
  }
110
-
111
99
  if (isSrcsetAttribute(node.tag, attrNameLower)) {
112
100
  if (srcset) {
113
101
  try {
114
- const parsedSrcset = srcset.parse(attrValue);
102
+ const parsedSrcset = srcset.parse(attrValue, {
103
+ strict: true
104
+ });
115
105
  node.attrs[attrName] = srcset.stringify(parsedSrcset.map(srcset => {
116
106
  if (relateUrlInstance) {
117
107
  srcset.url = relateUrlInstance.relate(srcset.url);
118
108
  }
119
-
120
109
  return srcset;
121
110
  }));
122
- } catch (e) {// srcset will throw an Error for invalid srcset.
111
+ } catch (e) {
112
+ // srcset will throw an Error for invalid srcset.
123
113
  }
124
114
  }
125
-
126
115
  continue;
127
116
  }
128
117
  }
129
-
130
118
  return node;
131
119
  });
132
120
  if (promises.length > 0) return Promise.all(promises).then(() => tree);
133
121
  return Promise.resolve(tree);
134
122
  }
135
-
136
123
  function isJavaScriptUrl(url) {
137
124
  return typeof url === 'string' && url.toLowerCase().startsWith(JAVASCRIPT_URL_PROTOCOL);
138
125
  }
139
-
126
+ const jsWrapperStart = 'function a(){';
127
+ const jsWrapperEnd = '}a();';
140
128
  function minifyJavaScriptUrl(node, attrName) {
141
129
  if (!terser) return Promise.resolve();
142
- const jsWrapperStart = 'function a(){';
143
- const jsWrapperEnd = '}a();';
144
130
  let result = node.attrs[attrName];
145
-
146
131
  if (result) {
147
- result = result.slice(JAVASCRIPT_URL_PROTOCOL.length);
132
+ result = jsWrapperStart + result.slice(JAVASCRIPT_URL_PROTOCOL.length) + jsWrapperEnd;
148
133
  return terser.minify(result, {}) // Default Option is good enough
149
134
  .then(({
150
135
  code
151
136
  }) => {
152
137
  const minifiedJs = code.substring(jsWrapperStart.length, code.length - jsWrapperEnd.length);
153
- node.attrs[attrName] = minifiedJs;
138
+ node.attrs[attrName] = JAVASCRIPT_URL_PROTOCOL + minifiedJs;
154
139
  });
155
140
  }
156
-
157
141
  return Promise.resolve();
158
142
  }