single-file-core.js 72 KB

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