single-file-util.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /*
  2. * Copyright 2010-2019 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 window */
  24. this.singlefile.lib.util = this.singlefile.lib.util || (() => {
  25. const DEBUG = false;
  26. const ONE_MB = 1024 * 1024;
  27. const PREFIX_CONTENT_TYPE_TEXT = "text/";
  28. const URL = window.URL;
  29. const DOMParser = window.DOMParser;
  30. const Blob = window.Blob;
  31. const FileReader = window.FileReader;
  32. const fetch = window.fetch;
  33. const crypto = window.crypto;
  34. const TextDecoder = window.TextDecoder;
  35. const TextEncoder = window.TextEncoder;
  36. const singlefile = this.singlefile;
  37. return {
  38. getInstance(utilOptions) {
  39. const modules = singlefile.lib.modules;
  40. const vendor = singlefile.lib.vendor;
  41. const helper = singlefile.lib.helper;
  42. if (modules.serializer === undefined) {
  43. modules.serializer = {
  44. process(doc) {
  45. const docType = doc.doctype;
  46. let docTypeString = "";
  47. if (docType) {
  48. docTypeString = "<!DOCTYPE " + docType.nodeName;
  49. if (docType.publicId) {
  50. docTypeString += " PUBLIC \"" + docType.publicId + "\"";
  51. if (docType.systemId)
  52. docTypeString += " \"" + docType.systemId + "\"";
  53. } else if (docType.systemId)
  54. docTypeString += " SYSTEM \"" + docType.systemId + "\"";
  55. if (docType.internalSubset)
  56. docTypeString += " [" + docType.internalSubset + "]";
  57. docTypeString += "> ";
  58. }
  59. return docTypeString + doc.documentElement.outerHTML;
  60. }
  61. };
  62. }
  63. utilOptions = utilOptions || {};
  64. utilOptions.fetch = utilOptions.fetch || fetch;
  65. return {
  66. getContent,
  67. parseURL(resourceURL, baseURI) {
  68. if (baseURI === undefined) {
  69. return new URL(resourceURL);
  70. } else {
  71. return new URL(resourceURL, baseURI);
  72. }
  73. },
  74. resolveURL(resourceURL, baseURI) {
  75. return this.parseURL(resourceURL, baseURI).href;
  76. },
  77. getValidFilename(filename, replacementCharacter) {
  78. filename = filename
  79. .replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, replacementCharacter); // eslint-disable-line no-control-regex
  80. filename = filename
  81. .replace(/\.\.\//g, "")
  82. .replace(/^\/+/, "")
  83. .replace(/\/+/g, "/")
  84. .replace(/\/$/, "")
  85. .replace(/\.$/, "")
  86. .replace(/\.\//g, "." + replacementCharacter)
  87. .replace(/\/\./g, "/" + replacementCharacter);
  88. return filename;
  89. },
  90. parseDocContent(content, baseURI) {
  91. const doc = (new DOMParser()).parseFromString(content, "text/html");
  92. if (!doc.head) {
  93. doc.documentElement.insertBefore(doc.createElement("HEAD"), doc.body);
  94. }
  95. let baseElement = doc.querySelector("base");
  96. if (!baseElement || !baseElement.getAttribute("href")) {
  97. if (baseElement) {
  98. baseElement.remove();
  99. }
  100. baseElement = doc.createElement("base");
  101. baseElement.setAttribute("href", baseURI);
  102. doc.head.insertBefore(baseElement, doc.head.firstChild);
  103. }
  104. return doc;
  105. },
  106. parseXMLContent(content) {
  107. return (new DOMParser()).parseFromString(content, "text/xml");
  108. },
  109. parseSVGContent(content) {
  110. return (new DOMParser()).parseFromString(content, "image/svg+xml");
  111. },
  112. async digest(algo, text) {
  113. const hash = await crypto.subtle.digest(algo, new TextEncoder("utf-8").encode(text));
  114. return hex(hash);
  115. },
  116. getContentSize(content) {
  117. return new Blob([content]).size;
  118. },
  119. async truncateText(content, maxSize) {
  120. const blob = new Blob([content]);
  121. const reader = new FileReader();
  122. reader.readAsText(blob.slice(0, maxSize));
  123. return new Promise((resolve, reject) => {
  124. reader.addEventListener("load", () => {
  125. if (content.startsWith(reader.result)) {
  126. resolve(reader.result);
  127. } else {
  128. this.truncateText(content, maxSize - 1).then(resolve).catch(reject);
  129. }
  130. }, false);
  131. reader.addEventListener("error", reject, false);
  132. });
  133. },
  134. minifyHTML(doc, options) {
  135. return modules.htmlMinifier.process(doc, options);
  136. },
  137. postMinifyHTML(doc) {
  138. return modules.htmlMinifier.postProcess(doc);
  139. },
  140. minifyCSSRules(stylesheets, styles, mediaAllInfo) {
  141. return modules.cssRulesMinifier.process(stylesheets, styles, mediaAllInfo);
  142. },
  143. removeUnusedFonts(doc, stylesheets, styles, options) {
  144. return modules.fontsMinifier.process(doc, stylesheets, styles, options);
  145. },
  146. removeAlternativeFonts(doc, stylesheets) {
  147. return modules.fontsAltMinifier.process(doc, stylesheets);
  148. },
  149. getMediaAllInfo(doc, stylesheets, styles) {
  150. return modules.matchedRules.getMediaAllInfo(doc, stylesheets, styles);
  151. },
  152. compressCSS(content, options) {
  153. return vendor.cssMinifier.processString(content, options);
  154. },
  155. minifyMedias(stylesheets) {
  156. return modules.mediasAltMinifier.process(stylesheets);
  157. },
  158. removeAlternativeImages(doc) {
  159. return modules.imagesAltMinifier.process(doc);
  160. },
  161. parseSrcset(srcset) {
  162. return vendor.srcsetParser.process(srcset);
  163. },
  164. preProcessDoc(doc, win, options) {
  165. return helper.preProcessDoc(doc, win, options);
  166. },
  167. postProcessDoc(doc, markedElements) {
  168. helper.postProcessDoc(doc, markedElements);
  169. },
  170. serialize(doc, compressHTML) {
  171. return modules.serializer.process(doc, compressHTML);
  172. },
  173. removeQuotes(string) {
  174. return helper.removeQuotes(string);
  175. },
  176. WIN_ID_ATTRIBUTE_NAME: helper.WIN_ID_ATTRIBUTE_NAME,
  177. REMOVED_CONTENT_ATTRIBUTE_NAME: helper.REMOVED_CONTENT_ATTRIBUTE_NAME,
  178. IMAGE_ATTRIBUTE_NAME: helper.IMAGE_ATTRIBUTE_NAME,
  179. POSTER_ATTRIBUTE_NAME: helper.POSTER_ATTRIBUTE_NAME,
  180. CANVAS_ATTRIBUTE_NAME: helper.CANVAS_ATTRIBUTE_NAME,
  181. HTML_IMPORT_ATTRIBUTE_NAME: helper.HTML_IMPORT_ATTRIBUTE_NAME,
  182. INPUT_VALUE_ATTRIBUTE_NAME: helper.INPUT_VALUE_ATTRIBUTE_NAME,
  183. SHADOW_ROOT_ATTRIBUTE_NAME: helper.SHADOW_ROOT_ATTRIBUTE_NAME,
  184. PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME: helper.PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME,
  185. STYLESHEET_ATTRIBUTE_NAME: helper.STYLESHEET_ATTRIBUTE_NAME,
  186. SELECTED_CONTENT_ATTRIBUTE_NAME: helper.SELECTED_CONTENT_ATTRIBUTE_NAME
  187. };
  188. async function getContent(resourceURL, options) {
  189. let response, startTime;
  190. const fetchResource = utilOptions.fetch;
  191. if (DEBUG) {
  192. startTime = Date.now();
  193. log(" // STARTED download url =", resourceURL, "asBinary =", options.asBinary);
  194. }
  195. try {
  196. response = await fetchResource(resourceURL);
  197. } catch (error) {
  198. return { data: options.asBinary ? "data:base64," : "", resourceURL };
  199. }
  200. const buffer = await response.arrayBuffer();
  201. resourceURL = response.url || resourceURL;
  202. let contentType = response.headers.get("content-type");
  203. let charset;
  204. if (contentType) {
  205. const matchContentType = contentType.toLowerCase().split(";");
  206. contentType = matchContentType[0].trim();
  207. if (!contentType.includes("/")) {
  208. contentType = null;
  209. }
  210. const charsetValue = matchContentType[1] && matchContentType[1].trim();
  211. if (charsetValue) {
  212. const matchCharset = charsetValue.match(/^charset=(.*)/);
  213. if (matchCharset && matchCharset[1]) {
  214. charset = helper.removeQuotes(matchCharset[1].trim());
  215. }
  216. }
  217. }
  218. if (!charset && options.charset) {
  219. charset = options.charset;
  220. }
  221. if (options.asBinary) {
  222. try {
  223. if (DEBUG) {
  224. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  225. }
  226. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  227. return { data: "data:base64,", resourceURL };
  228. } else {
  229. const reader = new FileReader();
  230. reader.readAsDataURL(new Blob([buffer], { type: contentType || this.getContentType() }));
  231. const dataUri = await new Promise((resolve, reject) => {
  232. reader.addEventListener("load", () => resolve(reader.result), false);
  233. reader.addEventListener("error", reject, false);
  234. });
  235. return { data: dataUri, resourceURL };
  236. }
  237. } catch (error) {
  238. return { data: "data:base64,", resourceURL };
  239. }
  240. } else {
  241. if (response.status >= 400 || (options.validateTextContentType && contentType && !contentType.startsWith(PREFIX_CONTENT_TYPE_TEXT))) {
  242. return { data: "", resourceURL };
  243. }
  244. if (!charset) {
  245. charset = "utf-8";
  246. }
  247. if (DEBUG) {
  248. log(" // ENDED download url =", resourceURL, "delay =", Date.now() - startTime);
  249. }
  250. if (options.maxResourceSizeEnabled && buffer.byteLength > options.maxResourceSize * ONE_MB) {
  251. return { data: "", resourceURL, charset };
  252. } else {
  253. try {
  254. return { data: new TextDecoder(charset).decode(buffer), resourceURL, charset };
  255. } catch (error) {
  256. try {
  257. charset = "utf-8";
  258. return { data: new TextDecoder(charset).decode(buffer), resourceURL, charset };
  259. } catch (error) {
  260. return { data: "", resourceURL, charset };
  261. }
  262. }
  263. }
  264. }
  265. }
  266. }
  267. };
  268. // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  269. function hex(buffer) {
  270. const hexCodes = [];
  271. const view = new DataView(buffer);
  272. for (let i = 0; i < view.byteLength; i += 4) {
  273. const value = view.getUint32(i);
  274. const stringValue = value.toString(16);
  275. const padding = "00000000";
  276. const paddedValue = (padding + stringValue).slice(-padding.length);
  277. hexCodes.push(paddedValue);
  278. }
  279. return hexCodes.join("");
  280. }
  281. function log(...args) {
  282. console.log("S-File <browser>", ...args); // eslint-disable-line no-console
  283. }
  284. })();