single-file-core.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. /*
  2. * Copyright 2018 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. const SingleFileCore = (() => {
  21. const SELECTED_CONTENT_ATTRIBUTE_NAME = "data-single-file-selected-content";
  22. let Download, DOM, URL;
  23. function SingleFileCore(...args) {
  24. [Download, DOM, URL] = args;
  25. return class {
  26. static async process(options) {
  27. const processor = new PageProcessor(options);
  28. processor.onprogress = options.onprogress;
  29. await processor.loadPage(options.content);
  30. await processor.initialize();
  31. return await processor.getContent();
  32. }
  33. };
  34. }
  35. // -------------
  36. // ProgressEvent
  37. // -------------
  38. const PAGE_LOADING = "page-loading";
  39. const PAGE_LOADED = "page-loaded";
  40. const RESOURCES_INITIALIZING = "resource-initializing";
  41. const RESOURCES_INITIALIZED = "resources-initialized";
  42. const RESOURCE_LOADING = "resource-loading";
  43. const RESOURCE_LOADED = "resource-loaded";
  44. const PAGE_ENDED = "page-ended";
  45. class ProgressEvent {
  46. constructor(type, details) {
  47. return { type, details, PAGE_LOADING, PAGE_LOADED, RESOURCES_INITIALIZING, RESOURCES_INITIALIZED, RESOURCE_LOADING, RESOURCE_LOADED, PAGE_ENDED };
  48. }
  49. }
  50. // -------------
  51. // PageProcessor
  52. // -------------
  53. class PageProcessor {
  54. constructor(options) {
  55. this.options = options;
  56. this.processor = new DOMProcessor(options);
  57. }
  58. async loadPage(pageContent) {
  59. if (this.onprogress) {
  60. this.onprogress(new ProgressEvent(PAGE_LOADING, { pageURL: this.options.url }));
  61. }
  62. await this.processor.loadPage(pageContent);
  63. if (this.onprogress) {
  64. this.onprogress(new ProgressEvent(PAGE_LOADED, { pageURL: this.options.url }));
  65. }
  66. }
  67. async initialize() {
  68. if (this.onprogress) {
  69. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZING, { pageURL: this.options.url }));
  70. }
  71. if (!this.options.jsEnabled) {
  72. this.processor.insertNoscriptContents();
  73. }
  74. this.processor.removeDiscardedResources();
  75. this.processor.resetCharsetMeta();
  76. this.processor.insertFaviconLink();
  77. this.processor.resolveHrefs();
  78. this.processor.insertSingleFileCommentNode();
  79. this.processor.replaceCanvasElements();
  80. if (this.options.removeHiddenElements) {
  81. this.processor.removeHiddenElements();
  82. }
  83. if (this.options.removeUnusedCSSRules) {
  84. this.processor.removeUnusedCSSRules();
  85. }
  86. await Promise.all([this.processor.inlineStylesheets(true), this.processor.linkStylesheets()], this.processor.attributeStyles(true));
  87. this.pendingPromises = Promise.all([this.processor.inlineStylesheets(), this.processor.attributeStyles(), this.processor.pageResources()]);
  88. if (this.onprogress) {
  89. this.onprogress(new ProgressEvent(RESOURCES_INITIALIZED, { pageURL: this.options.url, index: 0, max: batchRequest.getMaxResources() }));
  90. }
  91. }
  92. async getContent() {
  93. await this.processor.retrieveResources(
  94. details => {
  95. if (this.onprogress) {
  96. details.pageURL = this.options.url;
  97. this.onprogress(new ProgressEvent(RESOURCE_LOADING, details));
  98. }
  99. },
  100. details => {
  101. if (this.onprogress) {
  102. details.pageURL = this.options.url;
  103. this.onprogress(new ProgressEvent(RESOURCE_LOADED, details));
  104. }
  105. });
  106. await this.pendingPromises;
  107. if (this.options.removeUnusedCSSRules) {
  108. this.processor.removeUnusedCSSRules();
  109. }
  110. if (this.onprogress) {
  111. this.onprogress(new ProgressEvent(PAGE_ENDED, { pageURL: this.options.url }));
  112. }
  113. return this.processor.getContent();
  114. }
  115. }
  116. // --------
  117. // BatchRequest
  118. // --------
  119. class BatchRequest {
  120. constructor() {
  121. this.requests = new Map();
  122. }
  123. async addURL(resourceURL) {
  124. return new Promise((resolve, reject) => {
  125. const resourceRequests = this.requests.get(resourceURL);
  126. if (resourceRequests) {
  127. resourceRequests.push({ resolve, reject });
  128. } else {
  129. this.requests.set(resourceURL, [{ resolve, reject }]);
  130. }
  131. });
  132. }
  133. getMaxResources() {
  134. return Array.from(this.requests.keys()).length;
  135. }
  136. async run(beforeListener, afterListener) {
  137. const resourceURLs = Array.from(this.requests.keys());
  138. let indexResource = 1, indexAfterResource = 1;
  139. return Promise.all(resourceURLs.map(async resourceURL => {
  140. let error;
  141. const resourceRequests = this.requests.get(resourceURL);
  142. beforeListener({ index: indexResource, max: resourceURLs.length, url: resourceURL, error });
  143. indexResource = indexResource + 1;
  144. try {
  145. const dataURI = await Download.getContent(resourceURL, true);
  146. resourceRequests.map(resourceRequest => resourceRequest.resolve(dataURI));
  147. } catch (responseError) {
  148. error = responseError;
  149. resourceRequests.map(resourceRequest => resourceRequest.reject(error));
  150. }
  151. afterListener({ index: indexAfterResource, max: resourceURLs.length, url: resourceURL, error });
  152. indexAfterResource = indexAfterResource + 1;
  153. this.requests.delete(resourceURL);
  154. }));
  155. }
  156. }
  157. // ------------
  158. // DOMProcessor
  159. // ------------
  160. const ESCAPED_FRAGMENT = "_escaped_fragment_=";
  161. const batchRequest = new BatchRequest();
  162. class DOMProcessor {
  163. constructor(options) {
  164. this.options = options;
  165. this.baseURI = options.url;
  166. }
  167. async loadPage(pageContent) {
  168. if (!pageContent) {
  169. pageContent = await Download.getContent(this.baseURI);
  170. }
  171. this.dom = DOM.create(pageContent, this.baseURI);
  172. this.DOMParser = this.dom.DOMParser;
  173. this.getComputedStyle = this.dom.getComputedStyle;
  174. this.doc = this.dom.document;
  175. if (!pageContent && this.doc.querySelector("meta[name=fragment][content=\"!\"]") && !this.baseURI.endsWith("?" + ESCAPED_FRAGMENT) && !this.baseURI.endsWith("&" + ESCAPED_FRAGMENT)) {
  176. await DOMProcessor.loadEscapedFragmentPage();
  177. }
  178. }
  179. async loadEscapedFragmentPage() {
  180. if (this.baseURI.includes("?")) {
  181. this.baseURI += "&";
  182. } else {
  183. this.baseURI += "?";
  184. }
  185. this.baseURI += ESCAPED_FRAGMENT;
  186. await this.loadPage();
  187. }
  188. async retrieveResources(beforeListener, afterListener) {
  189. await batchRequest.run(beforeListener, afterListener);
  190. }
  191. getContent() {
  192. if (this.options.selected) {
  193. const selectedElement = this.doc.querySelector("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]");
  194. DomProcessorHelper.isolateElement(selectedElement.parentElement, selectedElement);
  195. selectedElement.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME);
  196. }
  197. const titleElement = this.doc.head.querySelector("title");
  198. let title;
  199. if (titleElement) {
  200. title = titleElement.textContent.trim();
  201. }
  202. return {
  203. title: title || this.baseURI.match(/([^/]*)\/?$/),
  204. content: this.dom.serialize()
  205. };
  206. }
  207. insertNoscriptContents() {
  208. if (this.DOMParser) {
  209. this.doc.querySelectorAll("noscript").forEach(element => {
  210. const fragment = this.doc.createDocumentFragment();
  211. Array.from(element.childNodes).forEach(node => {
  212. const parsedNode = new this.DOMParser().parseFromString(node.nodeValue, "text/html");
  213. Array.from(parsedNode.head.childNodes).concat(Array.from(parsedNode.body.childNodes)).forEach(node => {
  214. this.doc.importNode(node);
  215. fragment.appendChild(node);
  216. });
  217. });
  218. element.parentElement.replaceChild(fragment, element);
  219. });
  220. }
  221. }
  222. removeDiscardedResources() {
  223. this.doc.querySelectorAll("script, iframe, frame, applet, meta[http-equiv=refresh], object:not([type=\"image/svg+xml\"]):not([type=\"image/svg-xml\"]), embed:not([src*=\".svg\"]), link[rel*=preload], link[rel*=prefetch]").forEach(element => element.remove());
  224. this.doc.querySelectorAll("[onload]").forEach(element => element.removeAttribute("onload"));
  225. this.doc.querySelectorAll("audio[src], video[src]").forEach(element => element.removeAttribute("src"));
  226. }
  227. resetCharsetMeta() {
  228. this.doc.querySelectorAll("meta[charset]").forEach(element => element.remove());
  229. const metaElement = this.doc.createElement("meta");
  230. metaElement.setAttribute("charset", "utf-8");
  231. this.doc.head.insertBefore(metaElement, this.doc.head.firstElementChild);
  232. }
  233. insertFaviconLink() {
  234. let faviconElement = this.doc.querySelectorAll("link[href][rel*=\"icon\"]")[0];
  235. if (!faviconElement) {
  236. faviconElement = this.doc.createElement("link");
  237. faviconElement.setAttribute("type", "image/x-icon");
  238. faviconElement.setAttribute("rel", "shortcut icon");
  239. faviconElement.setAttribute("href", "/favicon.ico");
  240. this.doc.head.appendChild(faviconElement);
  241. }
  242. }
  243. resolveHrefs() {
  244. this.doc.querySelectorAll("[href]").forEach(element => element.setAttribute("href", element.href));
  245. }
  246. removeUnusedCSSRules() {
  247. const doc = this.doc;
  248. doc.querySelectorAll("style").forEach(style => {
  249. const cssRules = [];
  250. if (style.sheet) {
  251. processRules(style.sheet.rules, cssRules);
  252. style.innerText = cssRules.join("");
  253. }
  254. });
  255. function processRules(rules, cssRules) {
  256. if (rules) {
  257. Array.from(rules).forEach(rule => {
  258. if (rule.media) {
  259. cssRules.push("@media " + Array.prototype.join.call(rule.media, ",") + " {");
  260. processRules(rule.cssRules, cssRules);
  261. cssRules.push("}");
  262. } else if (rule.selectorText) {
  263. const selector = rule.selectorText.replace(/::after|::before|::first-line|::first-letter|:focus|:hover/gi, "").trim();
  264. if (selector) {
  265. try {
  266. if (doc.querySelector(selector)) {
  267. cssRules.push(rule.cssText);
  268. }
  269. } catch (e) {
  270. cssRules.push(rule.cssText);
  271. }
  272. }
  273. } else {
  274. cssRules.push(rule.cssText);
  275. }
  276. });
  277. }
  278. }
  279. }
  280. removeHiddenElements() {
  281. this.doc.querySelectorAll("html > body *:not(style):not(script):not(link)").forEach(element => {
  282. if (this.getComputedStyle) {
  283. const style = this.getComputedStyle(element);
  284. if ((style.visibility == "hidden" || style.display == "none" || style.opacity == 0)) {
  285. element.remove();
  286. }
  287. }
  288. });
  289. }
  290. insertSingleFileCommentNode() {
  291. const commentNode = this.doc.createComment("\n Archive processed by SingleFile \n url: " + this.baseURI + " \n saved date: " + new Date() + " \n");
  292. this.doc.documentElement.insertBefore(commentNode, this.doc.documentElement.firstChild);
  293. }
  294. replaceCanvasElements() {
  295. if (this.options.canvasData) {
  296. this.doc.querySelectorAll("canvas").forEach((canvasElement, indexCanvasElement) => {
  297. const canvasData = this.options.canvasData[indexCanvasElement];
  298. if (canvasData) {
  299. const imgElement = this.doc.createElement("img");
  300. imgElement.setAttribute("src", canvasData.dataURI);
  301. Array.from(canvasElement.attributes).forEach(attribute => {
  302. if (attribute.value) {
  303. imgElement.setAttribute(attribute.name, attribute.value);
  304. }
  305. });
  306. if (!imgElement.width && canvasData.width) {
  307. imgElement.style.pixelWidth = canvasData.width;
  308. }
  309. if (!imgElement.height && canvasData.height) {
  310. imgElement.style.pixelHeight = canvasData.height;
  311. }
  312. canvasElement.parentElement.replaceChild(imgElement, canvasElement);
  313. }
  314. });
  315. }
  316. }
  317. async pageResources() {
  318. await Promise.all([
  319. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("link[href][rel*=\"icon\"]"), "href", this.baseURI),
  320. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("img[src], input[src][type=image], object[type=\"image/svg+xml\"], object[type=\"image/svg-xml\"], embed[src*=\".svg\"]"), "src", this.baseURI),
  321. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("video[poster]"), "poster", this.baseURI),
  322. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("*[background]"), "background", this.baseURI),
  323. DomProcessorHelper.processAttribute(this.doc.querySelectorAll("image, use"), "xlink:href", this.baseURI),
  324. DomProcessorHelper.processSrcSet(this.doc.querySelectorAll("[srcset]"), this.baseURI, this.dom)
  325. ]);
  326. }
  327. async inlineStylesheets(initialization) {
  328. await Promise.all(Array.from(this.doc.querySelectorAll("style")).map(async styleElement => {
  329. let stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(styleElement.textContent, this.baseURI) : await DomProcessorHelper.processStylesheet(styleElement.textContent, this.baseURI);
  330. styleElement.textContent = stylesheetContent;
  331. }));
  332. }
  333. async attributeStyles(initialization) {
  334. await Promise.all(Array.from(this.doc.querySelectorAll("[style]")).map(async element => {
  335. const stylesheetContent = initialization ? await DomProcessorHelper.resolveImportURLs(element.getAttribute("style"), this.baseURI) : await DomProcessorHelper.processStylesheet(element.getAttribute("style"), this.baseURI);
  336. element.setAttribute("style", stylesheetContent);
  337. }));
  338. }
  339. async linkStylesheets() {
  340. await Promise.all(Array.from(this.doc.querySelectorAll("link[rel*=stylesheet]")).map(async linkElement => {
  341. const stylesheetContent = await DomProcessorHelper.resolveLinkStylesheetURLs(linkElement.href, this.baseURI, linkElement.media);
  342. const styleElement = this.doc.createElement("style");
  343. styleElement.textContent = stylesheetContent;
  344. linkElement.parentElement.replaceChild(styleElement, linkElement);
  345. }));
  346. }
  347. }
  348. // ---------
  349. // DomHelper
  350. // ---------
  351. class DomProcessorHelper {
  352. static isolateElement(parentElement, element) {
  353. Array.from(parentElement.childNodes).forEach(node => {
  354. if (node == element) {
  355. node.removeAttribute("style");
  356. node.style.all = "unset";
  357. } else {
  358. if (node.tagName != "HEAD" && node.tagName != "STYLE") {
  359. node.remove();
  360. }
  361. }
  362. });
  363. element = element.parentElement;
  364. if (element.parentElement) {
  365. DomProcessorHelper.isolateElement(element.parentElement, element);
  366. }
  367. }
  368. static async resolveImportURLs(stylesheetContent, baseURI) {
  369. stylesheetContent = DomUtil.removeCssComments(stylesheetContent);
  370. const imports = DomUtil.getImportFunctions(stylesheetContent);
  371. await Promise.all(imports.map(async cssImport => {
  372. const match = DomUtil.matchImport(cssImport);
  373. if (match) {
  374. const resourceURL = DomUtil.normalizeURL(match.resourceURL);
  375. if (resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  376. let importedStylesheetContent = await Download.getContent(new URL(match.resourceURL, baseURI).href);
  377. importedStylesheetContent = DomUtil.wrapMediaQuery(importedStylesheetContent, match.media);
  378. if (stylesheetContent.indexOf(cssImport) != -1) {
  379. stylesheetContent = stylesheetContent.replace(cssImport, importedStylesheetContent);
  380. }
  381. }
  382. }
  383. }));
  384. stylesheetContent = DomProcessorHelper.resolveStylesheetURLs(stylesheetContent, baseURI);
  385. if (imports.length) {
  386. return await DomProcessorHelper.resolveImportURLs(stylesheetContent, baseURI);
  387. } else {
  388. return stylesheetContent;
  389. }
  390. }
  391. static resolveStylesheetURLs(stylesheetContent, baseURI) {
  392. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  393. urlFunctions.map(urlFunction => {
  394. let resourceURL = DomUtil.matchURL(urlFunction);
  395. resourceURL = DomUtil.normalizeURL(resourceURL);
  396. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  397. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, new URL(resourceURL, baseURI).href));
  398. }
  399. });
  400. return stylesheetContent;
  401. }
  402. static async resolveLinkStylesheetURLs(resourceURL, baseURI, media) {
  403. resourceURL = DomUtil.normalizeURL(resourceURL);
  404. if (resourceURL && resourceURL != baseURI && resourceURL != ABOUT_BLANK_URI) {
  405. let stylesheetContent = await Download.getContent(resourceURL);
  406. stylesheetContent = await DomProcessorHelper.resolveImportURLs(stylesheetContent, resourceURL);
  407. stylesheetContent = DomUtil.wrapMediaQuery(stylesheetContent, media);
  408. return stylesheetContent;
  409. }
  410. }
  411. static async processStylesheet(stylesheetContent, baseURI) {
  412. const urlFunctions = DomUtil.getUrlFunctions(stylesheetContent);
  413. await Promise.all(urlFunctions.map(async urlFunction => {
  414. let resourceURL = DomUtil.matchURL(urlFunction);
  415. resourceURL = DomUtil.normalizeURL(resourceURL);
  416. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  417. const dataURI = await batchRequest.addURL(resourceURL);
  418. stylesheetContent = stylesheetContent.replace(urlFunction, urlFunction.replace(resourceURL, dataURI));
  419. }
  420. }));
  421. return stylesheetContent;
  422. }
  423. static async processAttribute(resourceElements, attributeName, baseURI) {
  424. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  425. let resourceURL = resourceElement.getAttribute(attributeName);
  426. if (resourceURL) {
  427. resourceURL = DomUtil.normalizeURL(resourceURL);
  428. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  429. try {
  430. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  431. resourceElement.setAttribute(attributeName, dataURI);
  432. } catch (e) {
  433. // ignored
  434. }
  435. }
  436. }
  437. }));
  438. }
  439. static async processSrcSet(resourceElements, baseURI, dom) {
  440. await Promise.all(Array.from(resourceElements).map(async resourceElement => {
  441. const srcSet = dom.parseSrcSet(resourceElement.getAttribute("srcset"));
  442. const srcSetValues = await Promise.all(srcSet.map(async srcSetValue => {
  443. const resourceURL = DomUtil.normalizeURL(srcSetValue.url);
  444. if (resourceURL && resourceURL != baseURI && DomUtil.testValidPath(resourceURL)) {
  445. try {
  446. const dataURI = await batchRequest.addURL(new URL(resourceURL, baseURI).href);
  447. return dataURI + (srcSetValue.w ? " " + srcSetValue.w : "");
  448. } catch (e) {
  449. // ignored
  450. }
  451. }
  452. }));
  453. resourceElement.setAttribute("srcset", srcSetValues.join(","));
  454. }));
  455. }
  456. }
  457. // -------
  458. // DomUtil
  459. // -------
  460. const DATA_URI_PREFIX = "data:";
  461. const BLOB_URI_PREFIX = "blob:";
  462. const ABOUT_BLANK_URI = "about:blank";
  463. const REGEXP_URL_FN = /(url\s*\(\s*'([^']*)'\s*\))|(url\s*\(\s*"([^"]*)"\s*\))|(url\s*\(\s*([^)]*)\s*\))/gi;
  464. const REGEXP_URL_SIMPLE_QUOTES_FN = /^url\s*\(\s*'([^']*)'\s*\)$/i;
  465. const REGEXP_URL_DOUBLE_QUOTES_FN = /^url\s*\(\s*"([^"]*)"\s*\)$/i;
  466. const REGEXP_URL_NO_QUOTES_FN = /^url\s*\(\s*([^)]*)\s*\)$/i;
  467. 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*'([^']*)'\s*\)\s*([^;]*);?)|(@import\s*\(\s*"([^"]*)"\s*\)\s*([^;]*);?)|(@import\s*\(\s*([^)]*)\s*\)\s*([^;]*);?)/gi;
  468. const REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN = /@import\s*url\s*\(\s*'([^']*)'\s*\)\s*([^;]*)/i;
  469. const REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN = /@import\s*url\s*\(\s*"([^"]*)"\s*\)\s*([^;]*)/i;
  470. const REGEXP_IMPORT_URL_NO_QUOTES_FN = /@import\s*url\s*\(\s*([^)]*)\s*\)\s*([^;]*)/i;
  471. const REGEXP_IMPORT_SIMPLE_QUOTES_FN = /@import\s*\(\s*'([^']*)'\s*\)\s*([^;]*)/i;
  472. const REGEXP_IMPORT_DOUBLE_QUOTES_FN = /@import\s*\(\s*"([^"]*)"\s*\)\s*([^;]*)/i;
  473. const REGEXP_IMPORT_NO_QUOTES_FN = /@import\s*\(\s*([^)]*)\s*\)\s*([^;]*)/i;
  474. class DomUtil {
  475. static normalizeURL(url) {
  476. return url.split("#")[0];
  477. }
  478. static getUrlFunctions(stylesheetContent) {
  479. return stylesheetContent.match(REGEXP_URL_FN) || [];
  480. }
  481. static getImportFunctions(stylesheetContent) {
  482. return stylesheetContent.match(REGEXP_IMPORT_FN) || [];
  483. }
  484. static matchURL(stylesheetContent) {
  485. const match = stylesheetContent.match(REGEXP_URL_SIMPLE_QUOTES_FN) ||
  486. stylesheetContent.match(REGEXP_URL_DOUBLE_QUOTES_FN) ||
  487. stylesheetContent.match(REGEXP_URL_NO_QUOTES_FN);
  488. return match && match[1];
  489. }
  490. static testValidPath(resourceURL) {
  491. return !resourceURL.startsWith(DATA_URI_PREFIX) && !resourceURL.startsWith(BLOB_URI_PREFIX) && resourceURL != ABOUT_BLANK_URI;
  492. }
  493. static matchImport(stylesheetContent) {
  494. const match = stylesheetContent.match(REGEXP_IMPORT_URL_SIMPLE_QUOTES_FN) ||
  495. stylesheetContent.match(REGEXP_IMPORT_URL_DOUBLE_QUOTES_FN) ||
  496. stylesheetContent.match(REGEXP_IMPORT_URL_NO_QUOTES_FN) ||
  497. stylesheetContent.match(REGEXP_IMPORT_SIMPLE_QUOTES_FN) ||
  498. stylesheetContent.match(REGEXP_IMPORT_DOUBLE_QUOTES_FN) ||
  499. stylesheetContent.match(REGEXP_IMPORT_NO_QUOTES_FN);
  500. if (match) {
  501. const [, resourceURL, media] = match;
  502. return { resourceURL, media };
  503. }
  504. }
  505. static removeCssComments(stylesheetContent) {
  506. let start, end;
  507. do {
  508. start = stylesheetContent.indexOf("/*");
  509. end = stylesheetContent.indexOf("*/", start);
  510. if (start != -1 && end != -1) {
  511. stylesheetContent = stylesheetContent.substring(0, start) + stylesheetContent.substr(end + 2);
  512. }
  513. } while (start != -1 && end != -1);
  514. return stylesheetContent;
  515. }
  516. static wrapMediaQuery(stylesheetContent, mediaQuery) {
  517. if (mediaQuery) {
  518. return "@media " + mediaQuery + "{ " + stylesheetContent + " }";
  519. } else {
  520. return stylesheetContent;
  521. }
  522. }
  523. }
  524. return SingleFileCore;
  525. })();
  526. if (typeof module != "undefined") {
  527. module.exports = SingleFileCore;
  528. }