css-fonts-alt-minifier.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global globalThis */
  24. import * as cssTree from "./../vendor/css-tree.js";
  25. import {
  26. normalizeFontFamily,
  27. getFontWeight
  28. } from "./../single-file-helper.js";
  29. const helper = {
  30. normalizeFontFamily,
  31. getFontWeight
  32. };
  33. const FontFace = globalThis.FontFace;
  34. const REGEXP_URL_SIMPLE_QUOTES_FN = /url\s*\(\s*'(.*?)'\s*\)/i;
  35. const REGEXP_URL_DOUBLE_QUOTES_FN = /url\s*\(\s*"(.*?)"\s*\)/i;
  36. const REGEXP_URL_NO_QUOTES_FN = /url\s*\(\s*(.*?)\s*\)/i;
  37. const REGEXP_URL_FUNCTION = /(url|local|-sf-url-original)\(.*?\)\s*(,|$)/g;
  38. const REGEXP_SIMPLE_QUOTES_STRING = /^'(.*?)'$/;
  39. const REGEXP_DOUBLE_QUOTES_STRING = /^"(.*?)"$/;
  40. const REGEXP_URL_FUNCTION_WOFF = /^url\(\s*["']?data:font\/(woff2?)/;
  41. const REGEXP_URL_FUNCTION_WOFF_ALT = /^url\(\s*["']?data:application\/x-font-(woff)/;
  42. const REGEXP_FONT_FORMAT = /\.([^.?#]+)((\?|#).*?)?$/;
  43. const REGEXP_FONT_FORMAT_VALUE = /format\((.*?)\)\s*,?$/;
  44. const REGEXP_FONT_SRC = /(.*?)\s*,?$/;
  45. const EMPTY_URL_SOURCE = /^url\(["']?data:[^,]*,?["']?\)/;
  46. const LOCAL_SOURCE = "local(";
  47. const MEDIA_ALL = "all";
  48. const FONT_STRETCHES = {
  49. "ultra-condensed": "50%",
  50. "extra-condensed": "62.5%",
  51. "condensed": "75%",
  52. "semi-condensed": "87.5%",
  53. "normal": "100%",
  54. "semi-expanded": "112.5%",
  55. "expanded": "125%",
  56. "extra-expanded": "150%",
  57. "ultra-expanded": "200%"
  58. };
  59. const FONT_MAX_LOAD_DELAY = 5000;
  60. export {
  61. process
  62. };
  63. async function process(doc, stylesheets, fontDeclarations, fontTests) {
  64. const fontsDetails = {
  65. fonts: new Map(),
  66. medias: new Map(),
  67. supports: new Map()
  68. };
  69. const stats = { rules: { processed: 0, discarded: 0 }, fonts: { processed: 0, discarded: 0 } };
  70. let sheetIndex = 0;
  71. stylesheets.forEach(stylesheetInfo => {
  72. const cssRules = stylesheetInfo.stylesheet.children;
  73. if (cssRules) {
  74. stats.rules.processed += cssRules.getSize();
  75. stats.rules.discarded += cssRules.getSize();
  76. if (stylesheetInfo.mediaText && stylesheetInfo.mediaText != MEDIA_ALL) {
  77. const mediaFontsDetails = createFontsDetailsInfo();
  78. fontsDetails.medias.set("media-" + sheetIndex + "-" + stylesheetInfo.mediaText, mediaFontsDetails);
  79. getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails);
  80. } else {
  81. getFontsDetails(doc, cssRules, sheetIndex, fontsDetails);
  82. }
  83. }
  84. sheetIndex++;
  85. });
  86. processFontDetails(fontsDetails);
  87. await Promise.all([...stylesheets].map(async ([, stylesheetInfo], sheetIndex) => {
  88. const cssRules = stylesheetInfo.stylesheet.children;
  89. const media = stylesheetInfo.mediaText;
  90. if (cssRules) {
  91. if (media && media != MEDIA_ALL) {
  92. await processFontFaceRules(cssRules, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + media), fontDeclarations, fontTests, stats);
  93. } else {
  94. await processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontDeclarations, fontTests, stats);
  95. }
  96. stats.rules.discarded -= cssRules.getSize();
  97. }
  98. }));
  99. return stats;
  100. }
  101. function getFontsDetails(doc, cssRules, sheetIndex, mediaFontsDetails) {
  102. let mediaIndex = 0, supportsIndex = 0;
  103. cssRules.forEach(ruleData => {
  104. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  105. const mediaText = cssTree.generate(ruleData.prelude);
  106. const fontsDetails = createFontsDetailsInfo();
  107. mediaFontsDetails.medias.set("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText, fontsDetails);
  108. mediaIndex++;
  109. getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
  110. } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  111. const supportsText = cssTree.generate(ruleData.prelude);
  112. const fontsDetails = createFontsDetailsInfo();
  113. mediaFontsDetails.supports.set("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText, fontsDetails);
  114. supportsIndex++;
  115. getFontsDetails(doc, ruleData.block.children, sheetIndex, fontsDetails);
  116. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face" && ruleData.block && ruleData.block.children) {
  117. const fontKey = getFontKey(ruleData);
  118. let fontInfo = mediaFontsDetails.fonts.get(fontKey);
  119. if (!fontInfo) {
  120. fontInfo = [];
  121. mediaFontsDetails.fonts.set(fontKey, fontInfo);
  122. }
  123. const src = getPropertyValue(ruleData, "src");
  124. if (src) {
  125. const fontSources = src.match(REGEXP_URL_FUNCTION);
  126. if (fontSources) {
  127. fontSources.forEach(source => fontInfo.unshift(source));
  128. }
  129. }
  130. }
  131. });
  132. }
  133. function processFontDetails(fontsDetails) {
  134. fontsDetails.fonts.forEach((fontInfo, fontKey) => {
  135. fontsDetails.fonts.set(fontKey, fontInfo.map(fontSource => {
  136. const fontFormatMatch = fontSource.match(REGEXP_FONT_FORMAT_VALUE);
  137. let fontFormat;
  138. const fontUrl = getURL(fontSource);
  139. if (fontFormatMatch && fontFormatMatch[1]) {
  140. fontFormat = fontFormatMatch[1].replace(REGEXP_SIMPLE_QUOTES_STRING, "$1").replace(REGEXP_DOUBLE_QUOTES_STRING, "$1").toLowerCase();
  141. }
  142. if (!fontFormat) {
  143. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF);
  144. if (fontFormatMatch && fontFormatMatch[1]) {
  145. fontFormat = fontFormatMatch[1];
  146. } else {
  147. const fontFormatMatch = fontSource.match(REGEXP_URL_FUNCTION_WOFF_ALT);
  148. if (fontFormatMatch && fontFormatMatch[1]) {
  149. fontFormat = fontFormatMatch[1];
  150. }
  151. }
  152. }
  153. if (!fontFormat && fontUrl) {
  154. const fontFormatMatch = fontUrl.match(REGEXP_FONT_FORMAT);
  155. if (fontFormatMatch && fontFormatMatch[1]) {
  156. fontFormat = fontFormatMatch[1];
  157. }
  158. }
  159. return { src: fontSource.match(REGEXP_FONT_SRC)[1], fontUrl, format: fontFormat };
  160. }));
  161. });
  162. fontsDetails.medias.forEach(mediaFontsDetails => processFontDetails(mediaFontsDetails));
  163. fontsDetails.supports.forEach(supportsFontsDetails => processFontDetails(supportsFontsDetails));
  164. }
  165. async function processFontFaceRules(cssRules, sheetIndex, fontsDetails, fontDeclarations, fontTests, stats) {
  166. const removedRules = [];
  167. let mediaIndex = 0, supportsIndex = 0;
  168. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  169. const ruleData = cssRule.data;
  170. if (ruleData.type == "Atrule" && ruleData.name == "media" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  171. const mediaText = cssTree.generate(ruleData.prelude);
  172. await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.medias.get("media-" + sheetIndex + "-" + mediaIndex + "-" + mediaText), fontDeclarations, fontTests, stats);
  173. mediaIndex++;
  174. } else if (ruleData.type == "Atrule" && ruleData.name == "supports" && ruleData.block && ruleData.block.children && ruleData.prelude) {
  175. const supportsText = cssTree.generate(ruleData.prelude);
  176. await processFontFaceRules(ruleData.block.children, sheetIndex, fontsDetails.supports.get("supports-" + sheetIndex + "-" + supportsIndex + "-" + supportsText), fontDeclarations, fontTests, stats);
  177. supportsIndex++;
  178. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  179. const key = getFontKey(ruleData);
  180. const fontInfo = fontsDetails.fonts.get(key);
  181. if (fontInfo) {
  182. const processed = await processFontFaceRule(ruleData, fontInfo, fontDeclarations, fontTests, stats);
  183. if (processed) {
  184. fontsDetails.fonts.delete(key);
  185. }
  186. } else {
  187. removedRules.push(cssRule);
  188. }
  189. }
  190. }
  191. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  192. }
  193. async function processFontFaceRule(ruleData, fontInfo, fontDeclarations, fontTests, stats) {
  194. const removedNodes = [];
  195. for (let node = ruleData.block.children.head; node; node = node.next) {
  196. if (node.data.property == "src") {
  197. removedNodes.push(node);
  198. }
  199. }
  200. removedNodes.pop();
  201. removedNodes.forEach(node => ruleData.block.children.remove(node));
  202. const srcDeclaration = ruleData.block.children.filter(node => node.property == "src").tail;
  203. if (srcDeclaration) {
  204. await Promise.all(fontInfo.map(async (source, sourceIndex) => {
  205. if (fontTests.has(source.src)) {
  206. source.valid = fontTests.get(source.src);
  207. } else {
  208. if (FontFace) {
  209. const fontFace = new FontFace("test-font", source.src);
  210. try {
  211. let timeout;
  212. await Promise.race([
  213. fontFace.load().then(() => fontFace.loaded).then(() => { source.valid = true; globalThis.clearTimeout(timeout); }),
  214. new Promise(resolve => timeout = globalThis.setTimeout(() => { source.valid = true; resolve(); }, FONT_MAX_LOAD_DELAY))
  215. ]);
  216. } catch (error) {
  217. const declarationFontURLs = fontDeclarations.get(srcDeclaration.data);
  218. if (declarationFontURLs) {
  219. const fontURL = declarationFontURLs[declarationFontURLs.length - sourceIndex - 1];
  220. if (fontURL) {
  221. const fontFace = new FontFace("test-font", "url(" + fontURL + ")");
  222. try {
  223. let timeout;
  224. await Promise.race([
  225. fontFace.load().then(() => fontFace.loaded).then(() => { source.valid = true; globalThis.clearTimeout(timeout); }),
  226. new Promise(resolve => timeout = globalThis.setTimeout(() => { source.valid = true; resolve(); }, FONT_MAX_LOAD_DELAY))
  227. ]);
  228. } catch (error) {
  229. // ignored
  230. }
  231. }
  232. } else {
  233. source.valid = true;
  234. }
  235. }
  236. } else {
  237. source.valid = true;
  238. }
  239. fontTests.set(source.src, source.valid);
  240. }
  241. }));
  242. const findSourceByFormat = (fontFormat, testValidity) => fontInfo.find(source => !source.src.match(EMPTY_URL_SOURCE) && source.format == fontFormat && (!testValidity || source.valid));
  243. const filterSources = fontSource => fontInfo.filter(source => source == fontSource || source.src.startsWith(LOCAL_SOURCE));
  244. stats.fonts.processed += fontInfo.length;
  245. stats.fonts.discarded += fontInfo.length;
  246. const woffFontFound =
  247. findSourceByFormat("woff2-variations", true) || findSourceByFormat("woff2", true) || findSourceByFormat("woff", true);
  248. if (woffFontFound) {
  249. fontInfo = filterSources(woffFontFound);
  250. } else {
  251. const ttfFontFound =
  252. findSourceByFormat("truetype-variations", true) || findSourceByFormat("truetype", true);
  253. if (ttfFontFound) {
  254. fontInfo = filterSources(ttfFontFound);
  255. } else {
  256. const otfFontFound =
  257. findSourceByFormat("opentype") || findSourceByFormat("embedded-opentype");
  258. if (otfFontFound) {
  259. fontInfo = filterSources(otfFontFound);
  260. } else {
  261. fontInfo = fontInfo.filter(source => !source.src.match(EMPTY_URL_SOURCE) && (source.valid) || source.src.startsWith(LOCAL_SOURCE));
  262. }
  263. }
  264. }
  265. stats.fonts.discarded -= fontInfo.length;
  266. fontInfo.reverse();
  267. try {
  268. srcDeclaration.data.value = cssTree.parse(fontInfo.map(fontSource => fontSource.src).join(","), { context: "value" });
  269. }
  270. catch (error) {
  271. // ignored
  272. }
  273. return true;
  274. } else {
  275. return false;
  276. }
  277. }
  278. function getPropertyValue(ruleData, propertyName) {
  279. let property;
  280. if (ruleData.block.children) {
  281. property = ruleData.block.children.filter(node => {
  282. try {
  283. return node.property == propertyName && !cssTree.generate(node.value).match(/\\9$/);
  284. } catch (error) {
  285. return node.property == propertyName;
  286. }
  287. }).tail;
  288. }
  289. if (property) {
  290. try {
  291. return cssTree.generate(property.data.value);
  292. } catch (error) {
  293. // ignored
  294. }
  295. }
  296. }
  297. function getFontKey(ruleData) {
  298. return JSON.stringify([
  299. helper.normalizeFontFamily(getPropertyValue(ruleData, "font-family")),
  300. helper.getFontWeight(getPropertyValue(ruleData, "font-weight") || "400"),
  301. getPropertyValue(ruleData, "font-style") || "normal",
  302. getPropertyValue(ruleData, "unicode-range"),
  303. getFontStretch(getPropertyValue(ruleData, "font-stretch")),
  304. getPropertyValue(ruleData, "font-variant") || "normal",
  305. getPropertyValue(ruleData, "font-feature-settings"),
  306. getPropertyValue(ruleData, "font-variation-settings")
  307. ]);
  308. }
  309. function getFontStretch(stretch) {
  310. return FONT_STRETCHES[stretch] || stretch;
  311. }
  312. function createFontsDetailsInfo() {
  313. return {
  314. fonts: new Map(),
  315. medias: new Map(),
  316. supports: new Map()
  317. };
  318. }
  319. function getURL(urlFunction) {
  320. const urlMatch = urlFunction.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  321. urlFunction.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  322. urlFunction.match(REGEXP_URL_NO_QUOTES_FN);
  323. return urlMatch && urlMatch[1];
  324. }