single-file-core.js 82 KB

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