single-file-util.js 12 KB

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