single-file-core.js 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862
  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: "replaceStyleContents" },
  80. { option: "selected", action: "removeUnselectedElements" },
  81. { option: "removeVideoSrc", action: "insertVideoPosters" },
  82. { option: "removeFrames", action: "removeFrames" },
  83. { option: "removeImports", action: "removeImports" },
  84. { option: "removeScripts", action: "removeScripts" },
  85. { option: "removeVideoSrc", action: "removeVideoSources" },
  86. { option: "removeAudioSrc", action: "removeAudioSources" },
  87. { action: "removeDiscardedResources" },
  88. { action: "resetCharsetMeta" },
  89. { action: "setInputValues" },
  90. { option: "insertFaviconLink", action: "insertFaviconLink" },
  91. { action: "replaceCanvasElements" },
  92. { action: "insertFonts" },
  93. { option: "removeHiddenElements", action: "removeHiddenElements" },
  94. { action: "resolveHrefs" },
  95. { action: "resolveStyleAttributeURLs" }
  96. ],
  97. parallel: [
  98. { action: "resolveStylesheetURLs" },
  99. { action: "resolveShadowRootURLs" },
  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. { action: "processShadowRoots" },
  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 && 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.stylesheetsData = docData.stylesheetsData;
  146. this.options.imageData = docData.imageData;
  147. this.options.postersData = docData.postersData;
  148. this.options.usedFonts = docData.usedFonts;
  149. this.options.shadowRootsData = docData.shadowRootsData;
  150. this.options.referrer = docData.referrer;
  151. }
  152. if (this.options.saveRawPage) {
  153. this.options.removeFrames = true;
  154. }
  155. this.options.content = this.options.content || (this.options.doc ? docUtil.serialize(this.options.doc, false) : null);
  156. this.onprogress = options.onprogress || (() => { });
  157. }
  158. async loadPage() {
  159. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url, frame: !this.root }));
  160. await this.processor.loadPage(this.options.content);
  161. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url, frame: !this.root }));
  162. }
  163. async initialize() {
  164. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  165. await this.executeStage(RESOLVE_URLS_STAGE);
  166. this.pendingPromises = this.executeStage(REPLACE_DATA_STAGE);
  167. if (this.options.doc) {
  168. docUtil.postProcessDoc(this.options.doc, this.options);
  169. }
  170. this.options.doc = null;
  171. this.options.win = null;
  172. }
  173. async run() {
  174. if (this.root) {
  175. this.processor.initialize(this.batchRequest);
  176. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: this.processor.maxResources }));
  177. }
  178. await this.batchRequest.run(detail => {
  179. detail.pageURL = this.options.url;
  180. this.onprogress(new ProgressEvent(RESOURCE_LOADED, detail));
  181. }, this.options);
  182. await this.pendingPromises;
  183. await this.executeStage(REPLACE_DOCS_STAGE);
  184. await this.executeStage(POST_PROCESS_STAGE);
  185. await this.processor.finalize();
  186. }
  187. getDocument() {
  188. return this.processor.doc;
  189. }
  190. async getPageData() {
  191. if (this.root) {
  192. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  193. }
  194. return this.processor.getPageData();
  195. }
  196. async executeStage(step) {
  197. if (DEBUG) {
  198. log("**** STARTED STAGE", step, "****");
  199. }
  200. const frame = !this.root;
  201. this.onprogress(new ProgressEvent(STAGE_STARTED, { pageURL: this.options.url, step, frame }));
  202. STAGES[step].sequential.forEach(task => {
  203. let startTime;
  204. if (DEBUG) {
  205. startTime = Date.now();
  206. log(" -- STARTED task =", task.action);
  207. }
  208. this.onprogress(new ProgressEvent(STAGE_TASK_STARTED, { pageURL: this.options.url, step, task: task.action, frame }));
  209. this.executeTask(task);
  210. this.onprogress(new ProgressEvent(STAGE_TASK_ENDED, { pageURL: this.options.url, step, task: task.action, frame }));
  211. if (DEBUG) {
  212. log(" -- ENDED task =", task.action, "delay =", Date.now() - startTime);
  213. }
  214. });
  215. let parallelTasksPromise;
  216. if (STAGES[step].parallel) {
  217. parallelTasksPromise = await Promise.all(STAGES[step].parallel.map(async task => {
  218. let startTime;
  219. if (DEBUG) {
  220. startTime = Date.now();
  221. log(" // STARTED task =", task.action);
  222. }
  223. this.onprogress(new ProgressEvent(STAGE_TASK_STARTED, { pageURL: this.options.url, step, task: task.action, frame }));
  224. await this.executeTask(task);
  225. this.onprogress(new ProgressEvent(STAGE_TASK_ENDED, { pageURL: this.options.url, step, task: task.action, frame }));
  226. if (DEBUG) {
  227. log(" // ENDED task =", task.action, "delay =", Date.now() - startTime);
  228. }
  229. }));
  230. } else {
  231. parallelTasksPromise = Promise.resolve();
  232. }
  233. this.onprogress(new ProgressEvent(STAGE_ENDED, { pageURL: this.options.url, step, frame }));
  234. if (DEBUG) {
  235. log("**** ENDED STAGE", step, "****");
  236. }
  237. return parallelTasksPromise;
  238. }
  239. executeTask(task) {
  240. if (!task.option || ((task.option.startsWith("!") && !this.options[task.option]) || this.options[task.option])) {
  241. return this.processor[task.action]();
  242. }
  243. }
  244. }
  245. // ------------
  246. // BatchRequest
  247. // ------------
  248. class BatchRequest {
  249. constructor() {
  250. this.requests = new Map();
  251. this.duplicates = new Map();
  252. }
  253. async addURL(resourceURL, asDataURI, groupDuplicates) {
  254. return new Promise((resolve, reject) => {
  255. const requestKey = JSON.stringify([resourceURL, asDataURI]);
  256. let resourceRequests = this.requests.get(requestKey);
  257. if (!resourceRequests) {
  258. resourceRequests = [];
  259. this.requests.set(requestKey, resourceRequests);
  260. }
  261. const callbacks = { resolve, reject };
  262. resourceRequests.push(callbacks);
  263. if (groupDuplicates) {
  264. let duplicateRequests = this.duplicates.get(requestKey);
  265. if (!duplicateRequests) {
  266. duplicateRequests = [];
  267. this.duplicates.set(requestKey, duplicateRequests);
  268. }
  269. duplicateRequests.push(callbacks);
  270. }
  271. });
  272. }
  273. getMaxResources() {
  274. return this.requests.size;
  275. }
  276. async run(onloadListener, options) {
  277. const resourceURLs = Array.from(this.requests.keys());
  278. let indexResource = 0;
  279. return Promise.all(resourceURLs.map(async requestKey => {
  280. const [resourceURL, asDataURI] = JSON.parse(requestKey);
  281. const resourceRequests = this.requests.get(requestKey);
  282. this.requests.delete(requestKey);
  283. try {
  284. const content = await docUtil.getContent(resourceURL, { asDataURI, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled });
  285. indexResource = indexResource + 1;
  286. onloadListener({ index: indexResource, url: resourceURL });
  287. resourceRequests.forEach(callbacks => {
  288. const duplicateCallbacks = this.duplicates.get(requestKey);
  289. const duplicate = duplicateCallbacks && duplicateCallbacks.length > 1 && duplicateCallbacks.includes(callbacks);
  290. callbacks.resolve({ content: content.data, indexResource, duplicate });
  291. });
  292. } catch (error) {
  293. indexResource = indexResource + 1;
  294. onloadListener({ index: indexResource, url: resourceURL });
  295. resourceRequests.forEach(resourceRequest => resourceRequest.reject(error));
  296. }
  297. }));
  298. }
  299. }
  300. // ---------
  301. // Processor
  302. // ---------
  303. const PREFIXES_FORBIDDEN_DATA_URI = ["data:text/"];
  304. const PREFIX_DATA_URI_IMAGE_SVG = "data:image/svg+xml";
  305. const EMPTY_IMAGE = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
  306. const SCRIPT_TAG_FOUND = /<script/gi;
  307. const NOSCRIPT_TAG_FOUND = /<noscript/gi;
  308. const WC_ATTRIBUTE_NAME = "data-single-file-web-component";
  309. class Processor {
  310. constructor(options, batchRequest) {
  311. this.options = options;
  312. this.stats = new Stats(options);
  313. this.baseURI = Util.normalizeURL(options.baseURI || options.url);
  314. this.batchRequest = batchRequest;
  315. this.stylesheets = new Map();
  316. this.styles = new Map();
  317. this.cssVariables = new Map();
  318. }
  319. initialize() {
  320. this.options.saveDate = new Date();
  321. this.options.saveUrl = this.options.url;
  322. if (this.options.enableMaff) {
  323. this.maffMetaDataPromise = this.batchRequest.addURL(docUtil.resolveURL("index.rdf", this.options.baseURI || this.options.url), false);
  324. }
  325. this.maxResources = this.batchRequest.getMaxResources();
  326. if (!this.options.saveRawPage && !this.options.removeFrames && this.options.framesData) {
  327. this.options.framesData.forEach(frameData => this.maxResources += frameData.maxResources || 0);
  328. }
  329. if (this.options.shadowRootsData) {
  330. this.options.shadowRootsData.forEach(shadowRootData => this.maxResources += shadowRootData.maxResources || 0);
  331. }
  332. this.stats.set("processed", "resources", this.maxResources);
  333. }
  334. async loadPage(pageContent, charset) {
  335. let content;
  336. if (!pageContent || this.options.saveRawPage) {
  337. content = await docUtil.getContent(this.baseURI, { asDataURI: false, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, charset });
  338. pageContent = content.data;
  339. }
  340. this.doc = docUtil.parseDocContent(pageContent, this.baseURI);
  341. if (this.options.saveRawPage) {
  342. let charset;
  343. this.doc.querySelectorAll("meta[charset], meta[http-equiv=\"content-type\"]").forEach(element => {
  344. const charsetDeclaration = element.content.split(";")[1];
  345. if (charsetDeclaration && !charset) {
  346. charset = charsetDeclaration.split("=")[1].trim().toLowerCase();
  347. }
  348. });
  349. if (charset && charset != content.charset) {
  350. return this.loadPage(pageContent, charset);
  351. }
  352. }
  353. this.workStyleElement = this.doc.createElement("style");
  354. this.doc.body.appendChild(this.workStyleElement);
  355. this.onEventAttributeNames = Util.getOnEventAttributeNames(this.doc);
  356. }
  357. async finalize() {
  358. if (this.workStyleElement.parentNode) {
  359. this.workStyleElement.remove();
  360. }
  361. const metaCharset = this.doc.head.querySelector("meta[charset]");
  362. if (metaCharset) {
  363. this.doc.head.insertBefore(metaCharset, this.doc.head.firstChild);
  364. }
  365. this.doc.querySelectorAll("base").forEach(element => element.remove());
  366. if (this.doc.head.querySelectorAll("*").length == 1 && metaCharset && this.doc.body.childNodes.length == 0) {
  367. this.doc.head.querySelector("meta[charset]").remove();
  368. }
  369. if (this.maffMetaDataPromise) {
  370. const maffMetaData = await this.maffMetaDataPromise;
  371. if (maffMetaData && maffMetaData.content) {
  372. const NAMESPACE_RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
  373. const maffDoc = docUtil.parseXMLContent(maffMetaData.content);
  374. const originalURLElement = maffDoc.querySelector("RDF > Description > originalurl");
  375. const archiveTimeElement = maffDoc.querySelector("RDF > Description > archivetime");
  376. if (originalURLElement) {
  377. this.options.saveUrl = originalURLElement.getAttributeNS(NAMESPACE_RDF, "resource");
  378. }
  379. if (archiveTimeElement) {
  380. const value = archiveTimeElement.getAttributeNS(NAMESPACE_RDF, "resource");
  381. if (value) {
  382. const date = new Date(value);
  383. if (!isNaN(date.getTime())) {
  384. this.options.saveDate = new Date(value);
  385. }
  386. }
  387. }
  388. }
  389. }
  390. const titleElement = this.doc.querySelector("title");
  391. const descriptionElement = this.doc.querySelector("meta[name=description]");
  392. const authorElement = this.doc.querySelector("meta[name=author]");
  393. const creatorElement = this.doc.querySelector("meta[name=creator]");
  394. const publisherElement = this.doc.querySelector("meta[name=publisher]");
  395. this.options.title = titleElement ? titleElement.textContent.trim() : "";
  396. this.options.infobarContent = await ProcessorHelper.evalTemplate(this.options.infobarTemplate, this.options, null, true);
  397. this.options.info = {
  398. description: descriptionElement && descriptionElement.content ? descriptionElement.content.trim() : "",
  399. lang: this.doc.documentElement.lang,
  400. author: authorElement && authorElement.content ? authorElement.content.trim() : "",
  401. creator: creatorElement && creatorElement.content ? creatorElement.content.trim() : "",
  402. publisher: publisherElement && publisherElement.content ? publisherElement.content.trim() : ""
  403. };
  404. }
  405. async getPageData() {
  406. docUtil.postProcessDoc(this.doc, this.options);
  407. const url = docUtil.parseURL(this.baseURI);
  408. if (this.options.insertSingleFileComment) {
  409. const infobarContent = (this.options.infobarContent || "").replace(/\\n/g, "\n").replace(/\\t/g, "\t");
  410. const commentNode = this.doc.createComment("\n Page saved with SingleFile" +
  411. " \n url: " + this.options.saveUrl +
  412. " \n saved date: " + this.options.saveDate +
  413. (infobarContent ? " \n info: " + infobarContent : "") + "\n");
  414. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  415. }
  416. let size;
  417. if (this.options.displayStats) {
  418. size = docUtil.getContentSize(this.doc.documentElement.outerHTML);
  419. }
  420. const content = docUtil.serialize(this.doc, this.options.compressHTML);
  421. if (this.options.displayStats) {
  422. const contentSize = docUtil.getContentSize(content);
  423. this.stats.set("processed", "HTML bytes", contentSize);
  424. this.stats.add("discarded", "HTML bytes", size - contentSize);
  425. }
  426. let filename = await ProcessorHelper.evalTemplate(this.options.filenameTemplate, this.options, content) || "";
  427. filename = filename.replace(/[~\\?%*:|"<>\x00-\x1f\x7F]+/g, "_"); // eslint-disable-line no-control-regex
  428. filename = filename.replace(/\.\.\//g, "").replace(/^\/+/, "").replace(/\/+/g, "/").replace(/\/$/, "").replace(/\.$/, "").replace(/\.\//g, "._").replace(/\/\./g, "/_");
  429. if (!this.options.backgroundSave) {
  430. filename = filename.replace(/\//g, "_");
  431. }
  432. if (docUtil.getContentSize(filename) > 192) {
  433. const extensionMatch = filename.match(/(\.[^.]{3,4})$/);
  434. const extension = extensionMatch && extensionMatch[0] && extensionMatch[0].length > 1 ? extensionMatch[0] : "";
  435. filename = await docUtil.truncateContent(filename, 192 - extension.length);
  436. filename = filename + "…" + extension;
  437. }
  438. if (!filename) {
  439. filename = "Unnamed page";
  440. }
  441. const matchTitle = this.baseURI.match(/([^/]*)\/?(\.html?.*)$/) || this.baseURI.match(/\/\/([^/]*)\/?$/);
  442. return {
  443. stats: this.stats.data,
  444. title: this.options.title || (this.baseURI && matchTitle ? matchTitle[1] : (url.hostname ? url.hostname : "")),
  445. filename,
  446. content
  447. };
  448. }
  449. preProcessPage() {
  450. if (this.options.win) {
  451. 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));
  452. }
  453. if (this.options.imageData && !this.options.saveRawPage) {
  454. const dataAttributeName = docUtil.IMAGE_ATTRIBUTE_NAME;
  455. this.doc.querySelectorAll("img").forEach(imgElement => {
  456. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  457. if (this.options.removeHiddenElements && imgData.size && !imgData.size.pxWidth && !imgData.size.pxHeight) {
  458. imgElement.setAttribute("src", EMPTY_IMAGE);
  459. } else if (imgData.currentSrc) {
  460. imgElement.setAttribute("src", imgData.currentSrc);
  461. }
  462. });
  463. if (this.options.loadDeferredImages) {
  464. this.doc.querySelectorAll("img[data-src]").forEach(imgElement => {
  465. const imgData = this.options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  466. if ((!imgElement.getAttribute("src") || imgElement.getAttribute("src") == EMPTY_IMAGE) && imgElement.getAttribute("data-src")) {
  467. imgData.src = imgElement.dataset.src;
  468. imgElement.setAttribute("src", imgElement.dataset.src);
  469. imgElement.removeAttribute("data-src");
  470. }
  471. });
  472. this.doc.querySelectorAll("img[data-srcset]").forEach(imgElement => {
  473. if (!imgElement.getAttribute("srcset") && imgElement.getAttribute("data-srcset")) {
  474. imgElement.setAttribute("srcset", imgElement.dataset.srcset);
  475. imgElement.removeAttribute("data-srcset");
  476. }
  477. });
  478. }
  479. }
  480. }
  481. replaceStyleContents() {
  482. if (this.options.stylesheetsData) {
  483. this.doc.querySelectorAll("style").forEach((styleElement, styleIndex) => {
  484. if (this.options.stylesheetsData[styleIndex]) {
  485. styleElement.textContent = this.options.stylesheetsData[styleIndex];
  486. }
  487. });
  488. }
  489. }
  490. removeUnselectedElements() {
  491. removeUnmarkedElements(this.doc.body);
  492. this.doc.body.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  493. function removeUnmarkedElements(element) {
  494. let selectedElementFound = false;
  495. Array.from(element.childNodes).forEach(node => {
  496. if (node.nodeType == 1) {
  497. const isSelectedElement = node.getAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME) == "";
  498. selectedElementFound = selectedElementFound || isSelectedElement;
  499. if (isSelectedElement) {
  500. node.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  501. removeUnmarkedElements(node);
  502. } else if (selectedElementFound) {
  503. removeNode(node);
  504. } else {
  505. if (canHideNode(node)) {
  506. node.style.setProperty("display", "none", "important");
  507. Array.from(node.childNodes).forEach(removeNode);
  508. }
  509. }
  510. }
  511. });
  512. }
  513. function removeNode(node) {
  514. if (canHideNode(node)) {
  515. node.remove();
  516. }
  517. }
  518. function canHideNode(node) {
  519. if (node.nodeType == 1) {
  520. const tagName = node.tagName && node.tagName.toLowerCase();
  521. return (tagName != "svg" && tagName != "style" && tagName != "link");
  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], meta[disabled-http-equiv], 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)) {
  721. let resolvedURL;
  722. try {
  723. resolvedURL = docUtil.resolveURL(href, this.options.baseURI || this.options.url);
  724. } catch (error) {
  725. // ignored
  726. }
  727. if (resolvedURL) {
  728. if (resolvedURL.startsWith(this.options.url + "#")) {
  729. resolvedURL = resolvedURL.substring(this.options.url.length);
  730. }
  731. try {
  732. element.setAttribute("href", resolvedURL);
  733. } catch (error) {
  734. // ignored
  735. }
  736. }
  737. }
  738. });
  739. }
  740. resolveStyleAttributeURLs() {
  741. this.doc.querySelectorAll("[style]").forEach(element => {
  742. let styleContent = element.getAttribute("style");
  743. if (this.options.compressCSS) {
  744. styleContent = docUtil.compressCSS(styleContent);
  745. }
  746. styleContent = ProcessorHelper.resolveStylesheetURLs(styleContent, this.baseURI);
  747. const declarationList = cssTree.parse(styleContent, { context: "declarationList" });
  748. this.styles.set(element, declarationList);
  749. });
  750. }
  751. async resolveStylesheetURLs() {
  752. await Promise.all(Array.from(this.doc.querySelectorAll("style, link[rel*=stylesheet]"))
  753. .map(async element => {
  754. let mediaText;
  755. if (element.media) {
  756. mediaText = element.media.toLowerCase();
  757. }
  758. this.stylesheets.set(element, { mediaText });
  759. const options = { maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled, url: this.options.url, charset: this.charset, compressCSS: this.options.compressCSS };
  760. let stylesheetContent;
  761. if (element.tagName.toLowerCase() == "link") {
  762. if (element.charset) {
  763. options.charset = element.charset;
  764. }
  765. stylesheetContent = await ProcessorHelper.resolveLinkStylesheetURLs(element.href, this.baseURI, options, this.workStyleElement);
  766. } else {
  767. stylesheetContent = await ProcessorHelper.resolveImportURLs(element.textContent, this.baseURI, options, this.workStyleElement);
  768. }
  769. let stylesheet;
  770. try {
  771. stylesheet = cssTree.parse(Util.removeCssComments(stylesheetContent));
  772. } catch (error) {
  773. // ignored
  774. }
  775. if (stylesheet && stylesheet.children) {
  776. if (this.options.compressCSS) {
  777. ProcessorHelper.removeSingleLineCssComments(stylesheet);
  778. }
  779. this.stylesheets.get(element).stylesheet = stylesheet;
  780. } else {
  781. this.stylesheets.delete(element);
  782. }
  783. }));
  784. }
  785. async resolveFrameURLs() {
  786. if (!this.options.saveRawPage && this.options.framesData) {
  787. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  788. await Promise.all(frameElements.map(async frameElement => {
  789. if (frameElement.tagName == "OBJECT") {
  790. frameElement.setAttribute("data", "data:text/html,");
  791. } else {
  792. frameElement.removeAttribute("src");
  793. frameElement.removeAttribute("srcdoc");
  794. }
  795. const frameWindowId = frameElement.getAttribute(docUtil.WIN_ID_ATTRIBUTE_NAME);
  796. if (frameWindowId) {
  797. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  798. if (frameData) {
  799. await initializeProcessor(frameData, frameElement, frameWindowId, this.batchRequest, Object.create(this.options));
  800. }
  801. }
  802. }));
  803. }
  804. async function initializeProcessor(frameData, frameElement, frameWindowId, batchRequest, options) {
  805. options.insertSingleFileComment = false;
  806. options.insertFaviconLink = false;
  807. options.doc = null;
  808. options.win = null;
  809. options.url = frameData.baseURI;
  810. options.windowId = frameWindowId;
  811. if (frameData.content) {
  812. options.content = frameData.content;
  813. options.postersData = frameData.postersData;
  814. options.canvasData = frameData.canvasData;
  815. options.stylesheetsData = frameData.stylesheetsData;
  816. options.fontsData = frameData.fontsData;
  817. options.imageData = frameData.imageData;
  818. options.usedFonts = frameData.usedFonts;
  819. options.shadowRootsData = frameData.shadowRootsData;
  820. frameData.processor = new Runner(options);
  821. frameData.frameElement = frameElement;
  822. await frameData.processor.loadPage();
  823. await frameData.processor.initialize();
  824. frameData.maxResources = batchRequest.getMaxResources();
  825. }
  826. }
  827. }
  828. async resolveShadowRootURLs() {
  829. const rootOptions = this.options;
  830. const batchRequest = this.batchRequest;
  831. if (this.options.shadowRootsData) {
  832. await resolveURLs(this.doc);
  833. }
  834. async function resolveURLs(rootElement) {
  835. const shadowRootElements = Array.from((rootElement.querySelectorAll("[" + docUtil.SHADOW_ROOT_ATTRIBUTE_NAME + "]")));
  836. await Promise.all(shadowRootElements.map(async element => {
  837. const id = element.getAttribute(docUtil.SHADOW_ROOT_ATTRIBUTE_NAME);
  838. const shadowRootData = rootOptions.shadowRootsData[Number(id)];
  839. const options = Object.create(rootOptions);
  840. options.insertSingleFileComment = false;
  841. options.insertFaviconLink = false;
  842. options.doc = null;
  843. options.win = null;
  844. options.url = options.baseURI = rootOptions.url;
  845. if (shadowRootData.content) {
  846. const doc = docUtil.parseDocContent(shadowRootData.content);
  847. const docData = docUtil.preProcessDoc(doc, options.win, options);
  848. options.content = docUtil.serialize(doc);
  849. docUtil.postProcessDoc(doc, options);
  850. options.postersData = docData.postersData;
  851. options.canvasData = docData.canvasData;
  852. options.stylesheetsData = docData.stylesheetsData;
  853. options.fontsData = docData.fontsData;
  854. options.imageData = docData.imageData;
  855. options.usedFonts = docData.usedFonts;
  856. options.shadowRootsData = docData.shadowRootsData;
  857. shadowRootData.processor = new Runner(options);
  858. shadowRootData.element = element;
  859. await shadowRootData.processor.loadPage();
  860. await shadowRootData.processor.initialize();
  861. shadowRootData.maxResources = batchRequest.getMaxResources();
  862. await resolveURLs(shadowRootData.processor.getDocument());
  863. }
  864. }));
  865. }
  866. }
  867. async resolveHtmlImportURLs() {
  868. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  869. if (!this.relImportProcessors) {
  870. this.relImportProcessors = new Map();
  871. }
  872. await Promise.all(linkElements.map(async linkElement => {
  873. const resourceURL = linkElement.href;
  874. linkElement.removeAttribute("href");
  875. const options = Object.create(this.options);
  876. options.insertSingleFileComment = false;
  877. options.insertFaviconLink = false;
  878. options.doc = null;
  879. options.win = null;
  880. options.url = resourceURL;
  881. if (!Util.testIgnoredPath(resourceURL) && Util.testValidPath(resourceURL)) {
  882. const processor = new Runner(options);
  883. this.relImportProcessors.set(linkElement, processor);
  884. await processor.loadPage();
  885. return processor.initialize();
  886. }
  887. }));
  888. }
  889. removeUnusedStyles() {
  890. if (!this.mediaAllInfo) {
  891. this.mediaAllInfo = docUtil.getMediaAllInfo(this.doc, this.stylesheets, this.styles);
  892. }
  893. const stats = docUtil.minifyCSSRules(this.stylesheets, this.styles, this.mediaAllInfo);
  894. this.stats.set("processed", "CSS rules", stats.processed);
  895. this.stats.set("discarded", "CSS rules", stats.discarded);
  896. }
  897. removeUnusedFonts() {
  898. docUtil.removeUnusedFonts(this.doc, this.stylesheets, this.styles, this.options);
  899. }
  900. removeAlternativeMedias() {
  901. const stats = docUtil.minifyMedias(this.stylesheets);
  902. this.stats.set("processed", "medias", stats.processed);
  903. this.stats.set("discarded", "medias", stats.discarded);
  904. }
  905. async processStylesheets() {
  906. await Promise.all(Array.from(this.stylesheets).map(([, stylesheetInfo]) =>
  907. ProcessorHelper.processStylesheet(stylesheetInfo.stylesheet.children, this.baseURI, this.options, this.cssVariables, this.batchRequest)
  908. ));
  909. }
  910. async processStyleAttributes() {
  911. return Promise.all(Array.from(this.styles).map(([, declarationList]) =>
  912. ProcessorHelper.processStyle(declarationList.children.toArray(), this.baseURI, this.options, this.cssVariables, this.batchRequest)
  913. ));
  914. }
  915. async processPageResources() {
  916. const processAttributeArgs = [
  917. ["link[href][rel*=\"icon\"]", "href", false, true],
  918. ["object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"]", "data"],
  919. ["img[src], input[src][type=image]", "src", true],
  920. ["embed[src*=\".svg\"], embed[src*=\".pdf\"]", "src"],
  921. ["video[poster]", "poster"],
  922. ["*[background]", "background"],
  923. ["image", "xlink:href"]
  924. ];
  925. let resourcePromises = processAttributeArgs.map(([selector, attributeName, processDuplicates, removeElementIfMissing]) =>
  926. ProcessorHelper.processAttribute(this.doc.querySelectorAll(selector), attributeName, this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest, processDuplicates, removeElementIfMissing)
  927. );
  928. resourcePromises = resourcePromises.concat([
  929. ProcessorHelper.processXLinks(this.doc.querySelectorAll("use"), this.baseURI, this.options, this.batchRequest),
  930. ProcessorHelper.processSrcset(this.doc.querySelectorAll("img[srcset], source[srcset]"), "srcset", this.baseURI, this.batchRequest)
  931. ]);
  932. if (!this.options.removeAudioSrc) {
  933. resourcePromises.push(ProcessorHelper.processAttribute(this.doc.querySelectorAll("audio[src], audio > source[src]"), "src", this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
  934. }
  935. if (!this.options.removeVideoSrc) {
  936. resourcePromises.push(ProcessorHelper.processAttribute(this.doc.querySelectorAll("video[src], video > source[src]"), "src", this.baseURI, this.options, this.cssVariables, this.styles, this.batchRequest));
  937. }
  938. await Promise.all(resourcePromises);
  939. ProcessorHelper.processShortcutIcons(this.doc);
  940. }
  941. async processScripts() {
  942. await Promise.all(Array.from(this.doc.querySelectorAll("script[src]")).map(async scriptElement => {
  943. let resourceURL;
  944. const scriptSrc = scriptElement.getAttribute("src");
  945. scriptElement.removeAttribute("src");
  946. scriptElement.textContent = "";
  947. try {
  948. resourceURL = docUtil.resolveURL(scriptSrc, this.baseURI);
  949. } catch (error) {
  950. // ignored
  951. }
  952. if (Util.testValidURL(resourceURL)) {
  953. this.stats.add("processed", "scripts", 1);
  954. const content = await docUtil.getContent(resourceURL, { asDataURI: true, maxResourceSize: this.options.maxResourceSize, maxResourceSizeEnabled: this.options.maxResourceSizeEnabled });
  955. scriptElement.setAttribute("src", content.data);
  956. }
  957. }));
  958. }
  959. removeAlternativeImages() {
  960. docUtil.removeAlternativeImages(this.doc);
  961. }
  962. removeAlternativeFonts() {
  963. docUtil.removeAlternativeFonts(this.doc, this.stylesheets);
  964. }
  965. async processFrames() {
  966. if (this.options.framesData) {
  967. const frameElements = Array.from(this.doc.querySelectorAll("iframe, frame, object[type=\"text/html\"][data]"));
  968. await Promise.all(frameElements.map(async frameElement => {
  969. const frameWindowId = frameElement.getAttribute(docUtil.WIN_ID_ATTRIBUTE_NAME);
  970. if (frameWindowId) {
  971. const frameData = this.options.framesData.find(frame => frame.windowId == frameWindowId);
  972. if (frameData) {
  973. this.options.framesData = this.options.framesData.filter(frame => frame.windowId != frameWindowId);
  974. if (frameData.processor) {
  975. this.stats.add("processed", "frames", 1);
  976. await frameData.processor.run();
  977. const pageData = await frameData.processor.getPageData();
  978. frameElement.removeAttribute(docUtil.WIN_ID_ATTRIBUTE_NAME);
  979. let sandbox = "allow-popups allow-top-navigation allow-top-navigation-by-user-activation";
  980. if (pageData.content.match(NOSCRIPT_TAG_FOUND) || pageData.content.match(SCRIPT_TAG_FOUND)) {
  981. sandbox += " allow-scripts allow-same-origin";
  982. }
  983. frameElement.setAttribute("sandbox", sandbox);
  984. if (frameElement.tagName == "OBJECT") {
  985. frameElement.setAttribute("data", "data:text/html," + pageData.content);
  986. } else {
  987. if (frameElement.tagName == "FRAME") {
  988. frameElement.setAttribute("src", "data:text/html," + pageData.content.replace(/#/g, "%23"));
  989. } else {
  990. frameElement.setAttribute("srcdoc", pageData.content);
  991. frameElement.removeAttribute("src");
  992. }
  993. }
  994. this.stats.addAll(pageData);
  995. } else {
  996. this.stats.add("discarded", "frames", 1);
  997. }
  998. }
  999. }
  1000. }));
  1001. }
  1002. }
  1003. async processShadowRoots() {
  1004. const rootDoc = this.doc;
  1005. const options = this.options;
  1006. const stats = this.stats;
  1007. if (this.options.shadowRootsData) {
  1008. await processRootElement(this.doc);
  1009. const scriptElement = rootDoc.createElement("script");
  1010. scriptElement.textContent = `processNode(document);function processNode(node){node.querySelectorAll("[${WC_ATTRIBUTE_NAME}]").forEach(element=>{const shadowRoot=element.previousElementSibling.attachShadow({mode:"open"});shadowRoot.innerHTML=element.innerHTML;element.remove();processNode(shadowRoot)})}`;
  1011. this.doc.body.appendChild(scriptElement);
  1012. }
  1013. async function processRootElement(rootElement) {
  1014. const shadowRootElements = Array.from(rootElement.querySelectorAll("[" + docUtil.SHADOW_ROOT_ATTRIBUTE_NAME + "]"));
  1015. await Promise.all(shadowRootElements.map(async element => {
  1016. const id = element.getAttribute(docUtil.SHADOW_ROOT_ATTRIBUTE_NAME);
  1017. if (id) {
  1018. const shadowRootData = options.shadowRootsData[Number(id)];
  1019. if (shadowRootData) {
  1020. options.shadowRootsData = options.shadowRootsData.filter(shadowRootData => shadowRootData.id != id);
  1021. if (shadowRootData.processor) {
  1022. stats.add("processed", "shadow root elements", 1);
  1023. await shadowRootData.processor.run();
  1024. const doc = shadowRootData.processor.getDocument();
  1025. const templateElement = rootDoc.createElement("template");
  1026. templateElement.setAttribute(WC_ATTRIBUTE_NAME, "");
  1027. if (doc.head) {
  1028. const metaCharset = doc.head.querySelector("meta[charset]");
  1029. if (metaCharset) {
  1030. metaCharset.remove();
  1031. }
  1032. doc.head.childNodes.forEach(node => templateElement.appendChild(doc.importNode(node, true)));
  1033. }
  1034. if (doc.body) {
  1035. doc.body.childNodes.forEach(node => templateElement.appendChild(doc.importNode(node, true)));
  1036. }
  1037. await processRootElement(templateElement);
  1038. element.insertAdjacentElement("afterend", templateElement);
  1039. } else {
  1040. stats.add("discarded", "shadow root elements", 1);
  1041. }
  1042. }
  1043. }
  1044. }));
  1045. }
  1046. }
  1047. async processHtmlImports() {
  1048. const linkElements = Array.from(this.doc.querySelectorAll("link[rel=import][href]"));
  1049. await Promise.all(linkElements.map(async linkElement => {
  1050. const processor = this.relImportProcessors.get(linkElement);
  1051. if (processor) {
  1052. this.stats.add("processed", "HTML imports", 1);
  1053. this.relImportProcessors.delete(linkElement);
  1054. const pageData = await processor.getPageData();
  1055. linkElement.setAttribute("href", "data:text/html," + pageData.content);
  1056. this.stats.addAll(pageData);
  1057. } else {
  1058. this.stats.add("discarded", "HTML imports", 1);
  1059. }
  1060. }));
  1061. }
  1062. replaceStylesheets() {
  1063. this.doc.querySelectorAll("style").forEach(styleElement => {
  1064. const stylesheetInfo = this.stylesheets.get(styleElement);
  1065. if (stylesheetInfo) {
  1066. this.stylesheets.delete(styleElement);
  1067. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  1068. styleElement.textContent = stylesheetContent;
  1069. if (stylesheetInfo.mediaText) {
  1070. styleElement.media = stylesheetInfo.mediaText;
  1071. }
  1072. } else if (!styleElement.closest("[" + WC_ATTRIBUTE_NAME + "]")) {
  1073. styleElement.remove();
  1074. }
  1075. });
  1076. this.doc.querySelectorAll("link[rel*=stylesheet]").forEach(linkElement => {
  1077. const stylesheetInfo = this.stylesheets.get(linkElement);
  1078. if (stylesheetInfo) {
  1079. this.stylesheets.delete(linkElement);
  1080. const styleElement = this.doc.createElement("style");
  1081. if (stylesheetInfo.mediaText) {
  1082. styleElement.media = stylesheetInfo.mediaText;
  1083. }
  1084. let stylesheetContent = cssTree.generate(stylesheetInfo.stylesheet);
  1085. styleElement.textContent = stylesheetContent;
  1086. linkElement.parentElement.replaceChild(styleElement, linkElement);
  1087. } else {
  1088. linkElement.remove();
  1089. }
  1090. });
  1091. }
  1092. replaceStyleAttributes() {
  1093. this.doc.querySelectorAll("[style]").forEach(async element => {
  1094. const declarations = this.styles.get(element);
  1095. if (declarations) {
  1096. this.styles.delete(element);
  1097. let styleContent = cssTree.generate(declarations);
  1098. element.setAttribute("style", styleContent);
  1099. } else if (!element.closest("[" + WC_ATTRIBUTE_NAME + "]")) {
  1100. element.setAttribute("style", "");
  1101. }
  1102. });
  1103. }
  1104. insertVariables() {
  1105. if (this.cssVariables.size) {
  1106. const styleElement = this.doc.createElement("style");
  1107. const firstStyleElement = this.doc.head.querySelector("style");
  1108. if (firstStyleElement) {
  1109. this.doc.head.insertBefore(styleElement, firstStyleElement);
  1110. } else {
  1111. this.doc.head.appendChild(styleElement);
  1112. }
  1113. let stylesheetContent = "";
  1114. this.cssVariables.forEach((content, indexResource) => {
  1115. this.cssVariables.delete(indexResource);
  1116. if (stylesheetContent) {
  1117. stylesheetContent += ";";
  1118. }
  1119. stylesheetContent += `${SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource}:url("${content}")`;
  1120. });
  1121. styleElement.textContent = ":root{" + stylesheetContent + "}";
  1122. }
  1123. }
  1124. compressHTML() {
  1125. let size;
  1126. if (this.options.displayStats) {
  1127. size = docUtil.getContentSize(this.doc.documentElement.outerHTML);
  1128. }
  1129. docUtil.minifyHTML(this.doc, { PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME: docUtil.PRESERVED_SPACE_ELEMENT_ATTRIBUTE_NAME });
  1130. if (this.options.displayStats) {
  1131. this.stats.add("discarded", "HTML bytes", size - docUtil.getContentSize(this.doc.documentElement.outerHTML));
  1132. }
  1133. }
  1134. }
  1135. // ---------------
  1136. // ProcessorHelper
  1137. // ---------------
  1138. const DATA_URI_PREFIX = "data:";
  1139. const ABOUT_BLANK_URI = "about:blank";
  1140. const EMPTY_DATA_URI = "data:base64,";
  1141. const REGEXP_AMP = /&/g;
  1142. const REGEXP_NBSP = /\u00a0/g;
  1143. const REGEXP_START_TAG = /</g;
  1144. const REGEXP_END_TAG = />/g;
  1145. const REGEXP_URL_HASH = /(#.+?)$/;
  1146. const PREFIX_DATA_URI_VND = "data:application/vnd.";
  1147. const SINGLE_FILE_VARIABLE_NAME_PREFIX = "--sf-img-";
  1148. class ProcessorHelper {
  1149. static async evalTemplate(template = "", options, content, dontReplaceSlash) {
  1150. const date = options.saveDate;
  1151. const url = docUtil.parseURL(options.saveUrl);
  1152. template = await Util.evalTemplateVariable(template, "page-title", () => options.title || "No title", dontReplaceSlash);
  1153. template = await Util.evalTemplateVariable(template, "page-language", () => options.info.lang || "No language", dontReplaceSlash);
  1154. template = await Util.evalTemplateVariable(template, "page-description", () => options.info.description || "No description", dontReplaceSlash);
  1155. template = await Util.evalTemplateVariable(template, "page-author", () => options.info.author || "No author", dontReplaceSlash);
  1156. template = await Util.evalTemplateVariable(template, "page-creator", () => options.info.creator || "No creator", dontReplaceSlash);
  1157. template = await Util.evalTemplateVariable(template, "page-publisher", () => options.info.publisher || "No publisher", dontReplaceSlash);
  1158. template = await Util.evalTemplateVariable(template, "datetime-iso", () => date.toISOString(), dontReplaceSlash);
  1159. template = await Util.evalTemplateVariable(template, "date-iso", () => date.toISOString().split("T")[0], dontReplaceSlash);
  1160. template = await Util.evalTemplateVariable(template, "time-iso", () => date.toISOString().split("T")[1].split("Z")[0], dontReplaceSlash);
  1161. template = await Util.evalTemplateVariable(template, "date-locale", () => date.toLocaleDateString(), dontReplaceSlash);
  1162. template = await Util.evalTemplateVariable(template, "time-locale", () => date.toLocaleTimeString(), dontReplaceSlash);
  1163. template = await Util.evalTemplateVariable(template, "day-locale", () => String(date.getDate()).padStart(2, "0"), dontReplaceSlash);
  1164. template = await Util.evalTemplateVariable(template, "month-locale", () => String(date.getMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  1165. template = await Util.evalTemplateVariable(template, "year-locale", () => String(date.getFullYear()), dontReplaceSlash);
  1166. template = await Util.evalTemplateVariable(template, "datetime-locale", () => date.toLocaleString(), dontReplaceSlash);
  1167. template = await Util.evalTemplateVariable(template, "datetime-utc", () => date.toUTCString(), dontReplaceSlash);
  1168. template = await Util.evalTemplateVariable(template, "day-utc", () => String(date.getUTCDate()).padStart(2, "0"), dontReplaceSlash);
  1169. template = await Util.evalTemplateVariable(template, "month-utc", () => String(date.getUTCMonth() + 1).padStart(2, "0"), dontReplaceSlash);
  1170. template = await Util.evalTemplateVariable(template, "year-utc", () => String(date.getUTCFullYear()), dontReplaceSlash);
  1171. template = await Util.evalTemplateVariable(template, "hours-locale", () => String(date.getHours()).padStart(2, "0"), dontReplaceSlash);
  1172. template = await Util.evalTemplateVariable(template, "minutes-locale", () => String(date.getMinutes()).padStart(2, "0"), dontReplaceSlash);
  1173. template = await Util.evalTemplateVariable(template, "seconds-locale", () => String(date.getSeconds()).padStart(2, "0"), dontReplaceSlash);
  1174. template = await Util.evalTemplateVariable(template, "hours-utc", () => String(date.getUTCHours()).padStart(2, "0"), dontReplaceSlash);
  1175. template = await Util.evalTemplateVariable(template, "minutes-utc", () => String(date.getUTCMinutes()).padStart(2, "0"), dontReplaceSlash);
  1176. template = await Util.evalTemplateVariable(template, "seconds-utc", () => String(date.getUTCSeconds()).padStart(2, "0"), dontReplaceSlash);
  1177. template = await Util.evalTemplateVariable(template, "url-hash", () => url.hash.substring(1) || "No hash", dontReplaceSlash);
  1178. template = await Util.evalTemplateVariable(template, "url-host", () => url.host.replace(/\/$/, "") || "No host", dontReplaceSlash);
  1179. template = await Util.evalTemplateVariable(template, "url-hostname", () => url.hostname.replace(/\/$/, "") || "No hostname", dontReplaceSlash);
  1180. template = await Util.evalTemplateVariable(template, "url-href", () => decodeURI(url.href) || "No href", dontReplaceSlash);
  1181. template = await Util.evalTemplateVariable(template, "url-referrer", () => decodeURI(options.referrer) || "No referrer", dontReplaceSlash);
  1182. template = await Util.evalTemplateVariable(template, "url-password", () => url.password || "No password", dontReplaceSlash);
  1183. template = await Util.evalTemplateVariable(template, "url-pathname", () => decodeURI(url.pathname).replace(/^\//, "").replace(/\/$/, "") || "No pathname", dontReplaceSlash === undefined ? true : dontReplaceSlash);
  1184. template = await Util.evalTemplateVariable(template, "url-port", () => url.port || "No port", dontReplaceSlash);
  1185. template = await Util.evalTemplateVariable(template, "url-protocol", () => url.protocol || "No protocol", dontReplaceSlash);
  1186. template = await Util.evalTemplateVariable(template, "url-search", () => url.search.substring(1) || "No search", dontReplaceSlash);
  1187. const params = url.search.substring(1).split("&").map(parameter => parameter.split("="));
  1188. for (const [name, value] of params) {
  1189. template = await Util.evalTemplateVariable(template, "url-search-" + name, () => value || "", dontReplaceSlash);
  1190. }
  1191. template = template.replace(/{\s*url-search-[^}\s]*\s*}/gi, "");
  1192. template = await Util.evalTemplateVariable(template, "url-username", () => url.username || "No username", dontReplaceSlash);
  1193. template = await Util.evalTemplateVariable(template, "tab-id", () => String(options.tabId || "No tab id"), dontReplaceSlash);
  1194. template = await Util.evalTemplateVariable(template, "tab-index", () => String(options.tabIndex || "No tab index"), dontReplaceSlash);
  1195. template = await Util.evalTemplateVariable(template, "url-last-segment", () => decodeURI(Util.getLastSegment(url)) || "No last segment", dontReplaceSlash);
  1196. if (content) {
  1197. template = await Util.evalTemplateVariable(template, "digest-sha-256", async () => docUtil.digest("SHA-256", content), dontReplaceSlash);
  1198. template = await Util.evalTemplateVariable(template, "digest-sha-384", async () => docUtil.digest("SHA-384", content), dontReplaceSlash);
  1199. template = await Util.evalTemplateVariable(template, "digest-sha-512", async () => docUtil.digest("SHA-512", content), dontReplaceSlash);
  1200. }
  1201. return template.trim();
  1202. }
  1203. static setBackgroundImage(element, url, style) {
  1204. element.style.setProperty("background-blend-mode", "normal", "important");
  1205. element.style.setProperty("background-clip", "content-box", "important");
  1206. element.style.setProperty("background-position", style && style["background-position"] ? style["background-position"] : "center", "important");
  1207. element.style.setProperty("background-color", style && style["background-color"] ? style["background-color"] : "transparent", "important");
  1208. element.style.setProperty("background-image", url, "important");
  1209. element.style.setProperty("background-size", style && style["background-size"] ? style["background-size"] : "100% 100%", "important");
  1210. element.style.setProperty("background-origin", "content-box", "important");
  1211. element.style.setProperty("background-repeat", "no-repeat", "important");
  1212. }
  1213. static processShortcutIcons(doc) {
  1214. let shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel=\"icon\"], link[href][rel=\"shortcut icon\"]")));
  1215. if (!shortcutIcon) {
  1216. shortcutIcon = Util.findShortcutIcon(Array.from(doc.querySelectorAll("link[href][rel*=\"icon\"]")));
  1217. if (shortcutIcon) {
  1218. shortcutIcon.rel = "icon";
  1219. }
  1220. }
  1221. if (shortcutIcon) {
  1222. doc.querySelectorAll("link[href][rel*=\"icon\"]").forEach(linkElement => {
  1223. if (linkElement != shortcutIcon) {
  1224. linkElement.remove();
  1225. }
  1226. });
  1227. }
  1228. }
  1229. static removeSingleLineCssComments(stylesheet) {
  1230. const removedRules = [];
  1231. for (let cssRule = stylesheet.children.head; cssRule; cssRule = cssRule.next) {
  1232. const ruleData = cssRule.data;
  1233. if (ruleData.type == "Raw" && ruleData.value && ruleData.value.trim().startsWith("//")) {
  1234. removedRules.push(cssRule);
  1235. }
  1236. }
  1237. removedRules.forEach(cssRule => stylesheet.children.remove(cssRule));
  1238. }
  1239. static async resolveImportURLs(stylesheetContent, baseURI, options, workStylesheet) {
  1240. stylesheetContent = ProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  1241. const imports = Util.getImportFunctions(stylesheetContent);
  1242. await Promise.all(imports.map(async cssImport => {
  1243. const match = Util.matchImport(cssImport);
  1244. if (match) {
  1245. let resourceURL = Util.normalizeURL(match.resourceURL);
  1246. if (!Util.testIgnoredPath(resourceURL) && Util.testValidPath(resourceURL)) {
  1247. try {
  1248. resourceURL = docUtil.resolveURL(match.resourceURL, baseURI);
  1249. } catch (error) {
  1250. // ignored
  1251. }
  1252. if (Util.testValidURL(resourceURL)) {
  1253. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, validateTextContentType: true };
  1254. const content = await docUtil.getContent(resourceURL, downloadOptions);
  1255. resourceURL = content.resourceURL;
  1256. let importedStylesheetContent = Util.removeCssComments(content.data);
  1257. if (options.compressCSS) {
  1258. importedStylesheetContent = docUtil.compressCSS(importedStylesheetContent);
  1259. }
  1260. importedStylesheetContent = Util.wrapMediaQuery(importedStylesheetContent, match.media);
  1261. if (stylesheetContent.includes(cssImport)) {
  1262. importedStylesheetContent = await ProcessorHelper.resolveImportURLs(importedStylesheetContent, resourceURL, options, workStylesheet);
  1263. workStylesheet.textContent = importedStylesheetContent;
  1264. if (workStylesheet.sheet.cssRules.length) {
  1265. stylesheetContent = stylesheetContent.replace(Util.getRegExp(cssImport), importedStylesheetContent);
  1266. } else {
  1267. stylesheetContent = stylesheetContent.replace(Util.getRegExp(cssImport), "");
  1268. }
  1269. }
  1270. }
  1271. }
  1272. }
  1273. }));
  1274. return stylesheetContent;
  1275. }
  1276. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  1277. const urlFunctions = Util.getUrlFunctions(stylesheetContent);
  1278. urlFunctions.map(urlFunction => {
  1279. const originalResourceURL = Util.matchURL(urlFunction);
  1280. const resourceURL = Util.normalizeURL(originalResourceURL);
  1281. if (!Util.testIgnoredPath(resourceURL)) {
  1282. if (!resourceURL || Util.testValidPath(resourceURL)) {
  1283. let resolvedURL;
  1284. try {
  1285. resolvedURL = docUtil.resolveURL(resourceURL, baseURI);
  1286. } catch (error) {
  1287. // ignored
  1288. }
  1289. if (Util.testValidURL(resolvedURL) && resourceURL != resolvedURL && stylesheetContent.includes(urlFunction)) {
  1290. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, resolvedURL));
  1291. }
  1292. } else {
  1293. let newUrlFunction;
  1294. if (originalResourceURL) {
  1295. newUrlFunction = urlFunction.replace(originalResourceURL, EMPTY_DATA_URI);
  1296. } else {
  1297. newUrlFunction = "url(" + EMPTY_DATA_URI + ")";
  1298. }
  1299. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), newUrlFunction);
  1300. }
  1301. } else {
  1302. if (resourceURL.startsWith(DATA_URI_PREFIX)) {
  1303. const escapedResourceURL = resourceURL.replace(REGEXP_AMP, "&amp;").replace(REGEXP_NBSP, "&nbsp;").replace(REGEXP_START_TAG, "&lt;").replace(REGEXP_END_TAG, "&gt;");
  1304. if (escapedResourceURL != resourceURL && stylesheetContent.includes(urlFunction)) {
  1305. stylesheetContent = stylesheetContent.replace(Util.getRegExp(urlFunction), urlFunction.replace(originalResourceURL, escapedResourceURL));
  1306. }
  1307. }
  1308. }
  1309. });
  1310. return stylesheetContent;
  1311. }
  1312. static async resolveLinkStylesheetURLs(resourceURL, baseURI, options, workStylesheet) {
  1313. resourceURL = Util.normalizeURL(resourceURL);
  1314. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  1315. const downloadOptions = { asDataURI: false, maxResourceSize: options.maxResourceSize, maxResourceSizeEnabled: options.maxResourceSizeEnabled, charset: options.charset };
  1316. const content = await docUtil.getContent(resourceURL, downloadOptions);
  1317. resourceURL = content.resourceURL;
  1318. let stylesheetContent = Util.removeCssComments(content.data);
  1319. if (options.compressCSS) {
  1320. stylesheetContent = docUtil.compressCSS(stylesheetContent);
  1321. }
  1322. stylesheetContent = await ProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL, options, workStylesheet);
  1323. return stylesheetContent;
  1324. }
  1325. }
  1326. static async processStylesheet(cssRules, baseURI, options, cssVariables, batchRequest) {
  1327. const promises = [];
  1328. const removedRules = [];
  1329. for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
  1330. const ruleData = cssRule.data;
  1331. if (ruleData.type == "Atrule" && ruleData.name == "charset") {
  1332. removedRules.push(cssRule);
  1333. } else if (ruleData.block && ruleData.block.children) {
  1334. if (ruleData.type == "Rule") {
  1335. promises.push(this.processStyle(ruleData.block.children.toArray(), baseURI, options, cssVariables, batchRequest));
  1336. } else if (ruleData.type == "Atrule" && (ruleData.name == "media" || ruleData.name == "supports")) {
  1337. promises.push(this.processStylesheet(ruleData.block.children, baseURI, options, cssVariables, batchRequest));
  1338. } else if (ruleData.type == "Atrule" && ruleData.name == "font-face") {
  1339. promises.push(processFontFaceRule(ruleData));
  1340. }
  1341. }
  1342. }
  1343. removedRules.forEach(cssRule => cssRules.remove(cssRule));
  1344. await Promise.all(promises);
  1345. async function processFontFaceRule(ruleData) {
  1346. await Promise.all(ruleData.block.children.toArray().map(async declaration => {
  1347. if (declaration.type == "Declaration" && declaration.value.children) {
  1348. const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
  1349. await Promise.all(urlFunctions.map(async urlFunction => {
  1350. const originalResourceURL = Util.matchURL(urlFunction);
  1351. const resourceURL = Util.normalizeURL(originalResourceURL);
  1352. if (!Util.testIgnoredPath(resourceURL)) {
  1353. if (Util.testValidURL(resourceURL)) {
  1354. let { content } = await batchRequest.addURL(resourceURL, true);
  1355. if (content != EMPTY_DATA_URI && !content.startsWith(PREFIX_DATA_URI_VND) && !content.startsWith(PREFIX_DATA_URI_IMAGE_SVG)) {
  1356. const validResource = await docUtil.validFont(urlFunction);
  1357. if (!validResource) {
  1358. content = EMPTY_DATA_URI;
  1359. }
  1360. }
  1361. replaceURLs(declaration, originalResourceURL, content);
  1362. }
  1363. } else if (resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(PREFIX_DATA_URI_VND) && !resourceURL.startsWith(PREFIX_DATA_URI_IMAGE_SVG)) {
  1364. const validResource = await docUtil.validFont(urlFunction);
  1365. if (!validResource) {
  1366. replaceURLs(declaration, originalResourceURL, EMPTY_DATA_URI);
  1367. }
  1368. }
  1369. }));
  1370. }
  1371. }));
  1372. function replaceURLs(declaration, oldURL, newURL) {
  1373. declaration.value.children.forEach(token => {
  1374. if (token.type == "Url" && docUtil.removeQuotes(Util.getCSSValue(token.value)) == oldURL) {
  1375. token.value.value = newURL;
  1376. }
  1377. });
  1378. }
  1379. }
  1380. }
  1381. static async processStyle(declarations, baseURI, options, cssVariables, batchRequest) {
  1382. await Promise.all(declarations.map(async declaration => {
  1383. if (declaration.type == "Declaration" && declaration.value.children) {
  1384. const urlFunctions = Util.getUrlFunctions(Util.getCSSValue(declaration.value));
  1385. await Promise.all(urlFunctions.map(async urlFunction => {
  1386. const originalResourceURL = Util.matchURL(urlFunction);
  1387. const resourceURL = Util.normalizeURL(originalResourceURL);
  1388. if (!Util.testIgnoredPath(resourceURL)) {
  1389. if (Util.testValidURL(resourceURL)) {
  1390. let { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, true);
  1391. let variableDefined;
  1392. const tokens = [];
  1393. findURLToken(originalResourceURL, declaration.value.children, (token, parent, rootFunction) => {
  1394. if (duplicate && options.groupDuplicateImages && rootFunction) {
  1395. const value = cssTree.parse("var(" + SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource + ")", { context: "value" }).children.head;
  1396. tokens.push({ parent, token, value });
  1397. variableDefined = true;
  1398. } else {
  1399. token.data.value.value = content;
  1400. }
  1401. });
  1402. if (variableDefined) {
  1403. cssVariables.set(indexResource, content);
  1404. tokens.forEach(({ parent, token, value }) => parent.replace(token, value));
  1405. }
  1406. }
  1407. }
  1408. }));
  1409. }
  1410. }));
  1411. function findURLToken(url, children, callback, depth = 0) {
  1412. for (let token = children.head; token; token = token.next) {
  1413. if (token.data.children) {
  1414. findURLToken(url, token.data.children, callback, depth + 1);
  1415. }
  1416. if (token.data.type == "Url" && docUtil.removeQuotes(Util.getCSSValue(token.data.value)) == url) {
  1417. callback(token, children, depth == 0);
  1418. }
  1419. }
  1420. }
  1421. }
  1422. static async processAttribute(resourceElements, attributeName, baseURI, options, cssVariables, styles, batchRequest, processDuplicates, removeElementIfMissing) {
  1423. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1424. let resourceURL = resourceElement.getAttribute(attributeName);
  1425. resourceURL = Util.normalizeURL(resourceURL);
  1426. if (!Util.testIgnoredPath(resourceURL)) {
  1427. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1428. if (Util.testValidPath(resourceURL)) {
  1429. try {
  1430. resourceURL = docUtil.resolveURL(resourceURL, baseURI);
  1431. } catch (error) {
  1432. // ignored
  1433. }
  1434. if (Util.testValidURL(resourceURL)) {
  1435. const { content, indexResource, duplicate } = await batchRequest.addURL(resourceURL, true, resourceElement.tagName == "IMG" && attributeName == "src");
  1436. if (removeElementIfMissing && content == EMPTY_DATA_URI) {
  1437. resourceElement.remove();
  1438. } else {
  1439. const forbiddenPrefixFound = PREFIXES_FORBIDDEN_DATA_URI.filter(prefixDataURI => content.startsWith(prefixDataURI)).length;
  1440. if (!forbiddenPrefixFound) {
  1441. const isSVG = content.startsWith(PREFIX_DATA_URI_IMAGE_SVG);
  1442. if (processDuplicates && duplicate && options.groupDuplicateImages && !isSVG) {
  1443. if (ProcessorHelper.replaceImageSource(resourceElement, SINGLE_FILE_VARIABLE_NAME_PREFIX + indexResource, options)) {
  1444. cssVariables.set(indexResource, content);
  1445. const declarationList = cssTree.parse(resourceElement.getAttribute("style"), { context: "declarationList" });
  1446. styles.set(resourceElement, declarationList);
  1447. } else {
  1448. resourceElement.setAttribute(attributeName, content);
  1449. }
  1450. } else {
  1451. resourceElement.setAttribute(attributeName, content);
  1452. }
  1453. }
  1454. }
  1455. }
  1456. }
  1457. }
  1458. }));
  1459. }
  1460. static async processXLinks(resourceElements, baseURI, options, batchRequest) {
  1461. const attributeName = "xlink:href";
  1462. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1463. const originalResourceURL = resourceElement.getAttribute(attributeName);
  1464. let resourceURL = Util.normalizeURL(originalResourceURL);
  1465. if (Util.testValidPath(resourceURL) && !Util.testIgnoredPath(resourceURL)) {
  1466. resourceElement.setAttribute(attributeName, EMPTY_IMAGE);
  1467. try {
  1468. resourceURL = docUtil.resolveURL(resourceURL, baseURI);
  1469. } catch (error) {
  1470. // ignored
  1471. }
  1472. if (Util.testValidURL(resourceURL)) {
  1473. try {
  1474. const { content } = await batchRequest.addURL(resourceURL);
  1475. const hashMatch = originalResourceURL.match(REGEXP_URL_HASH);
  1476. if (hashMatch && hashMatch[0]) {
  1477. const svgDoc = docUtil.parseSVGContent(content);
  1478. const symbolElement = svgDoc.querySelector(hashMatch[0]);
  1479. if (symbolElement) {
  1480. resourceElement.setAttribute(attributeName, hashMatch[0]);
  1481. resourceElement.parentElement.insertBefore(symbolElement, resourceElement.parentElement.firstChild);
  1482. }
  1483. } else {
  1484. resourceElement.setAttribute(attributeName, PREFIX_DATA_URI_IMAGE_SVG + "," + content);
  1485. }
  1486. } catch (error) {
  1487. /* ignored */
  1488. }
  1489. }
  1490. } else if (resourceURL == options.url) {
  1491. resourceElement.setAttribute(attributeName, originalResourceURL.substring(resourceURL.length));
  1492. }
  1493. }));
  1494. }
  1495. static async processSrcset(resourceElements, attributeName, baseURI, batchRequest) {
  1496. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  1497. const srcset = docUtil.parseSrcset(resourceElement.getAttribute(attributeName));
  1498. const srcsetValues = await Promise.all(srcset.map(async srcsetValue => {
  1499. let resourceURL = Util.normalizeURL(srcsetValue.url);
  1500. if (!Util.testIgnoredPath(resourceURL)) {
  1501. if (Util.testValidPath(resourceURL)) {
  1502. try {
  1503. resourceURL = docUtil.resolveURL(resourceURL, baseURI);
  1504. } catch (error) {
  1505. // ignored
  1506. }
  1507. if (Util.testValidURL(resourceURL)) {
  1508. const { content } = await batchRequest.addURL(resourceURL, true);
  1509. const forbiddenPrefixFound = PREFIXES_FORBIDDEN_DATA_URI.filter(prefixDataURI => content.startsWith(prefixDataURI)).length;
  1510. if (forbiddenPrefixFound) {
  1511. return "";
  1512. }
  1513. return content + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1514. } else {
  1515. return "";
  1516. }
  1517. } else {
  1518. return "";
  1519. }
  1520. } else {
  1521. return resourceURL + (srcsetValue.w ? " " + srcsetValue.w + "w" : srcsetValue.d ? " " + srcsetValue.d + "x" : "");
  1522. }
  1523. }));
  1524. resourceElement.setAttribute(attributeName, srcsetValues.join(", "));
  1525. }));
  1526. }
  1527. static replaceImageSource(imgElement, variableName, options) {
  1528. const dataAttributeName = docUtil.IMAGE_ATTRIBUTE_NAME;
  1529. if (imgElement.getAttribute(dataAttributeName) != null) {
  1530. const imgData = options.imageData[Number(imgElement.getAttribute(dataAttributeName))];
  1531. if (imgData.replaceable) {
  1532. 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>`);
  1533. const backgroundStyle = {};
  1534. const backgroundSize = (imgData.objectFit == "content" || imgData.objectFit == "cover") && imgData.objectFit;
  1535. if (backgroundSize) {
  1536. backgroundStyle["background-size"] = imgData.objectFit;
  1537. }
  1538. if (imgData.objectPosition) {
  1539. backgroundStyle["background-position"] = imgData.objectPosition;
  1540. }
  1541. if (imgData.backgroundColor) {
  1542. backgroundStyle["background-color"] = imgData.backgroundColor;
  1543. }
  1544. ProcessorHelper.setBackgroundImage(imgElement, "var(" + variableName + ")", backgroundStyle);
  1545. imgElement.removeAttribute(dataAttributeName);
  1546. return true;
  1547. }
  1548. }
  1549. }
  1550. }
  1551. // ----
  1552. // Util
  1553. // ----
  1554. const BLOB_URI_PREFIX = "blob:";
  1555. const HTTP_URI_PREFIX = /^https?:\/\//;
  1556. const FILE_URI_PREFIX = /^file:\/\//;
  1557. const EMPTY_URL = /^https?:\/\/+\s*$/;
  1558. const NOT_EMPTY_URL = /^(https?:\/\/|file:\/\/|blob:).+/;
  1559. const REGEXP_URL_FN = /(url\s*\(\s*'(.*?)'\s*\))|(url\s*\(\s*"(.*?)"\s*\))|(url\s*\(\s*(.*?)\s*\))/gi;
  1560. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'(.*?)'\s*\)$/i;
  1561. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"(.*?)"\s*\)$/i;
  1562. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*(.*?)\s*\)$/i;
  1563. 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;
  1564. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'(.*?)'\s*\)\s*(.*?)(;|$|})/i;
  1565. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"(.*?)"\s*\)\s*(.*?)(;|$|})/i;
  1566. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*(.*?)\s*\)\s*(.*?)(;|$|})/i;
  1567. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*'(.*?)'\s*(.*?)(;|$|})/i;
  1568. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*"(.*?)"\s*(.*?)(;|$|})/i;
  1569. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*(.*?)\s*(.*?)(;|$|})/i;
  1570. const REGEXP_ESCAPE = /([{}()^$&.*?/+|[\\\\]|\]|-)/g;
  1571. class Util {
  1572. static normalizeURL(url) {
  1573. if (!url || url.startsWith(DATA_URI_PREFIX)) {
  1574. return url;
  1575. } else {
  1576. return url.split("#")[0];
  1577. }
  1578. }
  1579. static getCSSValue(value) {
  1580. let result = "";
  1581. try {
  1582. result = cssTree.generate(value);
  1583. } catch (error) {
  1584. // ignored
  1585. }
  1586. return result;
  1587. }
  1588. static getOnEventAttributeNames(doc) {
  1589. const element = doc.createElement("div");
  1590. const attributeNames = [];
  1591. for (const propertyName in element) {
  1592. if (propertyName.startsWith("on")) {
  1593. attributeNames.push(propertyName);
  1594. }
  1595. }
  1596. return attributeNames;
  1597. }
  1598. static async evalTemplateVariable(template, variableName, valueGetter, dontReplaceSlash) {
  1599. const replaceRegExp = new RegExp("{\\s*" + variableName + "\\s*}", "g");
  1600. if (template && template.match(replaceRegExp)) {
  1601. let value = await valueGetter();
  1602. if (!dontReplaceSlash) {
  1603. value = value.replace(/\/+/g, "_");
  1604. }
  1605. return template.replace(replaceRegExp, value);
  1606. }
  1607. return template;
  1608. }
  1609. static getLastSegment(url) {
  1610. let lastSegmentMatch = url.pathname.match(/\/([^/]+)$/), lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1611. if (!lastSegment) {
  1612. lastSegmentMatch = url.href.match(/([^/]+)\/?$/);
  1613. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1614. }
  1615. if (!lastSegment) {
  1616. lastSegmentMatch = lastSegment.match(/(.*)\.[^.]+$/);
  1617. lastSegment = lastSegmentMatch && lastSegmentMatch[0];
  1618. }
  1619. if (!lastSegment) {
  1620. lastSegment = url.hostname.replace(/\/+/g, "_").replace(/\/$/, "");
  1621. }
  1622. lastSegmentMatch = lastSegment.match(/(.*)\.[^.]+$/);
  1623. if (lastSegmentMatch && lastSegmentMatch[1]) {
  1624. lastSegment = lastSegmentMatch[1];
  1625. }
  1626. lastSegment = lastSegment.replace(/\/$/, "").replace(/^\//, "");
  1627. return lastSegment;
  1628. }
  1629. static getRegExp(string) {
  1630. return new RegExp(string.replace(REGEXP_ESCAPE, "\\$1"), "gi");
  1631. }
  1632. static getUrlFunctions(stylesheetContent) {
  1633. return Array.from(new Set(stylesheetContent.match(REGEXP_URL_FN) || []));
  1634. }
  1635. static getImportFunctions(stylesheetContent) {
  1636. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  1637. }
  1638. static findShortcutIcon(shortcutIcons) {
  1639. shortcutIcons = shortcutIcons.filter(linkElement => linkElement.href != EMPTY_IMAGE);
  1640. shortcutIcons.sort((linkElement1, linkElement2) => (parseInt(linkElement2.sizes, 10) || 16) - (parseInt(linkElement1.sizes, 10) || 16));
  1641. return shortcutIcons[0];
  1642. }
  1643. static matchURL(stylesheetContent) {
  1644. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  1645. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  1646. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  1647. return match && match[1];
  1648. }
  1649. static testIgnoredPath(resourceURL) {
  1650. return resourceURL && (resourceURL.startsWith(DATA_URI_PREFIX) || resourceURL == ABOUT_BLANK_URI);
  1651. }
  1652. static testValidPath(resourceURL) {
  1653. return resourceURL && !resourceURL.match(EMPTY_URL);
  1654. }
  1655. static testValidURL(resourceURL) {
  1656. return Util.testValidPath(resourceURL) && (resourceURL.match(HTTP_URI_PREFIX) || resourceURL.match(FILE_URI_PREFIX) || resourceURL.startsWith(BLOB_URI_PREFIX)) && resourceURL.match(NOT_EMPTY_URL);
  1657. }
  1658. static matchImport(stylesheetContent) {
  1659. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  1660. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  1661. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  1662. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  1663. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  1664. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  1665. if (match) {
  1666. const [, resourceURL, media] = match;
  1667. return { resourceURL, media };
  1668. }
  1669. }
  1670. static removeCssComments(stylesheetContent) {
  1671. let start, end;
  1672. do {
  1673. start = stylesheetContent.indexOf("/*");
  1674. end = stylesheetContent.indexOf("*/", start + 2);
  1675. if (start != -1 && end != -1) {
  1676. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  1677. }
  1678. } while (start != -1 && end != -1);
  1679. return stylesheetContent;
  1680. }
  1681. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  1682. if (mediaQuery) {
  1683. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  1684. } else {
  1685. return stylesheetContent;
  1686. }
  1687. }
  1688. }
  1689. function log(...args) {
  1690. console.log("S-File <core> ", ...args); // eslint-disable-line no-console
  1691. }
  1692. // -----
  1693. // Stats
  1694. // -----
  1695. const STATS_DEFAULT_VALUES = {
  1696. discarded: {
  1697. "HTML bytes": 0,
  1698. "hidden elements": 0,
  1699. "HTML imports": 0,
  1700. scripts: 0,
  1701. objects: 0,
  1702. "audio sources": 0,
  1703. "video sources": 0,
  1704. frames: 0,
  1705. "CSS rules": 0,
  1706. canvas: 0,
  1707. stylesheets: 0,
  1708. resources: 0,
  1709. medias: 0
  1710. },
  1711. processed: {
  1712. "HTML bytes": 0,
  1713. "hidden elements": 0,
  1714. "HTML imports": 0,
  1715. scripts: 0,
  1716. objects: 0,
  1717. "audio sources": 0,
  1718. "video sources": 0,
  1719. frames: 0,
  1720. "CSS rules": 0,
  1721. canvas: 0,
  1722. stylesheets: 0,
  1723. resources: 0,
  1724. medias: 0
  1725. }
  1726. };
  1727. class Stats {
  1728. constructor(options) {
  1729. this.options = options;
  1730. if (options.displayStats) {
  1731. this.data = JSON.parse(JSON.stringify(STATS_DEFAULT_VALUES));
  1732. }
  1733. }
  1734. set(type, subType, value) {
  1735. if (this.options.displayStats) {
  1736. this.data[type][subType] = value;
  1737. }
  1738. }
  1739. add(type, subType, value) {
  1740. if (this.options.displayStats) {
  1741. this.data[type][subType] += value;
  1742. }
  1743. }
  1744. addAll(pageData) {
  1745. if (this.options.displayStats) {
  1746. Object.keys(this.data.discarded).forEach(key => this.add("discarded", key, pageData.stats.discarded[key] || 0));
  1747. Object.keys(this.data.processed).forEach(key => this.add("processed", key, pageData.stats.processed[key] || 0));
  1748. }
  1749. }
  1750. }
  1751. return { getClass };
  1752. })();