single-file-core.js 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725
  1. /*
  2. * Copyright 2018 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. this.SingleFileCore = this.SingleFileCore || (() => {
  24. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  25. const SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = "data-single-file-selected-content-root";
  26. const DEBUG = false;
  27. let DocUtil, cssTree, sessionId = 0;
  28. function getClass(...args) {
  29. [DocUtil, cssTree] = args;
  30. return SingleFileClass;
  31. }
  32. class SingleFileClass {
  33. constructor(options) {
  34. this.options = options;
  35. if (options.sessionId === undefined) {
  36. options.sessionId = sessionId;
  37. sessionId++;
  38. }
  39. }
  40. async initialize() {
  41. this.runner = new Runner(this.options, true);
  42. await this.runner.loadPage();
  43. await this.runner.initialize();
  44. }
  45. async run() {
  46. await this.runner.run();
  47. }
  48. async getPageData() {
  49. return this.runner.getPageData();
  50. }
  51. }
  52. SingleFileClass.SELECTED_CONTENT_ATTRIBUTE_NAME = SELECTED_CONTENT_ATTRIBUTE_NAME;
  53. SingleFileClass.SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME = SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME;
  54. // -------------
  55. // ProgressEvent
  56. // -------------
  57. const PAGE_LOADING = "page-loading";
  58. const PAGE_LOADED = "page-loaded";
  59. const RESOURCES_INITIALIZING = "resource-initializing";
  60. const RESOURCES_INITIALIZED = "resources-initialized";
  61. const RESOURCE_LOADED = "resource-loaded";
  62. const PAGE_ENDED = "page-ended";
  63. const STAGE_STARTED = "stage-started";
  64. const STAGE_ENDED = "stage-ended";
  65. const STAGE_TASK_STARTED = "stage-task-started";
  66. const STAGE_TASK_ENDED = "stage-task-ended";
  67. class ProgressEvent {
  68. constructor(type, detail) {
  69. return { type, detail, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADED, PAGE_ENDED, STAGE_STARTED, STAGE_ENDED, STAGE_TASK_STARTED, STAGE_TASK_ENDED };
  70. }
  71. }
  72. // ------
  73. // Runner
  74. // ------
  75. const RESOLVE_URLS_STAGE = 0;
  76. const REPLACE_DATA_STAGE = 1;
  77. const REPLACE_DOCS_STAGE = 2;
  78. const POST_PROCESS_STAGE = 3;
  79. const STAGES = [{
  80. sequential: [
  81. { action: "preProcessPage" },
  82. { action: "insertShadowRootContents" },
  83. { action: "replaceStyleContents" },
  84. { option: "selected", action: "removeUnselectedElements" },
  85. { option: "removeVideoSrc", action: "insertVideoPosters" },
  86. { option: "removeFrames", action: "removeFrames" },
  87. { option: "removeImports", action: "removeImports" },
  88. { option: "removeScripts", action: "removeScripts" },
  89. { action: "removeDiscardedResources" },
  90. { action: "resetCharsetMeta" },
  91. { action: "setInputValues" },
  92. { option: "insertFaviconLink", action: "insertFaviconLink" },
  93. { action: "replaceCanvasElements" },
  94. { action: "insertFonts" },
  95. { option: "removeHiddenElements", action: "removeHiddenElements" },
  96. { action: "resolveHrefs" },
  97. { action: "resolveStyleAttributeURLs" }
  98. ],
  99. parallel: [
  100. { action: "resolveStylesheetURLs" },
  101. { option: "!removeFrames", action: "resolveFrameURLs" },
  102. { option: "!removeImports", action: "resolveHtmlImportURLs" }
  103. ]
  104. }, {
  105. sequential: [
  106. { option: "removeUnusedStyles", action: "removeUnusedStyles" },
  107. { option: "removeAlternativeMedias", action: "removeAlternativeMedias" },
  108. { option: "removeUnusedStyles", action: "removeUnusedFonts" }
  109. ],
  110. parallel: [
  111. { action: "processStylesheets" },
  112. { action: "processStyleAttributes" },
  113. { action: "processPageResources" },
  114. { option: "!removeScripts", action: "processScripts" }
  115. ]
  116. }, {
  117. sequential: [
  118. { option: "removeAlternativeImages", action: "removeAlternativeImages" },
  119. { option: "removeAlternativeFonts", action: "removeAlternativeFonts" }
  120. ],
  121. parallel: [
  122. { option: "!removeFrames", action: "processFrames" },
  123. { option: "!removeImports", action: "processHtmlImports" },
  124. ]
  125. }, {
  126. sequential: [
  127. { action: "replaceStylesheets" },
  128. { action: "replaceStyleAttributes" },
  129. { action: "insertVariables" },
  130. { option: "compressHTML", action: "compressHTML" }
  131. ]
  132. }];
  133. class Runner {
  134. constructor(options, root) {
  135. this.root = root;
  136. this.options = options;
  137. this.options.url = this.options.url || this.options.doc.location.href;
  138. this.options.baseURI = this.options.doc && this.options.doc.baseURI;
  139. this.batchRequest = new BatchRequest();
  140. this.processor = new Processor(options, this.batchRequest);
  141. if (this.options.doc) {
  142. const docData = DocUtil.preProcessDoc(this.options.doc, this.options.win, this.options);
  143. this.options.canvasData = docData.canvasData;
  144. this.options.fontsData = docData.fontsData;
  145. this.options.stylesheetContents = docData.stylesheetContents;
  146. this.options.imageData = docData.imageData;
  147. this.options.postersData = docData.postersData;
  148. this.options.usedFonts = docData.usedFonts;
  149. this.options.shadowRootContents = docData.shadowRootContents;
  150. }
  151. this.options.content = this.options.content || (this.options.doc ? DocUtil.serialize(this.options.doc, false) : null);
  152. this.onprogress = options.onprogress || (() => { });
  153. }
  154. async loadPage() {
  155. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url, frame: !this.root }));
  156. await this.processor.loadPage(this.options.content);
  157. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url, frame: !this.root }));
  158. }
  159. async initialize() {
  160. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  161. await this.executeStage(RESOLVE_URLS_STAGE);
  162. this.pendingPromises = this.executeStage(REPLACE_DATA_STAGE);
  163. if (this.options.doc) {
  164. DocUtil.postProcessDoc(this.options.doc, this.options);
  165. this.options.doc = null;
  166. this.options.win = null;
  167. }
  168. }
  169. async run() {
  170. if (this.root) {
  171. this.processor.initialize(this.batchRequest);
  172. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: this.processor.maxResources }));
  173. }
  174. await this.batchRequest.run(detail => {
  175. detail.pageURL = this.options.url;
  176. this.onprogress(new ProgressEvent(RESOURCE_LOADED, detail));
  177. }, this.options);
  178. await this.pendingPromises;
  179. await this.executeStage(REPLACE_DOCS_STAGE);
  180. await this.executeStage(POST_PROCESS_STAGE);
  181. await this.processor.end();
  182. }
  183. async getPageData() {
  184. if (this.root) {
  185. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  186. }
  187. return this.processor.getPageData();
  188. }
  189. async executeStage(step) {
  190. if (DEBUG) {
  191. log("**** STARTED STAGE", step, "****");
  192. }
  193. const frame = !this.root;
  194. this.onprogress(new ProgressEvent(STAGE_STARTED, { pageURL: this.options.url, step, frame }));
  195. STAGES[step].sequential.forEach(task => {
  196. let startTime;
  197. if (DEBUG) {
  198. startTime = Date.now();
  199. log(" -- STARTED task =", task.action);
  200. }
  201. this.onprogress(new ProgressEvent(STAGE_TASK_STARTED, { pageURL: this.options.url, step, task: task.action, frame }));
  202. this.executeTask(task);
  203. this.onprogress(new ProgressEvent(STAGE_TASK_ENDED, { pageURL: this.options.url, step, task: task.action, frame }));
  204. if (DEBUG) {
  205. log(" -- ENDED task =", task.action, "delay =", Date.now() - startTime);
  206. }
  207. });
  208. let parallelTasksPromise;
  209. if (STAGES[step].parallel) {
  210. parallelTasksPromise = await Promise.all(STAGES[step].parallel.map(async task => {
  211. let startTime;
  212. if (DEBUG) {
  213. startTime = Date.now();
  214. log(" // STARTED task =", task.action);
  215. }
  216. this.onprogress(new ProgressEvent(STAGE_TASK_STARTED, { pageURL: this.options.url, step, task: task.action, frame }));
  217. await this.executeTask(task);
  218. this.onprogress(new ProgressEvent(STAGE_TASK_ENDED, { pageURL: this.options.url, step, task: task.action, frame }));
  219. if (DEBUG) {
  220. log(" // ENDED task =", task.action, "delay =", Date.now() - startTime);
  221. }
  222. }));
  223. } else {
  224. parallelTasksPromise = Promise.resolve();
  225. }
  226. this.onprogress(new ProgressEvent(STAGE_ENDED, { pageURL: this.options.url, step, frame }));
  227. if (DEBUG) {
  228. log("**** ENDED STAGE", step, "****");
  229. }
  230. return parallelTasksPromise;
  231. }
  232. executeTask(task) {
  233. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  234. return this.processor[task.action]();
  235. }
  236. }
  237. }
  238. // ------------
  239. // BatchRequest
  240. // ------------
  241. class BatchRequest {
  242. constructor() {
  243. this.requests = new Map();
  244. this.duplicates = new Map();
  245. }
  246. async addURL(resourceURL, asDataURI, groupDuplicates) {
  247. return new Promise((resolve, reject) => {
  248. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  249. let resourceRequests = this.requests.get(requestKey);
  250. if (!resourceRequests) {
  251. resourceRequests = [];
  252. this.requests.set(requestKey, resourceRequests);
  253. }
  254. const callbacks = { resolve, reject };
  255. resourceRequests.push(callbacks);
  256. if (groupDuplicates) {
  257. let duplicateRequests = this.duplicates.get(requestKey);
  258. if (!duplicateRequests) {
  259. duplicateRequests = [];
  260. this.duplicates.set(requestKey, duplicateRequests);
  261. }
  262. duplicateRequests.push(callbacks);
  263. }
  264. });
  265. }
  266. getMaxResources() {
  267. return Array.from(this.requests.keys()).length;
  268. }
  269. async run(onloadListener, options) {
  270. const resourceURLs = Array.from(this.requests.keys());
  271. let indexResource = 0;
  272. return Promise.all(resourceURLs.map(async requestKey => {
  273. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  274. const resourceRequests = this.requests.get(requestKey);
  275. try {
  276. const content = await DocUtil.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  277. indexResource = indexResource + 1;
  278. onloadListener({ index: indexResource, url: resourceURL });
  279. resourceRequests.forEach(callbacks => {
  280. const duplicateCallbacks = this.duplicates.get(requestKey);
  281. const duplicate = duplicateCallbacks && duplicateCallbacks.length > 1 && duplicateCallbacks.includes(callbacks);
  282. callbacks.resolve({ content: content.data, indexResource, duplicate });
  283. });
  284. } catch (error) {
  285. indexResource = indexResource + 1;
  286. onloadListener({ index: indexResource, url: resourceURL });
  287. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  288. }
  289. this.requests.delete(requestKey);
  290. }));
  291. }
  292. }
  293. // ---------
  294. // Processor
  295. // ---------
  296. const EMPTY_DATA_URI = "data:base64,";
  297. const EMPTY_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  298. const SCRIPT_TAG_FOUND = /<script/gi;
  299. const NOSCRIPT_TAG_FOUND = /<noscript/gi;
  300. class Processor {
  301. constructor(options, batchRequest) {
  302. this.options = options;
  303. this.stats = new Stats(options);
  304. this.baseURI = Util.normalizeURL(options.baseURI || options.url);
  305. this.batchRequest = batchRequest;
  306. this.stylesheets = new Map();
  307. this.styles = new Map();
  308. this.cssVariables = new Map();
  309. }
  310. initialize() {
  311. this.maxResources = this.batchRequest.getMaxResources();
  312. if (!this.options.removeFrames) {
  313. this.options.framesData.forEach(frameData => this.maxResources += frameData.maxResources || 0);
  314. }
  315. this.stats.set("processed", "resources", this.maxResources);
  316. }
  317. async loadPage(pageContent) {
  318. let resourceURL;
  319. if (!pageContent || this.options.saveRawPage) {
  320. const content = await DocUtil.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  321. pageContent = content.data;
  322. this.baseURI = this.options.url = resourceURL;
  323. }
  324. this.doc = DocUtil.createDoc(pageContent, this.baseURI);
  325. this.onEventAttributeNames = Util.getOnEventAttributeNames(this.doc);
  326. }
  327. async getPageData() {
  328. DocUtil.postProcessDoc(this.doc, this.options);
  329. const url = DocUtil.parseURL(this.baseURI);
  330. if (this.options.insertSingleFileComment) {
  331. const infobarContent = (this.options.infobarContent || "").replace(/\\n/g, "\n").replace(/\\t/g, "\t");
  332. const commentNode = this.doc.createComment("\n Page saved with SingleFile" +
  333. " \n url: " + this.options.url +
  334. " \n saved date: " + new Date() +
  335. (infobarContent ? " \n info: " + infobarContent : "") + "\n");
  336. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  337. }
  338. let size;
  339. if (this.options.displayStats) {
  340. size = DocUtil.getContentSize(this.doc.documentElement.outerHTML);
  341. }
  342. const content = DocUtil.serialize(this.doc, this.options.compressHTML);
  343. if (this.options.displayStats) {
  344. const contentSize = DocUtil.getContentSize(content);
  345. this.stats.set("processed", "HTML bytes", contentSize);
  346. this.stats.add("discarded", "HTML bytes", size - contentSize);
  347. }
  348. let filename = await ProcessorHelper.evalTemplate(this.options.filenameTemplate, this.options, content);
  349. filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
  350. filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "");
  351. if (!this.options.backgroundSave) {
  352. filename = filename.replace(/\//g, "_");
  353. }
  354. if (filename.length > 192) {
  355. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  356. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  357. filename = filename.substring(0, 192 - extension.length) + "…" + extension;
  358. }
  359. if (!filename) {
  360. filename = "Unnamed page";
  361. }
  362. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  363. return {
  364. stats: this.stats.data,
  365. title: this.options.title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "")),
  366. filename,
  367. content
  368. };
  369. }
  370. removeUnselectedElements() {
  371. const rootElement = this.doc.querySelector("[" + SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME + "]");
  372. if (rootElement) {
  373. ProcessorHelper.isolateElements(rootElement);
  374. rootElement.removeAttribute(SELECTED_CONTENT_ROOT_ATTRIBUTE_NAME);
  375. rootElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  376. }
  377. }
  378. setInputValues() {
  379. this.doc.querySelectorAll("input").forEach(input => {
  380. const value = input.getAttribute(DocUtil.inputValueAttributeName(this.options.sessionId));
  381. input.setAttribute("value", value || "");
  382. });
  383. this.doc.querySelectorAll("input[type=radio], input[type=checkbox]").forEach(input => {
  384. const value = input.getAttribute(DocUtil.inputValueAttributeName(this.options.sessionId));
  385. if (value == "true") {
  386. input.setAttribute("checked", "");
  387. }
  388. });
  389. this.doc.querySelectorAll("textarea").forEach(textarea => {
  390. const value = textarea.getAttribute(DocUtil.inputValueAttributeName(this.options.sessionId));
  391. textarea.textContent = value || "";
  392. });
  393. this.doc.querySelectorAll("select").forEach(select => {
  394. select.querySelectorAll("option").forEach(option => {
  395. const selected = option.getAttribute(DocUtil.inputValueAttributeName(this.options.sessionId)) != null;
  396. if (selected) {
  397. option.setAttribute("selected", "");
  398. }
  399. });
  400. });
  401. }
  402. removeDiscardedResources() {
  403. const objectElements = this.doc.querySelectorAll("applet, meta[http-equiv=refresh], object[data]:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]):not([type=\"text/html\"]), embed[src]:not([src*=\".svg\"])");
  404. this.stats.set("discarded", "objects", objectElements.length);
  405. this.stats.set("processed", "objects", objectElements.length);
  406. objectElements.forEach(element => element.remove());
  407. const replacedAttributeValue = this.doc.querySelectorAll("link[rel~=preconnect], link[rel~=prerender], link[rel~=dns-prefetch], link[rel~=preload], link[rel~=prefetch]");
  408. replacedAttributeValue.forEach(element => {
  409. const relValue = element.getAttribute("rel").replace(/(preconnect|prerender|dns-prefetch|preload|prefetch)/g, "").trim();
  410. if (relValue.length) {
  411. element.setAttribute("rel", relValue);
  412. } else {
  413. element.remove();
  414. }
  415. });
  416. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"]").forEach(element => element.remove());
  417. if (this.options.compressHTML) {
  418. this.doc.querySelectorAll("input[type=hidden]").forEach(element => element.remove());
  419. }
  420. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  421. if (this.options.removeScripts) {
  422. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  423. this.doc.querySelectorAll("[href]").forEach(element => {
  424. if (element.href && element.href.match && element.href.match(/^\s*javascript:/)) {
  425. element.setAttribute("href", "");
  426. }
  427. });
  428. this.doc.querySelectorAll("[src]").forEach(element => {
  429. if (element.src && element.src.match(/^\s*javascript:/)) {
  430. element.removeAttribute("src");
  431. }
  432. });
  433. }
  434. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  435. this.stats.set("processed", "audio sources", audioSourceElements.length);
  436. if (this.options.removeAudioSrc) {
  437. this.stats.set("discarded", "audio sources", audioSourceElements.length);
  438. audioSourceElements.forEach(element => {
  439. if (element.tagName == "SOURCE") {
  440. element.remove();
  441. } else {
  442. audioSourceElements.forEach(element => element.removeAttribute("src"));
  443. }
  444. });
  445. }
  446. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source[src]");
  447. this.stats.set("processed", "video sources", videoSourceElements.length);
  448. if (this.options.removeVideoSrc) {
  449. this.stats.set("discarded", "video sources", videoSourceElements.length);
  450. videoSourceElements.forEach(element => {
  451. if (element.tagName == "SOURCE") {
  452. element.remove();
  453. } else {
  454. videoSourceElements.forEach(element => element.removeAttribute("src"));
  455. }
  456. });
  457. }
  458. }
  459. async end() {
  460. const metaCharset = this.doc.head.querySelector("meta[charset]");
  461. if (metaCharset) {
  462. this.doc.head.insertBefore(metaCharset, this.doc.head.firstChild);
  463. }
  464. this.doc.querySelectorAll("base").forEach(element => element.remove());
  465. if (this.doc.head.querySelectorAll("*").length == 1 && metaCharset && this.doc.body.childNodes.length == 0) {
  466. this.doc.head.querySelector("meta[charset]").remove();
  467. }
  468. const titleElement = this.doc.querySelector("title");
  469. const descriptionElement = this.doc.querySelector("meta[name=description]");
  470. const authorElement = this.doc.querySelector("meta[name=author]");
  471. const creatorElement = this.doc.querySelector("meta[name=creator]");
  472. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  473. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  474. this.options.infobarContent = await ProcessorHelper.evalTemplate(this.options.infobarTemplate, this.options, null, true);
  475. this.options.info = {
  476. description: descriptionElement ? descriptionElement.content.trim() : "",
  477. lang: this.doc.documentElement.lang,
  478. author: authorElement ? authorElement.content.trim() : "",
  479. creator: creatorElement ? creatorElement.content.trim() : "",
  480. publisher: publisherElement ? publisherElement.content.trim() : ""
  481. };
  482. }
  483. preProcessPage() {
  484. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask, singlefile-logs-window").forEach(element => element.remove());
  485. if (this.options.win) {
  486. this.doc.body.querySelectorAll(":not(svg) title, meta, link[href][rel*=\"icon\"]").forEach(element => element instanceof this.options.win.HTMLElement && this.doc.head.appendChild(element));
  487. }
  488. if (this.options.imageData) {
  489. const dataAttributeName = DocUtil.imagesAttributeName(this.options.sessionId);
  490. this.doc.querySelectorAll("img").forEach(imgElement => {
  491. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  492. if (this.options.removeHiddenElements && imgData.size && !imgData.size.pxWidth && !imgData.size.pxHeight) {
  493. imgElement.setAttribute("src", EMPTY_IMAGE);
  494. } else if (imgData.currentSrc) {
  495. imgElement.setAttribute("src", imgData.currentSrc);
  496. }
  497. });
  498. if (this.options.lazyLoadImages) {
  499. this.doc.querySelectorAll("img[data-src]").forEach(imgElement => {
  500. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  501. if ((!imgElement.getAttribute("src") || imgElement.getAttribute("src") == EMPTY_IMAGE) && imgElement.getAttribute("data-src")) {
  502. imgData.src = imgElement.dataset.src;
  503. imgElement.setAttribute("src", imgElement.dataset.src);
  504. imgElement.removeAttribute("data-src");
  505. }
  506. });
  507. this.doc.querySelectorAll("img[data-srcset]").forEach(imgElement => {
  508. if (!imgElement.getAttribute("srcset") && imgElement.getAttribute("data-srcset")) {
  509. imgElement.setAttribute("srcset", imgElement.dataset.srcset);
  510. imgElement.removeAttribute("data-srcset");
  511. }
  512. });
  513. }
  514. }
  515. }
  516. removeScripts() {
  517. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  518. this.stats.set("discarded", "scripts", scriptElements.length);
  519. this.stats.set("processed", "scripts", scriptElements.length);
  520. scriptElements.forEach(element => element.remove());
  521. }
  522. removeFrames() {
  523. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  524. this.stats.set("discarded", "frames", frameElements.length);
  525. this.stats.set("processed", "frames", frameElements.length);
  526. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  527. }
  528. removeImports() {
  529. const importElements = this.doc.querySelectorAll("link[rel=import]");
  530. this.stats.set("discarded", "HTML imports", importElements.length);
  531. this.stats.set("processed", "HTML imports", importElements.length);
  532. importElements.forEach(element => element.remove());
  533. }
  534. resetCharsetMeta() {
  535. let charset;
  536. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  537. const charsetDeclaration = element.content.split(";")[1];
  538. if (charsetDeclaration && !charset) {
  539. charset = charsetDeclaration.split("=")[1];
  540. if (charset) {
  541. this.charset = charset.trim().toLowerCase();
  542. }
  543. }
  544. element.remove();
  545. });
  546. const metaElement = this.doc.createElement("meta");
  547. metaElement.setAttribute("charset", "utf-8");
  548. if (this.doc.head.firstChild) {
  549. this.doc.head.insertBefore(metaElement, this.doc.head.firstChild);
  550. } else {
  551. this.doc.head.appendChild(metaElement);
  552. }
  553. }
  554. insertFaviconLink() {
  555. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  556. if (!faviconElement) {
  557. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  558. }
  559. if (!faviconElement) {
  560. faviconElement = this.doc.createElement("link");
  561. faviconElement.setAttribute("type", "image/x-icon");
  562. faviconElement.setAttribute("rel", "shortcut icon");
  563. faviconElement.setAttribute("href", "/favicon.ico");
  564. }
  565. this.doc.head.appendChild(faviconElement);
  566. }
  567. resolveHrefs() {
  568. this.doc.querySelectorAll("[href]").forEach(element => {
  569. const href = element.getAttribute("href");
  570. if (!Util.testIgnoredPath(href) && Util.testValidPath(href, this.baseURI, this.options.url)) {
  571. const normalizedHref = Util.normalizeURL(href);
  572. if (element.tagName == "LINK") {
  573. try {
  574. element.setAttribute("href", DocUtil.resolveURL(href, this.options.baseURI || this.options.url));
  575. } catch (error) {
  576. if (element.tagName == "LINK") {
  577. element.setAttribute("href", EMPTY_URL);
  578. }
  579. }
  580. } else if (normalizedHref == href) {
  581. try {
  582. element.setAttribute("href", DocUtil.resolveURL(normalizedHref, this.options.baseURI || this.options.url));
  583. } catch (error) {
  584. // ignored
  585. }
  586. }
  587. }
  588. });
  589. }
  590. removeUnusedStyles() {
  591. if (!this.mediaAllInfo) {
  592. this.mediaAllInfo = DocUtil.getMediaAllInfo(this.doc, this.stylesheets, this.styles);
  593. }
  594. const stats = DocUtil.minifyCSSRules(this.stylesheets, this.styles, this.mediaAllInfo);
  595. this.stats.set("processed", "CSS rules", stats.processed);
  596. this.stats.set("discarded", "CSS rules", stats.discarded);
  597. }
  598. removeUnusedFonts() {
  599. DocUtil.removeUnusedFonts(this.doc, this.stylesheets, this.styles, this.options);
  600. }
  601. removeAlternativeFonts() {
  602. DocUtil.removeAlternativeFonts(this.doc, this.stylesheets);
  603. }
  604. removeAlternativeImages() {
  605. DocUtil.removeAlternativeImages(this.doc);
  606. }
  607. removeHiddenElements() {
  608. const hiddenElements = this.doc.querySelectorAll("[" + DocUtil.removedContentAttributeName(this.options.sessionId) + "]");
  609. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  610. this.stats.set("processed", "hidden elements", hiddenElements.length);
  611. hiddenElements.forEach(element => element.remove());
  612. }
  613. compressHTML() {
  614. let size;
  615. if (this.options.displayStats) {
  616. size = DocUtil.getContentSize(this.doc.documentElement.outerHTML);
  617. }
  618. DocUtil.minifyHTML(this.doc, { preservedSpaceAttributeName: DocUtil.preservedSpaceAttributeName(this.options.sessionId) });
  619. if (this.options.displayStats) {
  620. this.stats.add("discarded", "HTML bytes", size - DocUtil.getContentSize(this.doc.documentElement.outerHTML));
  621. }
  622. }
  623. removeAlternativeMedias() {
  624. const stats = DocUtil.minifyMedias(this.stylesheets);
  625. this.stats.set("processed", "medias", stats.processed);
  626. this.stats.set("discarded", "medias", stats.discarded);
  627. }
  628. replaceCanvasElements() {
  629. if (this.options.canvasData) {
  630. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  631. const canvasData = this.options.canvasData[indexCanvasElement];
  632. if (canvasData) {
  633. ProcessorHelper.setBackgroundImage(canvasElement, "url(" + canvasData.dataURI + ")");
  634. this.stats.add("processed", "canvas", 1);
  635. }
  636. });
  637. }
  638. }
  639. insertFonts() {
  640. if (this.options.fontsData && this.options.fontsData.length) {
  641. let stylesheetContent = "";
  642. this.options.fontsData.forEach(fontStyles => {
  643. if (fontStyles["font-family"] && fontStyles.src) {
  644. stylesheetContent += "@font-face{";
  645. let stylesContent = "";
  646. Object.keys(fontStyles).forEach(fontStyle => {
  647. if (stylesContent) {
  648. stylesContent += ";";
  649. }
  650. stylesContent += fontStyle + ":" + fontStyles[fontStyle];
  651. });
  652. stylesheetContent += stylesContent + "}";
  653. }
  654. });
  655. if (stylesheetContent) {
  656. const styleElement = this.doc.createElement("style");
  657. styleElement.textContent = stylesheetContent;
  658. const existingStyleElement = this.doc.querySelector("style");
  659. if (existingStyleElement) {
  660. existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
  661. } else {
  662. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  663. }
  664. }
  665. }
  666. }
  667. replaceStyleContents() {
  668. if (this.options.stylesheetContents) {
  669. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  670. if (this.options.stylesheetContents[styleIndex]) {
  671. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  672. }
  673. });
  674. }
  675. }
  676. insertShadowRootContents() {
  677. if (this.options.shadowRootContents) {
  678. this.doc.querySelectorAll("[" + DocUtil.shadowRootAttributeName(this.options.sessionId) + "]").forEach((element, elementIndex) => {
  679. const elementInfo = this.options.shadowRootContents[elementIndex];
  680. if (elementInfo) {
  681. const frameElement = this.doc.createElement("iframe");
  682. frameElement.setAttribute("style", "all:initial!important;border:0!important;width:100%!important;height:" + elementInfo.height + "px!important");
  683. const windowId = "shadow-" + this.options.framesData.length;
  684. frameElement.setAttribute(DocUtil.windowIdAttributeName(this.options.sessionId), windowId);
  685. this.options.framesData.push({ windowId, content: elementInfo.content, baseURI: this.baseURI });
  686. element.appendChild(frameElement);
  687. }
  688. });
  689. }
  690. }
  691. insertVideoPosters() {
  692. if (this.options.postersData) {
  693. this.doc.querySelectorAll("video[src], video > source[src]").forEach((element, videoIndex) => {
  694. let videoElement;
  695. if (element.tagName == "VIDEO") {
  696. videoElement = element;
  697. } else {
  698. videoElement = element.parentElement;
  699. }
  700. if (!videoElement.poster && this.options.postersData[videoIndex]) {
  701. videoElement.setAttribute("poster", this.options.postersData[videoIndex]);
  702. }
  703. });
  704. }
  705. }
  706. async processPageResources() {
  707. const processAttributeArgs = [
  708. ["link[href][rel*=\"icon\"]", "href", "data:", false, true],
  709. ["object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]", "data", PREFIX_DATA_URI_IMAGE_SVG],
  710. ["img[src], input[src][type=image]", "src", PREFIX_DATA_URI_IMAGE, true],
  711. ["embed[src*=\".svg\"]", "src", PREFIX_DATA_URI_IMAGE_SVG],
  712. ["video[poster]", "poster", PREFIX_DATA_URI_IMAGE],
  713. ["*[background]", "background", PREFIX_DATA_URI_IMAGE],
  714. ["image", "xlink:href", PREFIX_DATA_URI_IMAGE]
  715. ];
  716. let resourcePromises = processAttributeArgs.map(([selector, attributeName, prefixDataURI, processDuplicates, removeElementIfMissing]) =>
  717. ProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll(selector), attributeName, prefixDataURI, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest, processDuplicates, removeElementIfMissing)
  718. );
  719. resourcePromises = resourcePromises.concat([
  720. ProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.options, this.batchRequest),
  721. ProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest)
  722. ]);
  723. if (!this.options.removeAudioSrc) {
  724. resourcePromises.push(ProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", PREFIX_DATA_URI_AUDIO, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
  725. }
  726. if (!this.options.removeVideoSrc) {
  727. resourcePromises.push(ProcessorHelper.processAttribute(this.doc, this.doc.querySelectorAll("video[src], video > source[src]"), "src", PREFIX_DATA_URI_VIDEO, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
  728. }
  729. await Promise.all(resourcePromises);
  730. ProcessorHelper.processShortcutIcons(this.doc);
  731. }
  732. async resolveStylesheetURLs() {
  733. await Promise.all(Array.from(this.doc.querySelectorAll("style, link[rel*=stylesheet]"))
  734. .map(async element => {
  735. let mediaText;
  736. if (element.media) {
  737. mediaText = element.media;
  738. }
  739. this.stylesheets.set(element, { mediaText });
  740. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, url: this.options.url, charset: this.charset, compressCSS: this.options.compressCSS };
  741. const isLinkTag = element.tagName.toLowerCase() == "link";
  742. if (isLinkTag && element.rel.includes("alternate") && element.title) {
  743. element.remove();
  744. } else {
  745. let stylesheetContent;
  746. if (isLinkTag) {
  747. if (element.charset) {
  748. options.charset = element.charset;
  749. }
  750. stylesheetContent = await ProcessorHelper.resolveLinkStylesheetURLs(element.href, this.baseURI, options);
  751. } else {
  752. stylesheetContent = await ProcessorHelper.resolveImportURLs(element.textContent, this.baseURI, options);
  753. }
  754. let stylesheet;
  755. try {
  756. stylesheet = cssTree.parse(stylesheetContent);
  757. } catch (error) {
  758. // ignored
  759. }
  760. if (stylesheet && stylesheet.children) {
  761. if (this.options.compressCSS) {
  762. const removedRules = [];
  763. for (let cssRule = stylesheet.children.head; cssRule; cssRule = cssRule.next) {
  764. if (cssRule.data.type == "Raw" && cssRule.data.value && cssRule.data.value.trim().startsWith("//")) {
  765. removedRules.push(cssRule);
  766. }
  767. }
  768. removedRules.forEach(cssRule => stylesheet.children.remove(cssRule));
  769. }
  770. this.stylesheets.get(element).stylesheet = stylesheet;
  771. }
  772. }
  773. }));
  774. }
  775. async processStylesheets() {
  776. await Promise.all(Array.from(this.stylesheets).map(([, stylesheetInfo]) =>
  777. ProcessorHelper.processStylesheet(stylesheetInfo.stylesheet.children, this.baseURI, this.options, this.cssVariables, this.batchRequest)
  778. ));
  779. }
  780. replaceStylesheets() {
  781. this.doc.querySelectorAll("style").forEach(styleElement => {
  782. const stylesheetInfo = this.stylesheets.get(styleElement);
  783. if (stylesheetInfo) {
  784. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  785. styleElement.textContent = stylesheetContent;
  786. if (stylesheetInfo.mediaText) {
  787. styleElement.media = stylesheetInfo.mediaText;
  788. }
  789. } else {
  790. styleElement.remove();
  791. }
  792. });
  793. this.doc.querySelectorAll("link[rel*=stylesheet]").forEach(linkElement => {
  794. const stylesheetInfo = this.stylesheets.get(linkElement);
  795. if (stylesheetInfo) {
  796. const styleElement = this.doc.createElement("style");
  797. if (stylesheetInfo.mediaText) {
  798. styleElement.media = stylesheetInfo.mediaText;
  799. }
  800. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  801. styleElement.textContent = stylesheetContent;
  802. linkElement.parentElement.replaceChild(styleElement, linkElement);
  803. } else {
  804. linkElement.remove();
  805. }
  806. });
  807. }
  808. insertVariables() {
  809. if (this.cssVariables.size) {
  810. const styleElement = this.doc.createElement("style");
  811. const firstStyleElement = this.doc.head.querySelector("style");
  812. if (firstStyleElement) {
  813. this.doc.head.insertBefore(styleElement, firstStyleElement);
  814. } else {
  815. this.doc.head.appendChild(styleElement);
  816. }
  817. let stylesheetContent = "";
  818. this.cssVariables.forEach((content, indexResource) => {
  819. if (stylesheetContent) {
  820. stylesheetContent += ";";
  821. }
  822. stylesheetContent += `${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")`;
  823. });
  824. styleElement.textContent = ":root{" + stylesheetContent + "}";
  825. }
  826. }
  827. async processScripts() {
  828. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  829. if (scriptElement.src) {
  830. this.stats.add("processed", "scripts", 1);
  831. const content = await DocUtil.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  832. let scriptContent = content.data.replace(/<\//gi, "<\\/");
  833. try {
  834. new Function(scriptContent);
  835. } catch (error) {
  836. scriptContent = content.data.replace(/<\//gi, "<\\\\/");
  837. }
  838. try {
  839. new Function(scriptContent);
  840. scriptContent = scriptContent.replace(/\/>/gi, "\\/>");
  841. } catch (error) {
  842. // ignored
  843. }
  844. if (scriptContent) {
  845. scriptElement.textContent = scriptContent;
  846. }
  847. }
  848. scriptElement.removeAttribute("src");
  849. }));
  850. }
  851. async resolveFrameURLs() {
  852. if (this.options.framesData) {
  853. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  854. await Promise.all(frameElements.map(async frameElement => {
  855. ProcessorHelper.setFrameEmptySrc(frameElement);
  856. const frameWindowId = frameElement.getAttribute(DocUtil.windowIdAttributeName(this.options.sessionId));
  857. if (frameWindowId) {
  858. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  859. if (frameData) {
  860. await initializeProcessor(frameData, frameElement, frameWindowId, this.batchRequest, Object.create(this.options));
  861. }
  862. }
  863. }));
  864. }
  865. async function initializeProcessor(frameData, frameElement, frameWindowId, batchRequest, options) {
  866. options.insertSingleFileComment = false;
  867. options.insertFaviconLink = false;
  868. options.doc = null;
  869. options.win = null;
  870. options.url = frameData.baseURI;
  871. options.windowId = frameWindowId;
  872. if (frameData.content) {
  873. options.content = frameData.content;
  874. options.canvasData = frameData.canvasData;
  875. options.stylesheetContents = frameData.stylesheetContents;
  876. options.fontsData = frameData.fontsData;
  877. options.imageData = frameData.imageData;
  878. options.usedFonts = frameData.usedFonts;
  879. frameData.processor = new Runner(options);
  880. frameData.frameElement = frameElement;
  881. await frameData.processor.loadPage();
  882. await frameData.processor.initialize();
  883. frameData.maxResources = batchRequest.getMaxResources();
  884. }
  885. }
  886. }
  887. async processFrames() {
  888. if (this.options.framesData) {
  889. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  890. await Promise.all(frameElements.map(async frameElement => {
  891. const frameWindowId = frameElement.getAttribute(DocUtil.windowIdAttributeName(this.options.sessionId));
  892. if (frameWindowId) {
  893. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  894. if (frameData) {
  895. if (frameData.processor) {
  896. this.stats.add("processed", "frames", 1);
  897. await frameData.processor.run();
  898. const pageData = await frameData.processor.getPageData();
  899. frameElement.removeAttribute(DocUtil.windowIdAttributeName(this.options.sessionId));
  900. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  901. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  902. } else {
  903. frameElement.setAttribute("sandbox", "");
  904. }
  905. ProcessorHelper.setFrameContent(frameElement, pageData.content);
  906. this.stats.addAll(pageData);
  907. } else {
  908. this.stats.add("discarded", "frames", 1);
  909. }
  910. }
  911. }
  912. }));
  913. }
  914. }
  915. async resolveHtmlImportURLs() {
  916. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  917. if (!this.relImportProcessors) {
  918. this.relImportProcessors = new Map();
  919. }
  920. await Promise.all(linkElements.map(async linkElement => {
  921. const resourceURL = linkElement.href;
  922. linkElement.removeAttribute("href");
  923. const options = Object.create(this.options);
  924. options.insertSingleFileComment = false;
  925. options.insertFaviconLink = false;
  926. options.doc = null;
  927. options.win = null;
  928. options.url = resourceURL;
  929. if (!Util.testIgnoredPath(resourceURL) && Util.testValidPath(resourceURL, this.baseURI, this.options.url)) {
  930. const processor = new Runner(options);
  931. this.relImportProcessors.set(linkElement, processor);
  932. await processor.loadPage();
  933. return processor.initialize();
  934. }
  935. }));
  936. }
  937. async processHtmlImports() {
  938. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  939. await Promise.all(linkElements.map(async linkElement => {
  940. const processor = this.relImportProcessors.get(linkElement);
  941. if (processor) {
  942. this.stats.add("processed", "HTML imports", 1);
  943. this.relImportProcessors.delete(linkElement);
  944. const pageData = await processor.getPageData();
  945. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  946. this.stats.addAll(pageData);
  947. } else {
  948. this.stats.add("discarded", "HTML imports", 1);
  949. }
  950. }));
  951. }
  952. resolveStyleAttributeURLs() {
  953. this.doc.querySelectorAll("[style]").forEach(element => {
  954. let styleContent = element.getAttribute("style");
  955. if (this.options.compressCSS) {
  956. styleContent = DocUtil.compressCSS(styleContent);
  957. }
  958. styleContent = ProcessorHelper.resolveStylesheetURLs(styleContent, this.baseURI, this.options);
  959. const declarationList = cssTree.parse(styleContent, { context: "declarationList" });
  960. this.styles.set(element, declarationList);
  961. });
  962. }
  963. async processStyleAttributes() {
  964. return Promise.all(Array.from(this.styles).map(([, declarationList]) =>
  965. ProcessorHelper.processStyle(declarationList.children.toArray(), this.baseURI, this.options, this.cssVariables, this.batchRequest)
  966. ));
  967. }
  968. replaceStyleAttributes() {
  969. this.doc.querySelectorAll("[style]").forEach(async element => {
  970. const declarations = this.styles.get(element);
  971. if (declarations) {
  972. let styleContent = cssTree.generate(declarations);
  973. element.setAttribute("style", styleContent);
  974. } else {
  975. element.setAttribute("style", "");
  976. }
  977. });
  978. }
  979. }
  980. // ---------------
  981. // ProcessorHelper
  982. // ---------------
  983. const REGEXP_AMP = /&/g;
  984. const REGEXP_NBSP = /\u00a0/g;
  985. const REGEXP_START_TAG = /</g;
  986. const REGEXP_END_TAG = />/g;
  987. const REGEXP_URL_HASH = /(#.+?)$/;
  988. const PREFIX_DATA_URI_IMAGE = "data:image/";
  989. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  990. const PREFIX_DATA_URI_VIDEO = "data:video/";
  991. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  992. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  993. const PREFIX_DATA_URI_OCTET_STREAM = /^data:(application|binary)\/octet-stream/;
  994. const PREFIX_DATA_URI_NULL_STREAM = /^data:null;/;
  995. const PREFIX_DATA_URI_VND = "data:application/vnd.";
  996. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  997. class ProcessorHelper {
  998. static async evalTemplate(template, options, content, dontReplaceSlash) {
  999. const date = new Date();
  1000. const url = DocUtil.parseURL(options.url);
  1001. template = await Util.evalTemplateVariable(template, "page-title", () => options.title || "No title", dontReplaceSlash);
  1002. template = await Util.evalTemplateVariable(template, "page-language", () => options.info.lang || "No language", dontReplaceSlash);
  1003. template = await Util.evalTemplateVariable(template, "page-description", () => options.info.description || "No description", dontReplaceSlash);
  1004. template = await Util.evalTemplateVariable(template, "page-author", () => options.info.author || "No author", dontReplaceSlash);
  1005. template = await Util.evalTemplateVariable(template, "page-creator", () => options.info.creator || "No creator", dontReplaceSlash);
  1006. template = await Util.evalTemplateVariable(template, "page-publisher", () => options.info.publisher || "No publisher", dontReplaceSlash);
  1007. template = await Util.evalTemplateVariable(template, "datetime-iso", () => date.toISOString(), dontReplaceSlash);
  1008. template = await Util.evalTemplateVariable(template, "date-iso", () => date.toISOString().split("T")[0], dontReplaceSlash);
  1009. template = await Util.evalTemplateVariable(template, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0], dontReplaceSlash);
  1010. template = await Util.evalTemplateVariable(template, "date-locale", () => date.toLocaleDateString(), dontReplaceSlash);
  1011. template = await Util.evalTemplateVariable(template, "time-locale", () => date.toLocaleTimeString(), dontReplaceSlash);
  1012. template = await Util.evalTemplateVariable(template, "day-locale", () => String(date.getDate()).padStart(2, "0"), dontReplaceSlash);
  1013. template = await Util.evalTemplateVariable(template, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  1014. template = await Util.evalTemplateVariable(template, "year-locale", () => String(date.getFullYear()), dontReplaceSlash);
  1015. template = await Util.evalTemplateVariable(template, "datetime-locale", () => date.toLocaleString(), dontReplaceSlash);
  1016. template = await Util.evalTemplateVariable(template, "datetime-utc", () => date.toUTCString(), dontReplaceSlash);
  1017. template = await Util.evalTemplateVariable(template, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"), dontReplaceSlash);
  1018. template = await Util.evalTemplateVariable(template, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  1019. template = await Util.evalTemplateVariable(template, "year-utc", () => String(date.getUTCFullYear()), dontReplaceSlash);
  1020. template = await Util.evalTemplateVariable(template, "hours-locale", () => String(date.getHours()).padStart(2, "0"), dontReplaceSlash);
  1021. template = await Util.evalTemplateVariable(template, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"), dontReplaceSlash);
  1022. template = await Util.evalTemplateVariable(template, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"), dontReplaceSlash);
  1023. template = await Util.evalTemplateVariable(template, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"), dontReplaceSlash);
  1024. template = await Util.evalTemplateVariable(template, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"), dontReplaceSlash);
  1025. template = await Util.evalTemplateVariable(template, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"), dontReplaceSlash);
  1026. template = await Util.evalTemplateVariable(template, "url-hash", () => url.hash.substring(1), dontReplaceSlash);
  1027. template = await Util.evalTemplateVariable(template, "url-host", () => url.host.replace(/\/$/, ""), dontReplaceSlash);
  1028. template = await Util.evalTemplateVariable(template, "url-hostname", () => url.hostname.replace(/\/$/, ""), dontReplaceSlash);
  1029. template = await Util.evalTemplateVariable(template, "url-href", () => url.href, dontReplaceSlash);
  1030. template = await Util.evalTemplateVariable(template, "url-password", () => url.password, dontReplaceSlash);
  1031. template = await Util.evalTemplateVariable(template, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, ""), dontReplaceSlash === undefined ? true : dontReplaceSlash);
  1032. template = await Util.evalTemplateVariable(template, "url-port", () => url.port, dontReplaceSlash);
  1033. template = await Util.evalTemplateVariable(template, "url-protocol", () => url.protocol, dontReplaceSlash);
  1034. template = await Util.evalTemplateVariable(template, "url-search", () => url.search.substring(1), dontReplaceSlash);
  1035. template = await Util.evalTemplateVariable(template, "url-username", () => url.username, dontReplaceSlash);
  1036. template = await Util.evalTemplateVariable(template, "tab-id", () => String(options.tabId || "No tab id"), dontReplaceSlash);
  1037. template = await Util.evalTemplateVariable(template, "url-last-segment", () => Util.getLastSegment(url), dontReplaceSlash);
  1038. if (content) {
  1039. template = await Util.evalTemplateVariable(template, "digest-sha-256", async () => DocUtil.digest("SHA-256", content), dontReplaceSlash);
  1040. template = await Util.evalTemplateVariable(template, "digest-sha-384", async () => DocUtil.digest("SHA-384", content), dontReplaceSlash);
  1041. template = await Util.evalTemplateVariable(template, "digest-sha-512", async () => DocUtil.digest("SHA-512", content), dontReplaceSlash);
  1042. }
  1043. return template;
  1044. }
  1045. static setBackgroundImage(element, url, style) {
  1046. element.style.setProperty("background-blend-mode", "normal", "important");
  1047. element.style.setProperty("background-clip", "content-box", "important");
  1048. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  1049. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  1050. element.style.setProperty("background-image", url, "important");
  1051. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  1052. element.style.setProperty("background-origin", "content-box", "important");
  1053. element.style.setProperty("background-repeat", "no-repeat", "important");
  1054. }
  1055. static processShortcutIcons(doc) {
  1056. let shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel=\"icon\"], link[href][rel=\"shortcut icon\"]")));
  1057. if (!shortcutIcon) {
  1058. shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel*=\"icon\"]")));
  1059. if (shortcutIcon) {
  1060. shortcutIcon.rel = "icon";
  1061. }
  1062. }
  1063. if (shortcutIcon) {
  1064. doc.querySelectorAll("link[href][rel*=\"icon\"]").forEach(linkElement => {
  1065. if (linkElement != shortcutIcon) {
  1066. linkElement.remove();
  1067. }
  1068. });
  1069. }
  1070. }
  1071. static setFrameEmptySrc(frameElement) {
  1072. if (frameElement.tagName == "OBJECT") {
  1073. frameElement.setAttribute("data", "data:text/html,");
  1074. } else {
  1075. frameElement.removeAttribute("src");
  1076. frameElement.removeAttribute("srcdoc");
  1077. }
  1078. }
  1079. static setFrameContent(frameElement, content) {
  1080. if (frameElement.tagName == "OBJECT") {
  1081. frameElement.setAttribute("data", "data:text/html," + content);
  1082. } else {
  1083. frameElement.setAttribute("srcdoc", content);
  1084. frameElement.removeAttribute("src");
  1085. }
  1086. }
  1087. static isolateElements(rootElement) {
  1088. rootElement.querySelectorAll("*:not(style)").forEach(element => {
  1089. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  1090. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  1091. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  1092. element.remove();
  1093. }
  1094. });
  1095. isolateParentElements(rootElement.parentElement, rootElement);
  1096. function isolateParentElements(parentElement, element) {
  1097. let elementFound = false;
  1098. Array.from(parentElement.childNodes).forEach(node => {
  1099. elementFound = elementFound || (node == element);
  1100. const tagName = node.tagName && node.tagName.toLowerCase();
  1101. if (node != element && tagName != "svg" && tagName != "style" && tagName != "link") {
  1102. if (elementFound) {
  1103. node.remove();
  1104. } else {
  1105. node.hidden = true;
  1106. if (node.childNodes && node.childNodes.length) {
  1107. Array.from(node.childNodes).forEach(node => node.remove());
  1108. }
  1109. }
  1110. }
  1111. });
  1112. element = element.parentElement;
  1113. if (element && element.parentElement && element.parentElement.tagName != "HTML") {
  1114. isolateParentElements(element.parentElement, element);
  1115. }
  1116. }
  1117. }
  1118. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  1119. stylesheetContent = ProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI, options);
  1120. const imports = Util.getImportFunctions(stylesheetContent);
  1121. await Promise.all(imports.map(async cssImport => {
  1122. const match = Util.matchImport(cssImport);
  1123. if (match) {
  1124. let resourceURL = Util.normalizeURL(match.resourceURL);
  1125. if (!Util.testIgnoredPath(resourceURL) && Util.testValidPath(resourceURL, baseURI, options.url)) {
  1126. try {
  1127. resourceURL = DocUtil.resolveURL(match.resourceURL, baseURI);
  1128. } catch (error) {
  1129. // ignored
  1130. }
  1131. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1132. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, validateTextContentType: true };
  1133. const content = await DocUtil.getContent(resourceURL, downloadOptions);
  1134. resourceURL = content.resourceURL;
  1135. let importedStylesheetContent = Util.removeCssComments(content.data);
  1136. if (options.compressCSS) {
  1137. importedStylesheetContent = DocUtil.compressCSS(importedStylesheetContent);
  1138. }
  1139. importedStylesheetContent = Util.wrapMediaQuery(importedStylesheetContent, match.media);
  1140. if (stylesheetContent.includes(cssImport)) {
  1141. importedStylesheetContent = await ProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options);
  1142. stylesheetContent = stylesheetContent.replace(Util.getRegExp(cssImport), importedStylesheetContent);
  1143. }
  1144. }
  1145. }
  1146. }
  1147. }));
  1148. return stylesheetContent;
  1149. }
  1150. static resolveStylesheetURLs(stylesheetContent, baseURI, options) {
  1151. const urlFunctions = Util.getUrlFunctions(stylesheetContent);
  1152. urlFunctions.map(urlFunction => {
  1153. const originalResourceURL = Util.matchURL(urlFunction);
  1154. const resourceURL = Util.normalizeURL(originalResourceURL);
  1155. if (!Util.testIgnoredPath(resourceURL)) {
  1156. if (!resourceURL || Util.testValidPath(resourceURL, baseURI, options.url)) {
  1157. let resolvedURL;
  1158. try {
  1159. resolvedURL = DocUtil.resolveURL(resourceURL, baseURI);
  1160. } catch (error) {
  1161. // ignored
  1162. }
  1163. if (Util.testValidURL(resolvedURL, baseURI, options.url) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  1164. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  1165. }
  1166. } else {
  1167. let newUrlFunction;
  1168. if (originalResourceURL) {
  1169. newUrlFunction = urlFunction.replace(originalResourceURL, EMPTY_DATA_URI);
  1170. } else {
  1171. newUrlFunction = "url(" + EMPTY_DATA_URI + ")";
  1172. }
  1173. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), newUrlFunction);
  1174. }
  1175. } else {
  1176. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  1177. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  1178. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  1179. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  1180. }
  1181. }
  1182. }
  1183. });
  1184. return stylesheetContent;
  1185. }
  1186. static async resolveLinkStylesheetURLs(resourceURL, baseURI, options) {
  1187. resourceURL = Util.normalizeURL(resourceURL);
  1188. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  1189. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charset: options.charset };
  1190. const content = await DocUtil.getContent(resourceURL, downloadOptions);
  1191. resourceURL = content.resourceURL;
  1192. let stylesheetContent = Util.removeCssComments(content.data);
  1193. if (options.compressCSS) {
  1194. stylesheetContent = DocUtil.compressCSS(stylesheetContent);
  1195. }
  1196. stylesheetContent = await ProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  1197. return stylesheetContent;
  1198. }
  1199. }
  1200. static async processStylesheet(cssRules, baseURI, options, cssVariables, batchRequest) {
  1201. const promises = [];
  1202. const removedRules = [];
  1203. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  1204. const ruleData = cssRule.data;
  1205. if (ruleData.type == "Atrule" && ruleData.name == "charset") {
  1206. removedRules.push(cssRule);
  1207. } else if (ruleData.block && ruleData.block.children) {
  1208. if (ruleData.type == "Rule") {
  1209. promises.push(this.processStyle(ruleData.block.children.toArray(), baseURI, options, cssVariables, batchRequest));
  1210. } else if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports")) {
  1211. promises.push(this.processStylesheet(ruleData.block.children, baseURI, options, cssVariables, batchRequest));
  1212. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  1213. promises.push(processFontFaceRule(ruleData));
  1214. }
  1215. }
  1216. }
  1217. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  1218. await Promise.all(promises);
  1219. async function processFontFaceRule(cssRule) {
  1220. await Promise.all(cssRule.block.children.toArray().map(async declaration => {
  1221. if (declaration.type == "Declaration" && declaration.value.children) {
  1222. const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
  1223. await Promise.all(urlFunctions.map(async urlFunction => {
  1224. const originalResourceURL = Util.matchURL(urlFunction);
  1225. const resourceURL = Util.normalizeURL(originalResourceURL);
  1226. if (!Util.testIgnoredPath(resourceURL)) {
  1227. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1228. let { content } = await batchRequest.addURL(resourceURL, true);
  1229. let validResource = content == EMPTY_DATA_URI || content.startsWith(PREFIX_DATA_URI_VND) || content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1230. if (!validResource) {
  1231. validResource = await DocUtil.validFont(urlFunction);
  1232. }
  1233. if (!validResource) {
  1234. content = EMPTY_DATA_URI;
  1235. }
  1236. declaration.value.children.forEach(token => {
  1237. if (token.type == "Url" && DocUtil.removeQuotes(Util.getCSSValue(token.value)) == originalResourceURL) {
  1238. token.value.value = content;
  1239. }
  1240. });
  1241. }
  1242. }
  1243. }));
  1244. }
  1245. }));
  1246. }
  1247. }
  1248. static async processStyle(declarations, baseURI, options, cssVariables, batchRequest) {
  1249. await Promise.all(declarations.map(async declaration => {
  1250. if (declaration.type == "Declaration" && declaration.value.children) {
  1251. const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
  1252. await Promise.all(urlFunctions.map(async urlFunction => {
  1253. const originalResourceURL = Util.matchURL(urlFunction);
  1254. const resourceURL = Util.normalizeURL(originalResourceURL);
  1255. if (!Util.testIgnoredPath(resourceURL)) {
  1256. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1257. let { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, true);
  1258. let variableDefined;
  1259. const tokens = [];
  1260. findURLToken(originalResourceURL, declaration.value.children, (token, parent, rootFunction) => {
  1261. if (duplicate && options.groupDuplicateImages && rootFunction) {
  1262. const value = cssTree.parse("var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")", { context: "value" }).children.head;
  1263. tokens.push({ parent, token, value });
  1264. variableDefined = true;
  1265. } else {
  1266. token.data.value.value = content;
  1267. }
  1268. });
  1269. if (variableDefined) {
  1270. cssVariables.set(indexResource, content);
  1271. tokens.forEach(({ parent, token, value }) => parent.replace(token, value));
  1272. }
  1273. }
  1274. }
  1275. }));
  1276. }
  1277. }));
  1278. function findURLToken(url, children, callback, depth = 0) {
  1279. for (let token = children.head; token; token = token.next) {
  1280. if (token.data.children) {
  1281. findURLToken(url, token.data.children, callback, depth + 1);
  1282. }
  1283. if (token.data.type == "Url" && DocUtil.removeQuotes(Util.getCSSValue(token.data.value)) == url) {
  1284. callback(token, children, depth == 0);
  1285. }
  1286. }
  1287. }
  1288. }
  1289. static async processAttribute(doc, resourceElements, attributeName, prefixDataURI, baseURI, options, cssVariables, styles, batchRequest, processDuplicates, removeElementIfMissing) {
  1290. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1291. let resourceURL = resourceElement.getAttribute(attributeName);
  1292. resourceURL = Util.normalizeURL(resourceURL);
  1293. if (!Util.testIgnoredPath(resourceURL)) {
  1294. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1295. if (Util.testValidPath(resourceURL, baseURI, options.url)) {
  1296. try {
  1297. resourceURL = DocUtil.resolveURL(resourceURL, baseURI);
  1298. } catch (error) {
  1299. // ignored
  1300. }
  1301. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1302. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, resourceElement.tagName == "IMG" && attributeName == "src");
  1303. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1304. resourceElement.remove();
  1305. } else {
  1306. if (content.startsWith(prefixDataURI) || content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) || content.match(PREFIX_DATA_URI_OCTET_STREAM) || content.match(PREFIX_DATA_URI_NULL_STREAM)) {
  1307. const isSVG = content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1308. if (processDuplicates && duplicate && options.groupDuplicateImages && !isSVG) {
  1309. if (Util.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1310. cssVariables.set(indexResource, content);
  1311. const declarationList = cssTree.parse(resourceElement.getAttribute("style"), { context: "declarationList" });
  1312. styles.set(resourceElement, declarationList);
  1313. } else {
  1314. resourceElement.setAttribute(attributeName, content);
  1315. }
  1316. } else {
  1317. resourceElement.setAttribute(attributeName, content);
  1318. }
  1319. }
  1320. }
  1321. }
  1322. }
  1323. }
  1324. }));
  1325. }
  1326. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1327. const attributeName = "xlink:href";
  1328. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1329. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1330. let resourceURL = Util.normalizeURL(originalResourceURL);
  1331. if (Util.testValidPath(resourceURL, baseURI, options.url) && !Util.testIgnoredPath(resourceURL)) {
  1332. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1333. try {
  1334. resourceURL = DocUtil.resolveURL(resourceURL, baseURI);
  1335. } catch (error) {
  1336. // ignored
  1337. }
  1338. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1339. try {
  1340. const { content } = await batchRequest.addURL(resourceURL);
  1341. const DOMParser = DocUtil.getParser();
  1342. if (DOMParser) {
  1343. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1344. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1345. if (hashMatch && hashMatch[0]) {
  1346. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1347. if (symbolElement) {
  1348. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1349. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1350. }
  1351. } else {
  1352. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1353. }
  1354. } else {
  1355. resourceElement.setAttribute(attributeName, "data:image/svg+xml," + content);
  1356. }
  1357. } catch (error) {
  1358. /* ignored */
  1359. }
  1360. }
  1361. } else if (resourceURL == options.url) {
  1362. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1363. }
  1364. }));
  1365. }
  1366. static async processSrcset(resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest) {
  1367. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1368. const srcset = DocUtil.parseSrcset(resourceElement.getAttribute(attributeName));
  1369. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1370. let resourceURL = Util.normalizeURL(srcsetValue.url);
  1371. if (!Util.testIgnoredPath(resourceURL)) {
  1372. if (Util.testValidPath(resourceURL, baseURI, options.url)) {
  1373. try {
  1374. resourceURL = DocUtil.resolveURL(resourceURL, baseURI);
  1375. } catch (error) {
  1376. // ignored
  1377. }
  1378. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1379. const { content } = await batchRequest.addURL(resourceURL, true);
  1380. if (!content.startsWith(prefixDataURI) && !content.startsWith(PREFIX_DATA_URI_NO_MIMETYPE) && !content.match(PREFIX_DATA_URI_OCTET_STREAM) && !content.match(PREFIX_DATA_URI_NULL_STREAM)) {
  1381. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1382. }
  1383. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1384. } else {
  1385. return "";
  1386. }
  1387. } else {
  1388. return "";
  1389. }
  1390. } else {
  1391. return resourceURL + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1392. }
  1393. }));
  1394. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1395. }));
  1396. }
  1397. }
  1398. // ----
  1399. // Util
  1400. // ----
  1401. const DATA_URI_PREFIX = "data:";
  1402. const BLOB_URI_PREFIX = "blob:";
  1403. const HTTP_URI_PREFIX = /^https?:\/\//;
  1404. const FILE_URI_PREFIX = /^file:\/\//;
  1405. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1406. const ABOUT_BLANK_URI = "about:blank";
  1407. const NOT_EMPTY_URL = /^(https?:\/\/|file:\/\/|blob:).+/;
  1408. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1409. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1410. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1411. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1412. const REGEXP_IMPORT_FN = /(@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|}))|(@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|}))|(@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|}))|(@import\s*'(.*?)'\s*(.*?)(;|$|}))|(@import\s*"(.*?)"\s*(.*?)(;|$|}))|(@import\s*(.*?)\s*(.*?)(;|$|}))/gi;
  1413. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1414. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1415. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1416. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1417. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1418. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1419. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1420. class Util {
  1421. static normalizeURL(url) {
  1422. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1423. return url;
  1424. } else {
  1425. return url.split("#")[0];
  1426. }
  1427. }
  1428. static getCSSValue(value) {
  1429. let result = "";
  1430. try {
  1431. result = cssTree.generate(value);
  1432. } catch (error) {
  1433. // ignored
  1434. }
  1435. return result;
  1436. }
  1437. static getOnEventAttributeNames(doc) {
  1438. const element = doc.createElement("div");
  1439. const attributeNames = [];
  1440. for (const propertyName in element) {
  1441. if (propertyName.startsWith("on")) {
  1442. attributeNames.push(propertyName);
  1443. }
  1444. }
  1445. return attributeNames;
  1446. }
  1447. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1448. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1449. if (template.match(replaceRegExp)) {
  1450. let value = await valueGetter();
  1451. if (!dontReplaceSlash) {
  1452. value = value.replace(/\/+/g, "_");
  1453. }
  1454. return template.replace(replaceRegExp, value);
  1455. }
  1456. return template;
  1457. }
  1458. static getLastSegment(url) {
  1459. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1460. if (!lastSegment) {
  1461. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1462. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1463. }
  1464. if (!lastSegment) {
  1465. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1466. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1467. }
  1468. if (!lastSegment) {
  1469. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1470. }
  1471. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1472. return lastSegment;
  1473. }
  1474. static getRegExp(string) {
  1475. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1476. }
  1477. static getUrlFunctions(stylesheetContent) {
  1478. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1479. }
  1480. static getImportFunctions(stylesheetContent) {
  1481. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1482. }
  1483. static findShortcutIcon(shortcutIcons) {
  1484. shortcutIcons = shortcutIcons.filter(linkElement => linkElement.href != EMPTY_IMAGE);
  1485. shortcutIcons.sort((linkElement1, linkElement2) => (parseInt(linkElement2.sizes, 10) || 16) - (parseInt(linkElement1.sizes, 10) || 16));
  1486. return shortcutIcons[0];
  1487. }
  1488. static matchURL(stylesheetContent) {
  1489. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1490. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1491. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1492. return match && match[1];
  1493. }
  1494. static testIgnoredPath(resourceURL) {
  1495. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
  1496. }
  1497. static testValidPath(resourceURL, baseURI, docURL) {
  1498. return resourceURL && resourceURL != baseURI && resourceURL != docURL && !resourceURL.match(EMPTY_URL);
  1499. }
  1500. static testValidURL(resourceURL, baseURI, docURL) {
  1501. return Util.testValidPath(resourceURL, baseURI, docURL) && (resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(FILE_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX)) && resourceURL.match(NOT_EMPTY_URL);
  1502. }
  1503. static matchImport(stylesheetContent) {
  1504. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1505. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1506. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1507. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1508. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1509. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1510. if (match) {
  1511. const [, resourceURL, media] = match;
  1512. return { resourceURL, media };
  1513. }
  1514. }
  1515. static removeCssComments(stylesheetContent) {
  1516. let start, end;
  1517. do {
  1518. start = stylesheetContent.indexOf("/*");
  1519. end = stylesheetContent.indexOf("*/", start + 2);
  1520. if (start != -1 && end != -1) {
  1521. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1522. }
  1523. } while (start != -1 && end != -1);
  1524. return stylesheetContent;
  1525. }
  1526. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1527. if (mediaQuery) {
  1528. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1529. } else {
  1530. return stylesheetContent;
  1531. }
  1532. }
  1533. static replaceImageSource(imgElement, variableName, options) {
  1534. const dataAttributeName = DocUtil.imagesAttributeName(options.sessionId);
  1535. if (imgElement.getAttribute(dataAttributeName) != null) {
  1536. const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  1537. if (imgData.replaceable) {
  1538. imgElement.setAttribute("src", `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="${imgData.size.pxWidth}" height="${imgData.size.pxHeight}"><rect fill-opacity="0"/></svg>`);
  1539. const backgroundStyle = {};
  1540. const backgroundSize = (imgData.objectFit == "content" || imgData.objectFit == "cover") && imgData.objectFit;
  1541. if (backgroundSize) {
  1542. backgroundStyle["background-size"] = imgData.objectFit;
  1543. }
  1544. if (imgData.objectPosition) {
  1545. backgroundStyle["background-position"] = imgData.objectPosition;
  1546. }
  1547. if (imgData.backgroundColor) {
  1548. backgroundStyle["background-color"] = imgData.backgroundColor;
  1549. }
  1550. ProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1551. imgElement.removeAttribute(dataAttributeName);
  1552. return true;
  1553. }
  1554. }
  1555. }
  1556. }
  1557. function log(...args) {
  1558. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1559. }
  1560. // -----
  1561. // Stats
  1562. // -----
  1563. const STATS_DEFAULT_VALUES = {
  1564. discarded: {
  1565. "HTML bytes": 0,
  1566. "hidden elements": 0,
  1567. "HTML imports": 0,
  1568. scripts: 0,
  1569. objects: 0,
  1570. "audio sources": 0,
  1571. "video sources": 0,
  1572. frames: 0,
  1573. "CSS rules": 0,
  1574. canvas: 0,
  1575. stylesheets: 0,
  1576. resources: 0,
  1577. medias: 0
  1578. },
  1579. processed: {
  1580. "HTML bytes": 0,
  1581. "hidden elements": 0,
  1582. "HTML imports": 0,
  1583. scripts: 0,
  1584. objects: 0,
  1585. "audio sources": 0,
  1586. "video sources": 0,
  1587. frames: 0,
  1588. "CSS rules": 0,
  1589. canvas: 0,
  1590. stylesheets: 0,
  1591. resources: 0,
  1592. medias: 0
  1593. }
  1594. };
  1595. class Stats {
  1596. constructor(options) {
  1597. this.options = options;
  1598. if (options.displayStats) {
  1599. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1600. }
  1601. }
  1602. set(type, subType, value) {
  1603. if (this.options.displayStats) {
  1604. this.data[type][subType] = value;
  1605. }
  1606. }
  1607. add(type, subType, value) {
  1608. if (this.options.displayStats) {
  1609. this.data[type][subType] += value;
  1610. }
  1611. }
  1612. addAll(pageData) {
  1613. if (this.options.displayStats) {
  1614. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1615. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1616. }
  1617. }
  1618. }
  1619. return { getClass };
  1620. })();