single-file-core.js 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731
  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("link[rel*=stylesheet][rel*=alternate][title]").forEach(element => element.remove());
  417. this.doc.querySelectorAll("meta[http-equiv=\"content-security-policy\"]").forEach(element => element.remove());
  418. if (this.options.compressHTML) {
  419. this.doc.querySelectorAll("input[type=hidden]").forEach(element => element.remove());
  420. }
  421. this.doc.querySelectorAll("a[ping]").forEach(element => element.removeAttribute("ping"));
  422. if (this.options.removeScripts) {
  423. this.onEventAttributeNames.forEach(attributeName => this.doc.querySelectorAll("[" + attributeName + "]").forEach(element => element.removeAttribute(attributeName)));
  424. this.doc.querySelectorAll("[href]").forEach(element => {
  425. if (element.href && element.href.match && element.href.match(/^\s*javascript:/)) {
  426. element.setAttribute("href", "");
  427. }
  428. });
  429. this.doc.querySelectorAll("[src]").forEach(element => {
  430. if (element.src && element.src.match(/^\s*javascript:/)) {
  431. element.removeAttribute("src");
  432. }
  433. });
  434. }
  435. const audioSourceElements = this.doc.querySelectorAll("audio[src], audio > source[src]");
  436. this.stats.set("processed", "audio sources", audioSourceElements.length);
  437. if (this.options.removeAudioSrc) {
  438. this.stats.set("discarded", "audio sources", audioSourceElements.length);
  439. audioSourceElements.forEach(element => {
  440. if (element.tagName == "SOURCE") {
  441. element.remove();
  442. } else {
  443. audioSourceElements.forEach(element => element.removeAttribute("src"));
  444. }
  445. });
  446. }
  447. const videoSourceElements = this.doc.querySelectorAll("video[src], video > source");
  448. this.stats.set("processed", "video sources", videoSourceElements.length);
  449. if (this.options.removeVideoSrc) {
  450. this.stats.set("discarded", "video sources", videoSourceElements.length);
  451. videoSourceElements.forEach(element => {
  452. if (element.tagName == "SOURCE") {
  453. element.remove();
  454. } else {
  455. videoSourceElements.forEach(element => element.removeAttribute("src"));
  456. }
  457. });
  458. }
  459. }
  460. async end() {
  461. const metaCharset = this.doc.head.querySelector("meta[charset]");
  462. if (metaCharset) {
  463. this.doc.head.insertBefore(metaCharset, this.doc.head.firstChild);
  464. }
  465. this.doc.querySelectorAll("base").forEach(element => element.remove());
  466. if (this.doc.head.querySelectorAll("*").length == 1 && metaCharset && this.doc.body.childNodes.length == 0) {
  467. this.doc.head.querySelector("meta[charset]").remove();
  468. }
  469. const titleElement = this.doc.querySelector("title");
  470. const descriptionElement = this.doc.querySelector("meta[name=description]");
  471. const authorElement = this.doc.querySelector("meta[name=author]");
  472. const creatorElement = this.doc.querySelector("meta[name=creator]");
  473. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  474. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  475. this.options.infobarContent = await ProcessorHelper.evalTemplate(this.options.infobarTemplate, this.options, null, true);
  476. this.options.info = {
  477. description: descriptionElement && descriptionElement.content ? descriptionElement.content.trim() : "",
  478. lang: this.doc.documentElement.lang,
  479. author: authorElement && authorElement.content ? authorElement.content.trim() : "",
  480. creator: creatorElement && creatorElement.content ? creatorElement.content.trim() : "",
  481. publisher: publisherElement && publisherElement.content ? publisherElement.content.trim() : ""
  482. };
  483. }
  484. preProcessPage() {
  485. this.doc.querySelectorAll("singlefile-infobar, singlefile-mask, singlefile-logs-window").forEach(element => element.remove());
  486. if (this.options.win) {
  487. 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));
  488. }
  489. if (this.options.imageData) {
  490. const dataAttributeName = DocUtil.imagesAttributeName(this.options.sessionId);
  491. this.doc.querySelectorAll("img").forEach(imgElement => {
  492. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  493. if (this.options.removeHiddenElements && imgData.size && !imgData.size.pxWidth && !imgData.size.pxHeight) {
  494. imgElement.setAttribute("src", EMPTY_IMAGE);
  495. } else if (imgData.currentSrc) {
  496. imgElement.setAttribute("src", imgData.currentSrc);
  497. }
  498. });
  499. if (this.options.lazyLoadImages) {
  500. this.doc.querySelectorAll("img[data-src]").forEach(imgElement => {
  501. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  502. if ((!imgElement.getAttribute("src") || imgElement.getAttribute("src") == EMPTY_IMAGE) && imgElement.getAttribute("data-src")) {
  503. imgData.src = imgElement.dataset.src;
  504. imgElement.setAttribute("src", imgElement.dataset.src);
  505. imgElement.removeAttribute("data-src");
  506. }
  507. });
  508. this.doc.querySelectorAll("img[data-srcset]").forEach(imgElement => {
  509. if (!imgElement.getAttribute("srcset") && imgElement.getAttribute("data-srcset")) {
  510. imgElement.setAttribute("srcset", imgElement.dataset.srcset);
  511. imgElement.removeAttribute("data-srcset");
  512. }
  513. });
  514. }
  515. }
  516. }
  517. removeScripts() {
  518. const scriptElements = this.doc.querySelectorAll("script:not([type=\"application/ld+json\"])");
  519. this.stats.set("discarded", "scripts", scriptElements.length);
  520. this.stats.set("processed", "scripts", scriptElements.length);
  521. scriptElements.forEach(element => element.remove());
  522. }
  523. removeFrames() {
  524. const frameElements = this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]");
  525. this.stats.set("discarded", "frames", frameElements.length);
  526. this.stats.set("processed", "frames", frameElements.length);
  527. this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]").forEach(element => element.remove());
  528. }
  529. removeImports() {
  530. const importElements = this.doc.querySelectorAll("link[rel=import]");
  531. this.stats.set("discarded", "HTML imports", importElements.length);
  532. this.stats.set("processed", "HTML imports", importElements.length);
  533. importElements.forEach(element => element.remove());
  534. }
  535. resetCharsetMeta() {
  536. let charset;
  537. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  538. const charsetDeclaration = element.content.split(";")[1];
  539. if (charsetDeclaration && !charset) {
  540. charset = charsetDeclaration.split("=")[1];
  541. if (charset) {
  542. this.charset = charset.trim().toLowerCase();
  543. }
  544. }
  545. element.remove();
  546. });
  547. const metaElement = this.doc.createElement("meta");
  548. metaElement.setAttribute("charset", "utf-8");
  549. if (this.doc.head.firstChild) {
  550. this.doc.head.insertBefore(metaElement, this.doc.head.firstChild);
  551. } else {
  552. this.doc.head.appendChild(metaElement);
  553. }
  554. }
  555. insertFaviconLink() {
  556. let faviconElement = this.doc.querySelector("link[href][rel=\"icon\"]");
  557. if (!faviconElement) {
  558. faviconElement = this.doc.querySelector("link[href][rel=\"shortcut icon\"]");
  559. }
  560. if (!faviconElement) {
  561. faviconElement = this.doc.createElement("link");
  562. faviconElement.setAttribute("type", "image/x-icon");
  563. faviconElement.setAttribute("rel", "shortcut icon");
  564. faviconElement.setAttribute("href", "/favicon.ico");
  565. }
  566. this.doc.head.appendChild(faviconElement);
  567. }
  568. resolveHrefs() {
  569. this.doc.querySelectorAll("a[href], area[href], link[href]").forEach(element => {
  570. const href = element.getAttribute("href").trim();
  571. if (!Util.testIgnoredPath(href) && !href.startsWith("#")) {
  572. try {
  573. element.setAttribute("href", DocUtil.resolveURL(href, this.options.baseURI || this.options.url));
  574. } catch (error) {
  575. // ignored
  576. }
  577. }
  578. });
  579. }
  580. removeUnusedStyles() {
  581. if (!this.mediaAllInfo) {
  582. this.mediaAllInfo = DocUtil.getMediaAllInfo(this.doc, this.stylesheets, this.styles);
  583. }
  584. const stats = DocUtil.minifyCSSRules(this.stylesheets, this.styles, this.mediaAllInfo);
  585. this.stats.set("processed", "CSS rules", stats.processed);
  586. this.stats.set("discarded", "CSS rules", stats.discarded);
  587. }
  588. removeUnusedFonts() {
  589. DocUtil.removeUnusedFonts(this.doc, this.stylesheets, this.styles, this.options);
  590. }
  591. removeAlternativeFonts() {
  592. DocUtil.removeAlternativeFonts(this.doc, this.stylesheets);
  593. }
  594. removeAlternativeImages() {
  595. DocUtil.removeAlternativeImages(this.doc);
  596. }
  597. removeHiddenElements() {
  598. const hiddenElements = this.doc.querySelectorAll("[" + DocUtil.removedContentAttributeName(this.options.sessionId) + "]");
  599. this.stats.set("discarded", "hidden elements", hiddenElements.length);
  600. this.stats.set("processed", "hidden elements", hiddenElements.length);
  601. hiddenElements.forEach(element => element.remove());
  602. }
  603. compressHTML() {
  604. let size;
  605. if (this.options.displayStats) {
  606. size = DocUtil.getContentSize(this.doc.documentElement.outerHTML);
  607. }
  608. DocUtil.minifyHTML(this.doc, { preservedSpaceAttributeName: DocUtil.preservedSpaceAttributeName(this.options.sessionId) });
  609. if (this.options.displayStats) {
  610. this.stats.add("discarded", "HTML bytes", size - DocUtil.getContentSize(this.doc.documentElement.outerHTML));
  611. }
  612. }
  613. removeAlternativeMedias() {
  614. const stats = DocUtil.minifyMedias(this.stylesheets);
  615. this.stats.set("processed", "medias", stats.processed);
  616. this.stats.set("discarded", "medias", stats.discarded);
  617. }
  618. replaceCanvasElements() {
  619. if (this.options.canvasData) {
  620. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  621. const canvasData = this.options.canvasData[indexCanvasElement];
  622. if (canvasData) {
  623. ProcessorHelper.setBackgroundImage(canvasElement, "url(" + canvasData.dataURI + ")");
  624. this.stats.add("processed", "canvas", 1);
  625. }
  626. });
  627. }
  628. }
  629. insertFonts() {
  630. if (this.options.fontsData && this.options.fontsData.length) {
  631. let stylesheetContent = "";
  632. this.options.fontsData.forEach(fontStyles => {
  633. if (fontStyles["font-family"] && fontStyles.src) {
  634. stylesheetContent += "@font-face{";
  635. let stylesContent = "";
  636. Object.keys(fontStyles).forEach(fontStyle => {
  637. if (stylesContent) {
  638. stylesContent += ";";
  639. }
  640. stylesContent += fontStyle + ":" + fontStyles[fontStyle];
  641. });
  642. stylesheetContent += stylesContent + "}";
  643. }
  644. });
  645. if (stylesheetContent) {
  646. const styleElement = this.doc.createElement("style");
  647. styleElement.textContent = stylesheetContent;
  648. const existingStyleElement = this.doc.querySelector("style");
  649. if (existingStyleElement) {
  650. existingStyleElement.parentElement.insertBefore(styleElement, existingStyleElement);
  651. } else {
  652. this.doc.head.insertBefore(styleElement, this.doc.head.firstChild);
  653. }
  654. }
  655. }
  656. }
  657. replaceStyleContents() {
  658. if (this.options.stylesheetContents) {
  659. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  660. if (this.options.stylesheetContents[styleIndex]) {
  661. styleElement.textContent = this.options.stylesheetContents[styleIndex];
  662. }
  663. });
  664. }
  665. }
  666. insertShadowRootContents() {
  667. if (this.options.shadowRootContents) {
  668. this.doc.querySelectorAll("[" + DocUtil.shadowRootAttributeName(this.options.sessionId) + "]").forEach((element, elementIndex) => {
  669. const elementInfo = this.options.shadowRootContents[elementIndex];
  670. if (elementInfo) {
  671. const frameElement = this.doc.createElement("iframe");
  672. frameElement.setAttribute("style", "all:initial!important;border:0!important;width:100%!important;height:" + elementInfo.height + "px!important");
  673. const windowId = "shadow-" + this.options.framesData.length;
  674. frameElement.setAttribute(DocUtil.windowIdAttributeName(this.options.sessionId), windowId);
  675. this.options.framesData.push({ windowId, content: elementInfo.content, baseURI: this.baseURI });
  676. element.appendChild(frameElement);
  677. }
  678. });
  679. }
  680. }
  681. insertVideoPosters() {
  682. if (this.options.postersData) {
  683. this.doc.querySelectorAll("video[src], video > source[src]").forEach((element, videoIndex) => {
  684. let videoElement;
  685. if (element.tagName == "VIDEO") {
  686. videoElement = element;
  687. } else {
  688. videoElement = element.parentElement;
  689. }
  690. if (!videoElement.poster && this.options.postersData[videoIndex]) {
  691. videoElement.setAttribute("poster", this.options.postersData[videoIndex]);
  692. }
  693. });
  694. }
  695. }
  696. async processPageResources() {
  697. const processAttributeArgs = [
  698. ["link[href][rel*=\"icon\"]", "href", "data:", false, true],
  699. ["object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]", "data", PREFIX_DATA_URI_IMAGE_SVG],
  700. ["img[src], input[src][type=image]", "src", PREFIX_DATA_URI_IMAGE, true],
  701. ["embed[src*=\".svg\"]", "src", PREFIX_DATA_URI_IMAGE_SVG],
  702. ["video[poster]", "poster", PREFIX_DATA_URI_IMAGE],
  703. ["*[background]", "background", PREFIX_DATA_URI_IMAGE],
  704. ["image", "xlink:href", PREFIX_DATA_URI_IMAGE]
  705. ];
  706. let resourcePromises = processAttributeArgs.map(([selector, attributeName, prefixDataURI, processDuplicates, removeElementIfMissing]) =>
  707. ProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), attributeName, prefixDataURI, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest, processDuplicates, removeElementIfMissing)
  708. );
  709. resourcePromises = resourcePromises.concat([
  710. ProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.options, this.batchRequest),
  711. ProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", PREFIX_DATA_URI_IMAGE, this.baseURI, this.options, this.batchRequest)
  712. ]);
  713. if (!this.options.removeAudioSrc) {
  714. 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));
  715. }
  716. if (!this.options.removeVideoSrc) {
  717. 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));
  718. }
  719. await Promise.all(resourcePromises);
  720. ProcessorHelper.processShortcutIcons(this.doc);
  721. }
  722. async resolveStylesheetURLs() {
  723. await Promise.all(Array.from(this.doc.querySelectorAll("style, link[rel*=stylesheet]"))
  724. .map(async element => {
  725. let mediaText;
  726. if (element.media) {
  727. mediaText = element.media.toLowerCase();
  728. }
  729. this.stylesheets.set(element, { mediaText });
  730. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, url: this.options.url, charset: this.charset, compressCSS: this.options.compressCSS };
  731. let stylesheetContent;
  732. if (element.tagName.toLowerCase() == "link") {
  733. if (element.charset) {
  734. options.charset = element.charset;
  735. }
  736. stylesheetContent = await ProcessorHelper.resolveLinkStylesheetURLs(element.href, this.baseURI, options);
  737. } else {
  738. stylesheetContent = await ProcessorHelper.resolveImportURLs(element.textContent, this.baseURI, options);
  739. }
  740. let stylesheet;
  741. try {
  742. stylesheet = cssTree.parse(stylesheetContent);
  743. } catch (error) {
  744. // ignored
  745. }
  746. if (stylesheet && stylesheet.children) {
  747. if (this.options.compressCSS) {
  748. ProcessorHelper.removeSingleLineCssComments(stylesheet);
  749. }
  750. this.stylesheets.get(element).stylesheet = stylesheet;
  751. } else {
  752. this.stylesheets.delete(element);
  753. }
  754. }));
  755. }
  756. async processStylesheets() {
  757. await Promise.all(Array.from(this.stylesheets).map(([, stylesheetInfo]) =>
  758. ProcessorHelper.processStylesheet(stylesheetInfo.stylesheet.children, this.baseURI, this.options, this.cssVariables, this.batchRequest)
  759. ));
  760. }
  761. replaceStylesheets() {
  762. this.doc.querySelectorAll("style").forEach(styleElement => {
  763. const stylesheetInfo = this.stylesheets.get(styleElement);
  764. if (stylesheetInfo) {
  765. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  766. styleElement.textContent = stylesheetContent;
  767. if (stylesheetInfo.mediaText) {
  768. styleElement.media = stylesheetInfo.mediaText;
  769. }
  770. } else {
  771. styleElement.remove();
  772. }
  773. });
  774. this.doc.querySelectorAll("link[rel*=stylesheet]").forEach(linkElement => {
  775. const stylesheetInfo = this.stylesheets.get(linkElement);
  776. if (stylesheetInfo) {
  777. const styleElement = this.doc.createElement("style");
  778. if (stylesheetInfo.mediaText) {
  779. styleElement.media = stylesheetInfo.mediaText;
  780. }
  781. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  782. styleElement.textContent = stylesheetContent;
  783. linkElement.parentElement.replaceChild(styleElement, linkElement);
  784. } else {
  785. linkElement.remove();
  786. }
  787. });
  788. }
  789. insertVariables() {
  790. if (this.cssVariables.size) {
  791. const styleElement = this.doc.createElement("style");
  792. const firstStyleElement = this.doc.head.querySelector("style");
  793. if (firstStyleElement) {
  794. this.doc.head.insertBefore(styleElement, firstStyleElement);
  795. } else {
  796. this.doc.head.appendChild(styleElement);
  797. }
  798. let stylesheetContent = "";
  799. this.cssVariables.forEach((content, indexResource) => {
  800. if (stylesheetContent) {
  801. stylesheetContent += ";";
  802. }
  803. stylesheetContent += `${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")`;
  804. });
  805. styleElement.textContent = ":root{" + stylesheetContent + "}";
  806. }
  807. }
  808. async processScripts() {
  809. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  810. let resourceURL;
  811. try {
  812. resourceURL = DocUtil.resolveURL(scriptElement.src, this.baseURI);
  813. } catch (error) {
  814. // ignored
  815. }
  816. if (Util.testValidURL(resourceURL, this.baseURI, this.options.url)) {
  817. this.stats.add("processed", "scripts", 1);
  818. const content = await DocUtil.getContent(scriptElement.src, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  819. let scriptContent = content.data.replace(/<\//gi, "<\\/");
  820. try {
  821. Function(scriptContent);
  822. } catch (error) {
  823. scriptContent = content.data.replace(/<\//gi, "<\\\\/");
  824. }
  825. try {
  826. Function(scriptContent);
  827. scriptContent = scriptContent.replace(/\/>/gi, "\\/>");
  828. } catch (error) {
  829. // ignored
  830. }
  831. if (scriptContent) {
  832. scriptElement.textContent = scriptContent;
  833. }
  834. }
  835. scriptElement.removeAttribute("src");
  836. }));
  837. }
  838. async resolveFrameURLs() {
  839. if (this.options.framesData) {
  840. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  841. await Promise.all(frameElements.map(async frameElement => {
  842. ProcessorHelper.setFrameEmptySrc(frameElement);
  843. const frameWindowId = frameElement.getAttribute(DocUtil.windowIdAttributeName(this.options.sessionId));
  844. if (frameWindowId) {
  845. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  846. if (frameData) {
  847. await initializeProcessor(frameData, frameElement, frameWindowId, this.batchRequest, Object.create(this.options));
  848. }
  849. }
  850. }));
  851. }
  852. async function initializeProcessor(frameData, frameElement, frameWindowId, batchRequest, options) {
  853. options.insertSingleFileComment = false;
  854. options.insertFaviconLink = false;
  855. options.doc = null;
  856. options.win = null;
  857. options.url = frameData.baseURI;
  858. options.windowId = frameWindowId;
  859. if (frameData.content) {
  860. options.content = frameData.content;
  861. options.canvasData = frameData.canvasData;
  862. options.stylesheetContents = frameData.stylesheetContents;
  863. options.fontsData = frameData.fontsData;
  864. options.imageData = frameData.imageData;
  865. options.usedFonts = frameData.usedFonts;
  866. frameData.processor = new Runner(options);
  867. frameData.frameElement = frameElement;
  868. await frameData.processor.loadPage();
  869. await frameData.processor.initialize();
  870. frameData.maxResources = batchRequest.getMaxResources();
  871. }
  872. }
  873. }
  874. async processFrames() {
  875. if (this.options.framesData) {
  876. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  877. await Promise.all(frameElements.map(async frameElement => {
  878. const frameWindowId = frameElement.getAttribute(DocUtil.windowIdAttributeName(this.options.sessionId));
  879. if (frameWindowId) {
  880. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  881. if (frameData) {
  882. if (frameData.processor) {
  883. this.stats.add("processed", "frames", 1);
  884. await frameData.processor.run();
  885. const pageData = await frameData.processor.getPageData();
  886. frameElement.removeAttribute(DocUtil.windowIdAttributeName(this.options.sessionId));
  887. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  888. frameElement.setAttribute("sandbox", "allow-scripts allow-same-origin");
  889. } else {
  890. frameElement.setAttribute("sandbox", "");
  891. }
  892. ProcessorHelper.setFrameContent(frameElement, pageData.content);
  893. this.stats.addAll(pageData);
  894. } else {
  895. this.stats.add("discarded", "frames", 1);
  896. }
  897. }
  898. }
  899. }));
  900. }
  901. }
  902. async resolveHtmlImportURLs() {
  903. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  904. if (!this.relImportProcessors) {
  905. this.relImportProcessors = new Map();
  906. }
  907. await Promise.all(linkElements.map(async linkElement => {
  908. const resourceURL = linkElement.href;
  909. linkElement.removeAttribute("href");
  910. const options = Object.create(this.options);
  911. options.insertSingleFileComment = false;
  912. options.insertFaviconLink = false;
  913. options.doc = null;
  914. options.win = null;
  915. options.url = resourceURL;
  916. if (!Util.testIgnoredPath(resourceURL) && Util.testValidPath(resourceURL, this.baseURI, this.options.url)) {
  917. const processor = new Runner(options);
  918. this.relImportProcessors.set(linkElement, processor);
  919. await processor.loadPage();
  920. return processor.initialize();
  921. }
  922. }));
  923. }
  924. async processHtmlImports() {
  925. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  926. await Promise.all(linkElements.map(async linkElement => {
  927. const processor = this.relImportProcessors.get(linkElement);
  928. if (processor) {
  929. this.stats.add("processed", "HTML imports", 1);
  930. this.relImportProcessors.delete(linkElement);
  931. const pageData = await processor.getPageData();
  932. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  933. this.stats.addAll(pageData);
  934. } else {
  935. this.stats.add("discarded", "HTML imports", 1);
  936. }
  937. }));
  938. }
  939. resolveStyleAttributeURLs() {
  940. this.doc.querySelectorAll("[style]").forEach(element => {
  941. let styleContent = element.getAttribute("style");
  942. if (this.options.compressCSS) {
  943. styleContent = DocUtil.compressCSS(styleContent);
  944. }
  945. styleContent = ProcessorHelper.resolveStylesheetURLs(styleContent, this.baseURI, this.options);
  946. const declarationList = cssTree.parse(styleContent, { context: "declarationList" });
  947. this.styles.set(element, declarationList);
  948. });
  949. }
  950. async processStyleAttributes() {
  951. return Promise.all(Array.from(this.styles).map(([, declarationList]) =>
  952. ProcessorHelper.processStyle(declarationList.children.toArray(), this.baseURI, this.options, this.cssVariables, this.batchRequest)
  953. ));
  954. }
  955. replaceStyleAttributes() {
  956. this.doc.querySelectorAll("[style]").forEach(async element => {
  957. const declarations = this.styles.get(element);
  958. if (declarations) {
  959. let styleContent = cssTree.generate(declarations);
  960. element.setAttribute("style", styleContent);
  961. } else {
  962. element.setAttribute("style", "");
  963. }
  964. });
  965. }
  966. }
  967. // ---------------
  968. // ProcessorHelper
  969. // ---------------
  970. const REGEXP_AMP = /&/g;
  971. const REGEXP_NBSP = /\u00a0/g;
  972. const REGEXP_START_TAG = /</g;
  973. const REGEXP_END_TAG = />/g;
  974. const REGEXP_URL_HASH = /(#.+?)$/;
  975. const PREFIX_DATA_URI_IMAGE = "data:image/";
  976. const PREFIX_DATA_URI_AUDIO = "data:audio/";
  977. const PREFIX_DATA_URI_VIDEO = "data:video/";
  978. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  979. const PREFIX_DATA_URI_NO_MIMETYPE = "data:;";
  980. const PREFIX_DATA_URI_OCTET_STREAM = /^data:(application|binary)\/octet-stream/;
  981. const PREFIX_DATA_URI_NULL_STREAM = /^data:null;/;
  982. const PREFIX_DATA_URI_VND = "data:application/vnd.";
  983. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  984. class ProcessorHelper {
  985. static async evalTemplate(template, options, content, dontReplaceSlash) {
  986. const date = new Date();
  987. const url = DocUtil.parseURL(options.url);
  988. template = await Util.evalTemplateVariable(template, "page-title", () => options.title || "No title", dontReplaceSlash);
  989. template = await Util.evalTemplateVariable(template, "page-language", () => options.info.lang || "No language", dontReplaceSlash);
  990. template = await Util.evalTemplateVariable(template, "page-description", () => options.info.description || "No description", dontReplaceSlash);
  991. template = await Util.evalTemplateVariable(template, "page-author", () => options.info.author || "No author", dontReplaceSlash);
  992. template = await Util.evalTemplateVariable(template, "page-creator", () => options.info.creator || "No creator", dontReplaceSlash);
  993. template = await Util.evalTemplateVariable(template, "page-publisher", () => options.info.publisher || "No publisher", dontReplaceSlash);
  994. template = await Util.evalTemplateVariable(template, "datetime-iso", () => date.toISOString(), dontReplaceSlash);
  995. template = await Util.evalTemplateVariable(template, "date-iso", () => date.toISOString().split("T")[0], dontReplaceSlash);
  996. template = await Util.evalTemplateVariable(template, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0], dontReplaceSlash);
  997. template = await Util.evalTemplateVariable(template, "date-locale", () => date.toLocaleDateString(), dontReplaceSlash);
  998. template = await Util.evalTemplateVariable(template, "time-locale", () => date.toLocaleTimeString(), dontReplaceSlash);
  999. template = await Util.evalTemplateVariable(template, "day-locale", () => String(date.getDate()).padStart(2, "0"), dontReplaceSlash);
  1000. template = await Util.evalTemplateVariable(template, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  1001. template = await Util.evalTemplateVariable(template, "year-locale", () => String(date.getFullYear()), dontReplaceSlash);
  1002. template = await Util.evalTemplateVariable(template, "datetime-locale", () => date.toLocaleString(), dontReplaceSlash);
  1003. template = await Util.evalTemplateVariable(template, "datetime-utc", () => date.toUTCString(), dontReplaceSlash);
  1004. template = await Util.evalTemplateVariable(template, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"), dontReplaceSlash);
  1005. template = await Util.evalTemplateVariable(template, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  1006. template = await Util.evalTemplateVariable(template, "year-utc", () => String(date.getUTCFullYear()), dontReplaceSlash);
  1007. template = await Util.evalTemplateVariable(template, "hours-locale", () => String(date.getHours()).padStart(2, "0"), dontReplaceSlash);
  1008. template = await Util.evalTemplateVariable(template, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"), dontReplaceSlash);
  1009. template = await Util.evalTemplateVariable(template, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"), dontReplaceSlash);
  1010. template = await Util.evalTemplateVariable(template, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"), dontReplaceSlash);
  1011. template = await Util.evalTemplateVariable(template, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"), dontReplaceSlash);
  1012. template = await Util.evalTemplateVariable(template, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"), dontReplaceSlash);
  1013. template = await Util.evalTemplateVariable(template, "url-hash", () => url.hash.substring(1) || "No hash", dontReplaceSlash);
  1014. template = await Util.evalTemplateVariable(template, "url-host", () => url.host.replace(/\/$/, "") || "No host", dontReplaceSlash);
  1015. template = await Util.evalTemplateVariable(template, "url-hostname", () => url.hostname.replace(/\/$/, "") || "No hostname", dontReplaceSlash);
  1016. template = await Util.evalTemplateVariable(template, "url-href", () => url.href || "No href", dontReplaceSlash);
  1017. template = await Util.evalTemplateVariable(template, "url-password", () => url.password || "No password", dontReplaceSlash);
  1018. template = await Util.evalTemplateVariable(template, "url-pathname", () => url.pathname.replace(/^\//, "").replace(/\/$/, "") || "No pathname", dontReplaceSlash === undefined ? true : dontReplaceSlash);
  1019. template = await Util.evalTemplateVariable(template, "url-port", () => url.port || "No port", dontReplaceSlash);
  1020. template = await Util.evalTemplateVariable(template, "url-protocol", () => url.protocol || "No protocol", dontReplaceSlash);
  1021. template = await Util.evalTemplateVariable(template, "url-search", () => url.search.substring(1) || "No search", dontReplaceSlash);
  1022. template = await Util.evalTemplateVariable(template, "url-username", () => url.username || "No username", dontReplaceSlash);
  1023. template = await Util.evalTemplateVariable(template, "tab-id", () => String(options.tabId || "No tab id"), dontReplaceSlash);
  1024. template = await Util.evalTemplateVariable(template, "url-last-segment", () => Util.getLastSegment(url) || "No last segment", dontReplaceSlash);
  1025. if (content) {
  1026. template = await Util.evalTemplateVariable(template, "digest-sha-256", async () => DocUtil.digest("SHA-256", content), dontReplaceSlash);
  1027. template = await Util.evalTemplateVariable(template, "digest-sha-384", async () => DocUtil.digest("SHA-384", content), dontReplaceSlash);
  1028. template = await Util.evalTemplateVariable(template, "digest-sha-512", async () => DocUtil.digest("SHA-512", content), dontReplaceSlash);
  1029. }
  1030. return template;
  1031. }
  1032. static setBackgroundImage(element, url, style) {
  1033. element.style.setProperty("background-blend-mode", "normal", "important");
  1034. element.style.setProperty("background-clip", "border-box", "important");
  1035. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  1036. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  1037. element.style.setProperty("background-image", url, "important");
  1038. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  1039. element.style.setProperty("background-origin", "content-box", "important");
  1040. element.style.setProperty("background-repeat", "no-repeat", "important");
  1041. }
  1042. static processShortcutIcons(doc) {
  1043. let shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel=\"icon\"], link[href][rel=\"shortcut icon\"]")));
  1044. if (!shortcutIcon) {
  1045. shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel*=\"icon\"]")));
  1046. if (shortcutIcon) {
  1047. shortcutIcon.rel = "icon";
  1048. }
  1049. }
  1050. if (shortcutIcon) {
  1051. doc.querySelectorAll("link[href][rel*=\"icon\"]").forEach(linkElement => {
  1052. if (linkElement != shortcutIcon) {
  1053. linkElement.remove();
  1054. }
  1055. });
  1056. }
  1057. }
  1058. static setFrameEmptySrc(frameElement) {
  1059. if (frameElement.tagName == "OBJECT") {
  1060. frameElement.setAttribute("data", "data:text/html,");
  1061. } else {
  1062. frameElement.removeAttribute("src");
  1063. frameElement.removeAttribute("srcdoc");
  1064. }
  1065. }
  1066. static setFrameContent(frameElement, content) {
  1067. if (frameElement.tagName == "OBJECT") {
  1068. frameElement.setAttribute("data", "data:text/html," + content);
  1069. } else {
  1070. frameElement.setAttribute("srcdoc", content);
  1071. frameElement.removeAttribute("src");
  1072. }
  1073. }
  1074. static isolateElements(rootElement) {
  1075. rootElement.querySelectorAll("*:not(style)").forEach(element => {
  1076. if (element.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "") {
  1077. element.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  1078. } else if (!element.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]")) {
  1079. element.remove();
  1080. }
  1081. });
  1082. isolateParentElements(rootElement.parentElement, rootElement);
  1083. function isolateParentElements(parentElement, element) {
  1084. let elementFound = false;
  1085. Array.from(parentElement.childNodes).forEach(node => {
  1086. elementFound = elementFound || (node == element);
  1087. const tagName = node.tagName && node.tagName.toLowerCase();
  1088. if (node != element && tagName != "svg" && tagName != "style" && tagName != "link") {
  1089. if (elementFound) {
  1090. node.remove();
  1091. } else {
  1092. node.hidden = true;
  1093. if (node.childNodes && node.childNodes.length) {
  1094. Array.from(node.childNodes).forEach(node => node.remove());
  1095. }
  1096. }
  1097. }
  1098. });
  1099. element = element.parentElement;
  1100. if (element && element.parentElement && element.parentElement.tagName != "HTML") {
  1101. isolateParentElements(element.parentElement, element);
  1102. }
  1103. }
  1104. }
  1105. static removeSingleLineCssComments(stylesheet) {
  1106. const removedRules = [];
  1107. for (let cssRule = stylesheet.children.head; cssRule; cssRule = cssRule.next) {
  1108. const ruleData = cssRule.data;
  1109. if (ruleData.type == "Raw" && ruleData.value && ruleData.value.trim().startsWith("//")) {
  1110. removedRules.push(cssRule);
  1111. }
  1112. }
  1113. removedRules.forEach(cssRule => stylesheet.children.remove(cssRule));
  1114. }
  1115. static async resolveImportURLs(stylesheetContent, baseURI, options) {
  1116. stylesheetContent = ProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI, options);
  1117. const imports = Util.getImportFunctions(stylesheetContent);
  1118. await Promise.all(imports.map(async cssImport => {
  1119. const match = Util.matchImport(cssImport);
  1120. if (match) {
  1121. let resourceURL = Util.normalizeURL(match.resourceURL);
  1122. if (!Util.testIgnoredPath(resourceURL) && Util.testValidPath(resourceURL, baseURI, options.url)) {
  1123. try {
  1124. resourceURL = DocUtil.resolveURL(match.resourceURL, baseURI);
  1125. } catch (error) {
  1126. // ignored
  1127. }
  1128. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1129. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, validateTextContentType: true };
  1130. const content = await DocUtil.getContent(resourceURL, downloadOptions);
  1131. resourceURL = content.resourceURL;
  1132. let importedStylesheetContent = Util.removeCssComments(content.data);
  1133. if (options.compressCSS) {
  1134. importedStylesheetContent = DocUtil.compressCSS(importedStylesheetContent);
  1135. }
  1136. importedStylesheetContent = Util.wrapMediaQuery(importedStylesheetContent, match.media);
  1137. if (stylesheetContent.includes(cssImport)) {
  1138. importedStylesheetContent = await ProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options);
  1139. stylesheetContent = stylesheetContent.replace(Util.getRegExp(cssImport), importedStylesheetContent);
  1140. }
  1141. }
  1142. }
  1143. }
  1144. }));
  1145. return stylesheetContent;
  1146. }
  1147. static resolveStylesheetURLs(stylesheetContent, baseURI, options) {
  1148. const urlFunctions = Util.getUrlFunctions(stylesheetContent);
  1149. urlFunctions.map(urlFunction => {
  1150. const originalResourceURL = Util.matchURL(urlFunction);
  1151. const resourceURL = Util.normalizeURL(originalResourceURL);
  1152. if (!Util.testIgnoredPath(resourceURL)) {
  1153. if (!resourceURL || Util.testValidPath(resourceURL, baseURI, options.url)) {
  1154. let resolvedURL;
  1155. try {
  1156. resolvedURL = DocUtil.resolveURL(resourceURL, baseURI);
  1157. } catch (error) {
  1158. // ignored
  1159. }
  1160. if (Util.testValidURL(resolvedURL, baseURI, options.url) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  1161. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  1162. }
  1163. } else {
  1164. let newUrlFunction;
  1165. if (originalResourceURL) {
  1166. newUrlFunction = urlFunction.replace(originalResourceURL, EMPTY_DATA_URI);
  1167. } else {
  1168. newUrlFunction = "url(" + EMPTY_DATA_URI + ")";
  1169. }
  1170. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), newUrlFunction);
  1171. }
  1172. } else {
  1173. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  1174. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  1175. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  1176. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  1177. }
  1178. }
  1179. }
  1180. });
  1181. return stylesheetContent;
  1182. }
  1183. static async resolveLinkStylesheetURLs(resourceURL, baseURI, options) {
  1184. resourceURL = Util.normalizeURL(resourceURL);
  1185. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  1186. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charset: options.charset };
  1187. const content = await DocUtil.getContent(resourceURL, downloadOptions);
  1188. resourceURL = content.resourceURL;
  1189. let stylesheetContent = Util.removeCssComments(content.data);
  1190. if (options.compressCSS) {
  1191. stylesheetContent = DocUtil.compressCSS(stylesheetContent);
  1192. }
  1193. stylesheetContent = await ProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options);
  1194. return stylesheetContent;
  1195. }
  1196. }
  1197. static async processStylesheet(cssRules, baseURI, options, cssVariables, batchRequest) {
  1198. const promises = [];
  1199. const removedRules = [];
  1200. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  1201. const ruleData = cssRule.data;
  1202. if (ruleData.type == "Atrule" && ruleData.name == "charset") {
  1203. removedRules.push(cssRule);
  1204. } else if (ruleData.block && ruleData.block.children) {
  1205. if (ruleData.type == "Rule") {
  1206. promises.push(this.processStyle(ruleData.block.children.toArray(), baseURI, options, cssVariables, batchRequest));
  1207. } else if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports")) {
  1208. promises.push(this.processStylesheet(ruleData.block.children, baseURI, options, cssVariables, batchRequest));
  1209. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  1210. promises.push(processFontFaceRule(ruleData));
  1211. }
  1212. }
  1213. }
  1214. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  1215. await Promise.all(promises);
  1216. async function processFontFaceRule(ruleData) {
  1217. await Promise.all(ruleData.block.children.toArray().map(async declaration => {
  1218. if (declaration.type == "Declaration" && declaration.value.children) {
  1219. const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
  1220. await Promise.all(urlFunctions.map(async urlFunction => {
  1221. const originalResourceURL = Util.matchURL(urlFunction);
  1222. const resourceURL = Util.normalizeURL(originalResourceURL);
  1223. if (!Util.testIgnoredPath(resourceURL)) {
  1224. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1225. let { content } = await batchRequest.addURL(resourceURL, true);
  1226. if (content != EMPTY_DATA_URI && !content.startsWith(PREFIX_DATA_URI_VND) && !content.startsWith(PREFIX_DATA_URI_IMAGE_SVG)) {
  1227. const validResource = await DocUtil.validFont("url(" + content + ")");
  1228. if (!validResource) {
  1229. content = EMPTY_DATA_URI;
  1230. }
  1231. }
  1232. replaceURLs(declaration, originalResourceURL, content);
  1233. }
  1234. } else if (resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(PREFIX_DATA_URI_VND) && !resourceURL.startsWith(PREFIX_DATA_URI_IMAGE_SVG)) {
  1235. const validResource = await DocUtil.validFont(urlFunction);
  1236. if (!validResource) {
  1237. replaceURLs(declaration, originalResourceURL, EMPTY_DATA_URI);
  1238. }
  1239. }
  1240. }));
  1241. }
  1242. }));
  1243. function replaceURLs(declaration, oldURL, newURL) {
  1244. declaration.value.children.forEach(token => {
  1245. if (token.type == "Url" && DocUtil.removeQuotes(Util.getCSSValue(token.value)) == oldURL) {
  1246. token.value.value = newURL;
  1247. }
  1248. });
  1249. }
  1250. }
  1251. }
  1252. static async processStyle(declarations, baseURI, options, cssVariables, batchRequest) {
  1253. await Promise.all(declarations.map(async declaration => {
  1254. if (declaration.type == "Declaration" && declaration.value.children) {
  1255. const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
  1256. await Promise.all(urlFunctions.map(async urlFunction => {
  1257. const originalResourceURL = Util.matchURL(urlFunction);
  1258. const resourceURL = Util.normalizeURL(originalResourceURL);
  1259. if (!Util.testIgnoredPath(resourceURL)) {
  1260. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1261. let { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, true);
  1262. let variableDefined;
  1263. const tokens = [];
  1264. findURLToken(originalResourceURL, declaration.value.children, (token, parent, rootFunction) => {
  1265. if (duplicate && options.groupDuplicateImages && rootFunction) {
  1266. const value = cssTree.parse("var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")", { context: "value" }).children.head;
  1267. tokens.push({ parent, token, value });
  1268. variableDefined = true;
  1269. } else {
  1270. token.data.value.value = content;
  1271. }
  1272. });
  1273. if (variableDefined) {
  1274. cssVariables.set(indexResource, content);
  1275. tokens.forEach(({ parent, token, value }) => parent.replace(token, value));
  1276. }
  1277. }
  1278. }
  1279. }));
  1280. }
  1281. }));
  1282. function findURLToken(url, children, callback, depth = 0) {
  1283. for (let token = children.head; token; token = token.next) {
  1284. if (token.data.children) {
  1285. findURLToken(url, token.data.children, callback, depth + 1);
  1286. }
  1287. if (token.data.type == "Url" && DocUtil.removeQuotes(Util.getCSSValue(token.data.value)) == url) {
  1288. callback(token, children, depth == 0);
  1289. }
  1290. }
  1291. }
  1292. }
  1293. static async processAttribute(resourceElements, attributeName, prefixDataURI, baseURI, options, cssVariables, styles, batchRequest, processDuplicates, removeElementIfMissing) {
  1294. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1295. let resourceURL = resourceElement.getAttribute(attributeName);
  1296. resourceURL = Util.normalizeURL(resourceURL);
  1297. if (!Util.testIgnoredPath(resourceURL)) {
  1298. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1299. if (Util.testValidPath(resourceURL, baseURI, options.url)) {
  1300. try {
  1301. resourceURL = DocUtil.resolveURL(resourceURL, baseURI);
  1302. } catch (error) {
  1303. // ignored
  1304. }
  1305. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1306. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, resourceElement.tagName == "IMG" && attributeName == "src");
  1307. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1308. resourceElement.remove();
  1309. } else {
  1310. 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)) {
  1311. const isSVG = content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1312. if (processDuplicates && duplicate && options.groupDuplicateImages && !isSVG) {
  1313. if (Util.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1314. cssVariables.set(indexResource, content);
  1315. const declarationList = cssTree.parse(resourceElement.getAttribute("style"), { context: "declarationList" });
  1316. styles.set(resourceElement, declarationList);
  1317. } else {
  1318. resourceElement.setAttribute(attributeName, content);
  1319. }
  1320. } else {
  1321. resourceElement.setAttribute(attributeName, content);
  1322. }
  1323. }
  1324. }
  1325. }
  1326. }
  1327. }
  1328. }));
  1329. }
  1330. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1331. const attributeName = "xlink:href";
  1332. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1333. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1334. let resourceURL = Util.normalizeURL(originalResourceURL);
  1335. if (Util.testValidPath(resourceURL, baseURI, options.url) && !Util.testIgnoredPath(resourceURL)) {
  1336. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1337. try {
  1338. resourceURL = DocUtil.resolveURL(resourceURL, baseURI);
  1339. } catch (error) {
  1340. // ignored
  1341. }
  1342. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1343. try {
  1344. const { content } = await batchRequest.addURL(resourceURL);
  1345. const DOMParser = DocUtil.getParser();
  1346. if (DOMParser) {
  1347. const svgDoc = new DOMParser().parseFromString(content, "image/svg+xml");
  1348. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1349. if (hashMatch && hashMatch[0]) {
  1350. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1351. if (symbolElement) {
  1352. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1353. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1354. }
  1355. } else {
  1356. resourceElement.setAttribute(attributeName, PREFIX_DATA_URI_IMAGE_SVG + "," + content);
  1357. }
  1358. } else {
  1359. resourceElement.setAttribute(attributeName, PREFIX_DATA_URI_IMAGE_SVG + "," + content);
  1360. }
  1361. } catch (error) {
  1362. /* ignored */
  1363. }
  1364. }
  1365. } else if (resourceURL == options.url) {
  1366. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1367. }
  1368. }));
  1369. }
  1370. static async processSrcset(resourceElements, attributeName, prefixDataURI, baseURI, options, batchRequest) {
  1371. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1372. const srcset = DocUtil.parseSrcset(resourceElement.getAttribute(attributeName));
  1373. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1374. let resourceURL = Util.normalizeURL(srcsetValue.url);
  1375. if (!Util.testIgnoredPath(resourceURL)) {
  1376. if (Util.testValidPath(resourceURL, baseURI, options.url)) {
  1377. try {
  1378. resourceURL = DocUtil.resolveURL(resourceURL, baseURI);
  1379. } catch (error) {
  1380. // ignored
  1381. }
  1382. if (Util.testValidURL(resourceURL, baseURI, options.url)) {
  1383. const { content } = await batchRequest.addURL(resourceURL, true);
  1384. 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)) {
  1385. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1386. }
  1387. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1388. } else {
  1389. return "";
  1390. }
  1391. } else {
  1392. return "";
  1393. }
  1394. } else {
  1395. return resourceURL + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1396. }
  1397. }));
  1398. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1399. }));
  1400. }
  1401. }
  1402. // ----
  1403. // Util
  1404. // ----
  1405. const DATA_URI_PREFIX = "data:";
  1406. const BLOB_URI_PREFIX = "blob:";
  1407. const HTTP_URI_PREFIX = /^https?:\/\//;
  1408. const FILE_URI_PREFIX = /^file:\/\//;
  1409. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1410. const ABOUT_BLANK_URI = "about:blank";
  1411. const NOT_EMPTY_URL = /^(https?:\/\/|file:\/\/|blob:).+/;
  1412. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1413. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1414. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1415. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1416. 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;
  1417. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1418. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1419. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1420. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1421. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1422. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1423. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1424. class Util {
  1425. static normalizeURL(url) {
  1426. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1427. return url;
  1428. } else {
  1429. return url.split("#")[0];
  1430. }
  1431. }
  1432. static getCSSValue(value) {
  1433. let result = "";
  1434. try {
  1435. result = cssTree.generate(value);
  1436. } catch (error) {
  1437. // ignored
  1438. }
  1439. return result;
  1440. }
  1441. static getOnEventAttributeNames(doc) {
  1442. const element = doc.createElement("div");
  1443. const attributeNames = [];
  1444. for (const propertyName in element) {
  1445. if (propertyName.startsWith("on")) {
  1446. attributeNames.push(propertyName);
  1447. }
  1448. }
  1449. return attributeNames;
  1450. }
  1451. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1452. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1453. if (template.match(replaceRegExp)) {
  1454. let value = await valueGetter();
  1455. if (!dontReplaceSlash) {
  1456. value = value.replace(/\/+/g, "_");
  1457. }
  1458. return template.replace(replaceRegExp, value);
  1459. }
  1460. return template;
  1461. }
  1462. static getLastSegment(url) {
  1463. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1464. if (!lastSegment) {
  1465. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1466. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1467. }
  1468. if (!lastSegment) {
  1469. lastSegmentMatch = lastSegment.match(/(.*)<\.[^.]+$/);
  1470. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1471. }
  1472. if (!lastSegment) {
  1473. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1474. }
  1475. lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1476. return lastSegment;
  1477. }
  1478. static getRegExp(string) {
  1479. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1480. }
  1481. static getUrlFunctions(stylesheetContent) {
  1482. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1483. }
  1484. static getImportFunctions(stylesheetContent) {
  1485. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1486. }
  1487. static findShortcutIcon(shortcutIcons) {
  1488. shortcutIcons = shortcutIcons.filter(linkElement => linkElement.href != EMPTY_IMAGE);
  1489. shortcutIcons.sort((linkElement1, linkElement2) => (parseInt(linkElement2.sizes, 10) || 16) - (parseInt(linkElement1.sizes, 10) || 16));
  1490. return shortcutIcons[0];
  1491. }
  1492. static matchURL(stylesheetContent) {
  1493. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1494. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1495. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1496. return match && match[1];
  1497. }
  1498. static testIgnoredPath(resourceURL) {
  1499. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
  1500. }
  1501. static testValidPath(resourceURL, baseURI, docURL) {
  1502. return resourceURL && resourceURL != baseURI && resourceURL != docURL && !resourceURL.match(EMPTY_URL);
  1503. }
  1504. static testValidURL(resourceURL, baseURI, docURL) {
  1505. 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);
  1506. }
  1507. static matchImport(stylesheetContent) {
  1508. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1509. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1510. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1511. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1512. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1513. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1514. if (match) {
  1515. const [, resourceURL, media] = match;
  1516. return { resourceURL, media };
  1517. }
  1518. }
  1519. static removeCssComments(stylesheetContent) {
  1520. let start, end;
  1521. do {
  1522. start = stylesheetContent.indexOf("/*");
  1523. end = stylesheetContent.indexOf("*/", start + 2);
  1524. if (start != -1 && end != -1) {
  1525. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1526. }
  1527. } while (start != -1 && end != -1);
  1528. return stylesheetContent;
  1529. }
  1530. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1531. if (mediaQuery) {
  1532. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1533. } else {
  1534. return stylesheetContent;
  1535. }
  1536. }
  1537. static replaceImageSource(imgElement, variableName, options) {
  1538. const dataAttributeName = DocUtil.imagesAttributeName(options.sessionId);
  1539. if (imgElement.getAttribute(dataAttributeName) != null) {
  1540. const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  1541. if (imgData.replaceable) {
  1542. 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>`);
  1543. const backgroundStyle = {};
  1544. const backgroundSize = (imgData.objectFit == "content" || imgData.objectFit == "cover") && imgData.objectFit;
  1545. if (backgroundSize) {
  1546. backgroundStyle["background-size"] = imgData.objectFit;
  1547. }
  1548. if (imgData.objectPosition) {
  1549. backgroundStyle["background-position"] = imgData.objectPosition;
  1550. }
  1551. if (imgData.backgroundColor) {
  1552. backgroundStyle["background-color"] = imgData.backgroundColor;
  1553. }
  1554. ProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1555. imgElement.removeAttribute(dataAttributeName);
  1556. return true;
  1557. }
  1558. }
  1559. }
  1560. }
  1561. function log(...args) {
  1562. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1563. }
  1564. // -----
  1565. // Stats
  1566. // -----
  1567. const STATS_DEFAULT_VALUES = {
  1568. discarded: {
  1569. "HTML bytes": 0,
  1570. "hidden elements": 0,
  1571. "HTML imports": 0,
  1572. scripts: 0,
  1573. objects: 0,
  1574. "audio sources": 0,
  1575. "video sources": 0,
  1576. frames: 0,
  1577. "CSS rules": 0,
  1578. canvas: 0,
  1579. stylesheets: 0,
  1580. resources: 0,
  1581. medias: 0
  1582. },
  1583. processed: {
  1584. "HTML bytes": 0,
  1585. "hidden elements": 0,
  1586. "HTML imports": 0,
  1587. scripts: 0,
  1588. objects: 0,
  1589. "audio sources": 0,
  1590. "video sources": 0,
  1591. frames: 0,
  1592. "CSS rules": 0,
  1593. canvas: 0,
  1594. stylesheets: 0,
  1595. resources: 0,
  1596. medias: 0
  1597. }
  1598. };
  1599. class Stats {
  1600. constructor(options) {
  1601. this.options = options;
  1602. if (options.displayStats) {
  1603. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1604. }
  1605. }
  1606. set(type, subType, value) {
  1607. if (this.options.displayStats) {
  1608. this.data[type][subType] = value;
  1609. }
  1610. }
  1611. add(type, subType, value) {
  1612. if (this.options.displayStats) {
  1613. this.data[type][subType] += value;
  1614. }
  1615. }
  1616. addAll(pageData) {
  1617. if (this.options.displayStats) {
  1618. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1619. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1620. }
  1621. }
  1622. }
  1623. return { getClass };
  1624. })();