single-file-util.js 11 KB

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