single-file-core.js 73 KB

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