critters.mjs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. import path from 'path';
  2. import { readFile } from 'fs';
  3. import prettyBytes from 'pretty-bytes';
  4. import parse5 from 'parse5';
  5. import { selectOne, selectAll } from 'css-select';
  6. import treeAdapter from 'parse5-htmlparser2-tree-adapter';
  7. import { parse, stringify } from 'postcss';
  8. import chalk from 'chalk';
  9. /**
  10. * Copyright 2018 Google LLC
  11. *
  12. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  13. * use this file except in compliance with the License. You may obtain a copy of
  14. * the License at
  15. *
  16. * http://www.apache.org/licenses/LICENSE-2.0
  17. *
  18. * Unless required by applicable law or agreed to in writing, software
  19. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  20. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  21. * License for the specific language governing permissions and limitations under
  22. * the License.
  23. */
  24. const PARSE5_OPTS = {
  25. treeAdapter
  26. };
  27. /**
  28. * Parse HTML into a mutable, serializable DOM Document.
  29. * The DOM implementation is an htmlparser2 DOM enhanced with basic DOM mutation methods.
  30. * @param {String} html HTML to parse into a Document instance
  31. */
  32. function createDocument(html) {
  33. const document =
  34. /** @type {HTMLDocument} */
  35. parse5.parse(html, PARSE5_OPTS);
  36. defineProperties(document, DocumentExtensions); // Extend Element.prototype with DOM manipulation methods.
  37. const scratch = document.createElement('div'); // Get a reference to the base Node class - used by createTextNode()
  38. document.$$Node = scratch.constructor;
  39. const elementProto = Object.getPrototypeOf(scratch);
  40. defineProperties(elementProto, ElementExtensions);
  41. elementProto.ownerDocument = document;
  42. return document;
  43. }
  44. /**
  45. * Serialize a Document to an HTML String
  46. * @param {HTMLDocument} document A Document, such as one created via `createDocument()`
  47. */
  48. function serializeDocument(document) {
  49. return parse5.serialize(document, PARSE5_OPTS);
  50. }
  51. /** @typedef {treeAdapter.Document & typeof ElementExtensions} HTMLDocument */
  52. /**
  53. * Methods and descriptors to mix into Element.prototype
  54. * @private
  55. */
  56. const ElementExtensions = {
  57. /** @extends treeAdapter.Element.prototype */
  58. nodeName: {
  59. get() {
  60. return this.tagName.toUpperCase();
  61. }
  62. },
  63. id: reflectedProperty('id'),
  64. className: reflectedProperty('class'),
  65. insertBefore(child, referenceNode) {
  66. if (!referenceNode) return this.appendChild(child);
  67. treeAdapter.insertBefore(this, child, referenceNode);
  68. return child;
  69. },
  70. appendChild(child) {
  71. treeAdapter.appendChild(this, child);
  72. return child;
  73. },
  74. removeChild(child) {
  75. treeAdapter.detachNode(child);
  76. },
  77. remove() {
  78. treeAdapter.detachNode(this);
  79. },
  80. textContent: {
  81. get() {
  82. return getText(this);
  83. },
  84. set(text) {
  85. this.children = [];
  86. treeAdapter.insertText(this, text);
  87. }
  88. },
  89. setAttribute(name, value) {
  90. if (this.attribs == null) this.attribs = {};
  91. if (value == null) value = '';
  92. this.attribs[name] = value;
  93. },
  94. removeAttribute(name) {
  95. if (this.attribs != null) {
  96. delete this.attribs[name];
  97. }
  98. },
  99. getAttribute(name) {
  100. return this.attribs != null && this.attribs[name];
  101. },
  102. hasAttribute(name) {
  103. return this.attribs != null && this.attribs[name] != null;
  104. },
  105. getAttributeNode(name) {
  106. const value = this.getAttribute(name);
  107. if (value != null) return {
  108. specified: true,
  109. value
  110. };
  111. }
  112. };
  113. /**
  114. * Methods and descriptors to mix into the global document instance
  115. * @private
  116. */
  117. const DocumentExtensions = {
  118. /** @extends treeAdapter.Document.prototype */
  119. // document is just an Element in htmlparser2, giving it a nodeType of ELEMENT_NODE.
  120. // TODO: verify if these are needed for css-select
  121. nodeType: {
  122. get() {
  123. return 9;
  124. }
  125. },
  126. contentType: {
  127. get() {
  128. return 'text/html';
  129. }
  130. },
  131. nodeName: {
  132. get() {
  133. return '#document';
  134. }
  135. },
  136. documentElement: {
  137. get() {
  138. // Find the first <html> element within the document
  139. return this.childNodes.filter(child => String(child.tagName).toLowerCase() === 'html');
  140. }
  141. },
  142. compatMode: {
  143. get() {
  144. const compatMode = {
  145. 'no-quirks': 'CSS1Compat',
  146. quirks: 'BackCompat',
  147. 'limited-quirks': 'CSS1Compat'
  148. };
  149. return compatMode[treeAdapter.getDocumentMode(this)];
  150. }
  151. },
  152. head: {
  153. get() {
  154. return this.querySelector('head');
  155. }
  156. },
  157. body: {
  158. get() {
  159. return this.querySelector('body');
  160. }
  161. },
  162. createElement(name) {
  163. return treeAdapter.createElement(name, null, []);
  164. },
  165. createTextNode(text) {
  166. // there is no dedicated createTextNode equivalent exposed in htmlparser2's DOM
  167. const Node = this.$$Node;
  168. return new Node({
  169. type: 'text',
  170. data: text,
  171. parent: null,
  172. prev: null,
  173. next: null
  174. });
  175. },
  176. querySelector(sel) {
  177. return selectOne(sel, this.documentElement);
  178. },
  179. querySelectorAll(sel) {
  180. if (sel === ':root') {
  181. return this;
  182. }
  183. return selectAll(sel, this.documentElement);
  184. }
  185. };
  186. /**
  187. * Essentially `Object.defineProperties()`, except function values are assigned as value descriptors for convenience.
  188. * @private
  189. */
  190. function defineProperties(obj, properties) {
  191. for (const i in properties) {
  192. const value = properties[i];
  193. Object.defineProperty(obj, i, typeof value === 'function' ? {
  194. value
  195. } : value);
  196. }
  197. }
  198. /**
  199. * Create a property descriptor defining a getter/setter pair alias for a named attribute.
  200. * @private
  201. */
  202. function reflectedProperty(attributeName) {
  203. return {
  204. get() {
  205. return this.getAttribute(attributeName);
  206. },
  207. set(value) {
  208. this.setAttribute(attributeName, value);
  209. }
  210. };
  211. }
  212. /**
  213. * Helper to get the text content of a node
  214. * https://github.com/fb55/domutils/blob/master/src/stringify.ts#L21
  215. * @private
  216. */
  217. function getText(node) {
  218. if (Array.isArray(node)) return node.map(getText).join('');
  219. if (treeAdapter.isElementNode(node)) return node.name === 'br' ? '\n' : getText(node.children);
  220. if (treeAdapter.isTextNode(node)) return node.data;
  221. return '';
  222. }
  223. /**
  224. * Copyright 2018 Google LLC
  225. *
  226. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  227. * use this file except in compliance with the License. You may obtain a copy of
  228. * the License at
  229. *
  230. * http://www.apache.org/licenses/LICENSE-2.0
  231. *
  232. * Unless required by applicable law or agreed to in writing, software
  233. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  234. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  235. * License for the specific language governing permissions and limitations under
  236. * the License.
  237. */
  238. /**
  239. * Parse a textual CSS Stylesheet into a Stylesheet instance.
  240. * Stylesheet is a mutable postcss AST with format similar to CSSOM.
  241. * @see https://github.com/postcss/postcss/
  242. * @private
  243. * @param {String} stylesheet
  244. * @returns {css.Stylesheet} ast
  245. */
  246. function parseStylesheet(stylesheet) {
  247. return parse(stylesheet);
  248. }
  249. /**
  250. * Serialize a postcss Stylesheet to a String of CSS.
  251. * @private
  252. * @param {css.Stylesheet} ast A Stylesheet to serialize, such as one returned from `parseStylesheet()`
  253. * @param {Object} options Options used by the stringify logic
  254. * @param {Boolean} [options.compress] Compress CSS output (removes comments, whitespace, etc)
  255. */
  256. function serializeStylesheet(ast, options) {
  257. let cssStr = '';
  258. stringify(ast, (result, node, type) => {
  259. var _node$raws;
  260. if (!options.compress) {
  261. cssStr += result;
  262. return;
  263. } // Simple minification logic
  264. if ((node == null ? void 0 : node.type) === 'comment') return;
  265. if ((node == null ? void 0 : node.type) === 'decl') {
  266. const prefix = node.prop + node.raws.between;
  267. cssStr += result.replace(prefix, prefix.trim());
  268. return;
  269. }
  270. if (type === 'start') {
  271. if (node.type === 'rule' && node.selectors) {
  272. cssStr += node.selectors.join(',') + '{';
  273. } else {
  274. cssStr += result.replace(/\s\{$/, '{');
  275. }
  276. return;
  277. }
  278. if (type === 'end' && result === '}' && node != null && (_node$raws = node.raws) != null && _node$raws.semicolon) {
  279. cssStr = cssStr.slice(0, -1);
  280. }
  281. cssStr += result.trim();
  282. });
  283. return cssStr;
  284. }
  285. /**
  286. * Converts a walkStyleRules() iterator to mark nodes with `.$$remove=true` instead of actually removing them.
  287. * This means they can be removed in a second pass, allowing the first pass to be nondestructive (eg: to preserve mirrored sheets).
  288. * @private
  289. * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node.
  290. * @returns {(rule) => void} nonDestructiveIterator
  291. */
  292. function markOnly(predicate) {
  293. return rule => {
  294. const sel = rule.selectors;
  295. if (predicate(rule) === false) {
  296. rule.$$remove = true;
  297. }
  298. rule.$$markedSelectors = rule.selectors;
  299. if (rule._other) {
  300. rule._other.$$markedSelectors = rule._other.selectors;
  301. }
  302. rule.selectors = sel;
  303. };
  304. }
  305. /**
  306. * Apply filtered selectors to a rule from a previous markOnly run.
  307. * @private
  308. * @param {css.Rule} rule The Rule to apply marked selectors to (if they exist).
  309. */
  310. function applyMarkedSelectors(rule) {
  311. if (rule.$$markedSelectors) {
  312. rule.selectors = rule.$$markedSelectors;
  313. }
  314. if (rule._other) {
  315. applyMarkedSelectors(rule._other);
  316. }
  317. }
  318. /**
  319. * Recursively walk all rules in a stylesheet.
  320. * @private
  321. * @param {css.Rule} node A Stylesheet or Rule to descend into.
  322. * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node.
  323. */
  324. function walkStyleRules(node, iterator) {
  325. node.nodes = node.nodes.filter(rule => {
  326. if (hasNestedRules(rule)) {
  327. walkStyleRules(rule, iterator);
  328. }
  329. rule._other = undefined;
  330. rule.filterSelectors = filterSelectors;
  331. return iterator(rule) !== false;
  332. });
  333. }
  334. /**
  335. * Recursively walk all rules in two identical stylesheets, filtering nodes into one or the other based on a predicate.
  336. * @private
  337. * @param {css.Rule} node A Stylesheet or Rule to descend into.
  338. * @param {css.Rule} node2 A second tree identical to `node`
  339. * @param {Function} iterator Invoked on each node in the tree. Return `false` to remove that node from the first tree, true to remove it from the second.
  340. */
  341. function walkStyleRulesWithReverseMirror(node, node2, iterator) {
  342. if (node2 === null) return walkStyleRules(node, iterator);
  343. [node.nodes, node2.nodes] = splitFilter(node.nodes, node2.nodes, (rule, index, rules, rules2) => {
  344. const rule2 = rules2[index];
  345. if (hasNestedRules(rule)) {
  346. walkStyleRulesWithReverseMirror(rule, rule2, iterator);
  347. }
  348. rule._other = rule2;
  349. rule.filterSelectors = filterSelectors;
  350. return iterator(rule) !== false;
  351. });
  352. } // Checks if a node has nested rules, like @media
  353. // @keyframes are an exception since they are evaluated as a whole
  354. function hasNestedRules(rule) {
  355. return rule.nodes && rule.nodes.length && rule.nodes.some(n => n.type === 'rule' || n.type === 'atrule') && rule.name !== 'keyframes' && rule.name !== '-webkit-keyframes';
  356. } // Like [].filter(), but applies the opposite filtering result to a second copy of the Array without a second pass.
  357. // This is just a quicker version of generating the compliment of the set returned from a filter operation.
  358. function splitFilter(a, b, predicate) {
  359. const aOut = [];
  360. const bOut = [];
  361. for (let index = 0; index < a.length; index++) {
  362. if (predicate(a[index], index, a, b)) {
  363. aOut.push(a[index]);
  364. } else {
  365. bOut.push(a[index]);
  366. }
  367. }
  368. return [aOut, bOut];
  369. } // can be invoked on a style rule to subset its selectors (with reverse mirroring)
  370. function filterSelectors(predicate) {
  371. if (this._other) {
  372. const [a, b] = splitFilter(this.selectors, this._other.selectors, predicate);
  373. this.selectors = a;
  374. this._other.selectors = b;
  375. } else {
  376. this.selectors = this.selectors.filter(predicate);
  377. }
  378. }
  379. const LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'silent'];
  380. const defaultLogger = {
  381. trace(msg) {
  382. console.trace(msg);
  383. },
  384. debug(msg) {
  385. console.debug(msg);
  386. },
  387. warn(msg) {
  388. console.warn(chalk.yellow(msg));
  389. },
  390. error(msg) {
  391. console.error(chalk.bold.red(msg));
  392. },
  393. info(msg) {
  394. console.info(chalk.bold.blue(msg));
  395. },
  396. silent() {}
  397. };
  398. function createLogger(logLevel) {
  399. const logLevelIdx = LOG_LEVELS.indexOf(logLevel);
  400. return LOG_LEVELS.reduce((logger, type, index) => {
  401. if (index >= logLevelIdx) {
  402. logger[type] = defaultLogger[type];
  403. } else {
  404. logger[type] = defaultLogger.silent;
  405. }
  406. return logger;
  407. }, {});
  408. }
  409. /**
  410. * Copyright 2018 Google LLC
  411. *
  412. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  413. * use this file except in compliance with the License. You may obtain a copy of
  414. * the License at
  415. *
  416. * http://www.apache.org/licenses/LICENSE-2.0
  417. *
  418. * Unless required by applicable law or agreed to in writing, software
  419. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  420. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  421. * License for the specific language governing permissions and limitations under
  422. * the License.
  423. */
  424. /**
  425. * The mechanism to use for lazy-loading stylesheets.
  426. *
  427. * Note: <kbd>JS</kbd> indicates a strategy requiring JavaScript (falls back to `<noscript>` unless disabled).
  428. *
  429. * - **default:** Move stylesheet links to the end of the document and insert preload meta tags in their place.
  430. * - **"body":** Move all external stylesheet links to the end of the document.
  431. * - **"media":** Load stylesheets asynchronously by adding `media="not x"` and removing once loaded. <kbd>JS</kbd>
  432. * - **"swap":** Convert stylesheet links to preloads that swap to `rel="stylesheet"` once loaded ([details](https://www.filamentgroup.com/lab/load-css-simpler/#the-code)). <kbd>JS</kbd>
  433. * - **"swap-high":** Use `<link rel="alternate stylesheet preload">` and swap to `rel="stylesheet"` once loaded ([details](http://filamentgroup.github.io/loadCSS/test/new-high.html)). <kbd>JS</kbd>
  434. * - **"js":** Inject an asynchronous CSS loader similar to [LoadCSS](https://github.com/filamentgroup/loadCSS) and use it to load stylesheets. <kbd>JS</kbd>
  435. * - **"js-lazy":** Like `"js"`, but the stylesheet is disabled until fully loaded.
  436. * - **false:** Disables adding preload tags.
  437. * @typedef {(default|'body'|'media'|'swap'|'swap-high'|'js'|'js-lazy')} PreloadStrategy
  438. * @public
  439. */
  440. /**
  441. * Controls which keyframes rules are inlined.
  442. *
  443. * - **"critical":** _(default)_ inline keyframes rules that are used by the critical CSS.
  444. * - **"all":** Inline all keyframes rules.
  445. * - **"none":** Remove all keyframes rules.
  446. * @typedef {('critical'|'all'|'none')} KeyframeStrategy
  447. * @private
  448. * @property {String} keyframes Which {@link KeyframeStrategy keyframe strategy} to use (default: `critical`)_
  449. */
  450. /**
  451. * Controls log level of the plugin. Specifies the level the logger should use. A logger will
  452. * not produce output for any log level beneath the specified level. Available levels and order
  453. * are:
  454. *
  455. * - **"info"** _(default)_
  456. * - **"warn"**
  457. * - **"error"**
  458. * - **"trace"**
  459. * - **"debug"**
  460. * - **"silent"**
  461. * @typedef {('info'|'warn'|'error'|'trace'|'debug'|'silent')} LogLevel
  462. * @public
  463. */
  464. /**
  465. * Custom logger interface:
  466. * @typedef {object} Logger
  467. * @public
  468. * @property {function(String)} trace - Prints a trace message
  469. * @property {function(String)} debug - Prints a debug message
  470. * @property {function(String)} info - Prints an information message
  471. * @property {function(String)} warn - Prints a warning message
  472. * @property {function(String)} error - Prints an error message
  473. */
  474. /**
  475. * All optional. Pass them to `new Critters({ ... })`.
  476. * @public
  477. * @typedef Options
  478. * @property {String} path Base path location of the CSS files _(default: `''`)_
  479. * @property {String} publicPath Public path of the CSS resources. This prefix is removed from the href _(default: `''`)_
  480. * @property {Boolean} external Inline styles from external stylesheets _(default: `true`)_
  481. * @property {Number} inlineThreshold Inline external stylesheets smaller than a given size _(default: `0`)_
  482. * @property {Number} minimumExternalSize If the non-critical external stylesheet would be below this size, just inline it _(default: `0`)_
  483. * @property {Boolean} pruneSource Remove inlined rules from the external stylesheet _(default: `false`)_
  484. * @property {Boolean} mergeStylesheets Merged inlined stylesheets into a single `<style>` tag _(default: `true`)_
  485. * @property {String[]} additionalStylesheets Glob for matching other stylesheets to be used while looking for critical CSS.
  486. * @property {String} preload Which {@link PreloadStrategy preload strategy} to use
  487. * @property {Boolean} noscriptFallback Add `<noscript>` fallback to JS-based strategies
  488. * @property {Boolean} inlineFonts Inline critical font-face rules _(default: `false`)_
  489. * @property {Boolean} preloadFonts Preloads critical fonts _(default: `true`)_
  490. * @property {Boolean} fonts Shorthand for setting `inlineFonts` + `preloadFonts`
  491. * - Values:
  492. * - `true` to inline critical font-face rules and preload the fonts
  493. * - `false` to don't inline any font-face rules and don't preload fonts
  494. * @property {String} keyframes Controls which keyframes rules are inlined.
  495. * - Values:
  496. * - `"critical"`: _(default)_ inline keyframes rules used by the critical CSS
  497. * - `"all"` inline all keyframes rules
  498. * - `"none"` remove all keyframes rules
  499. * @property {Boolean} compress Compress resulting critical CSS _(default: `true`)_
  500. * @property {String} logLevel Controls {@link LogLevel log level} of the plugin _(default: `"info"`)_
  501. * @property {object} logger Provide a custom logger interface {@link Logger logger}
  502. */
  503. class Critters {
  504. /** @private */
  505. constructor(options) {
  506. this.options = Object.assign({
  507. logLevel: 'info',
  508. path: '',
  509. publicPath: '',
  510. reduceInlineStyles: true,
  511. pruneSource: false,
  512. additionalStylesheets: []
  513. }, options || {});
  514. this.urlFilter = this.options.filter;
  515. if (this.urlFilter instanceof RegExp) {
  516. this.urlFilter = this.urlFilter.test.bind(this.urlFilter);
  517. }
  518. this.logger = this.options.logger || createLogger(this.options.logLevel);
  519. }
  520. /**
  521. * Read the contents of a file from the specified filesystem or disk
  522. */
  523. readFile(filename) {
  524. const fs = this.fs;
  525. return new Promise((resolve, reject) => {
  526. const callback = (err, data) => {
  527. if (err) reject(err);else resolve(data);
  528. };
  529. if (fs && fs.readFile) {
  530. fs.readFile(filename, callback);
  531. } else {
  532. readFile(filename, 'utf8', callback);
  533. }
  534. });
  535. }
  536. /**
  537. * Apply critical CSS processing to the html
  538. */
  539. async process(html) {
  540. const start = process.hrtime.bigint(); // Parse the generated HTML in a DOM we can mutate
  541. const document = createDocument(html);
  542. if (this.options.additionalStylesheets.length > 0) {
  543. this.embedAdditionalStylesheet(document);
  544. } // `external:false` skips processing of external sheets
  545. if (this.options.external !== false) {
  546. const externalSheets = [].slice.call(document.querySelectorAll('link[rel="stylesheet"]'));
  547. await Promise.all(externalSheets.map(link => this.embedLinkedStylesheet(link, document)));
  548. } // go through all the style tags in the document and reduce them to only critical CSS
  549. const styles = this.getAffectedStyleTags(document);
  550. await Promise.all(styles.map(style => this.processStyle(style, document)));
  551. if (this.options.mergeStylesheets !== false && styles.length !== 0) {
  552. await this.mergeStylesheets(document);
  553. } // serialize the document back to HTML and we're done
  554. const output = serializeDocument(document);
  555. const end = process.hrtime.bigint();
  556. this.logger.info('Time ' + parseFloat(end - start) / 1000000.0);
  557. return output;
  558. }
  559. /**
  560. * Get the style tags that need processing
  561. */
  562. getAffectedStyleTags(document) {
  563. const styles = [].slice.call(document.querySelectorAll('style')); // `inline:false` skips processing of inline stylesheets
  564. if (this.options.reduceInlineStyles === false) {
  565. return styles.filter(style => style.$$external);
  566. }
  567. return styles;
  568. }
  569. async mergeStylesheets(document) {
  570. const styles = this.getAffectedStyleTags(document);
  571. if (styles.length === 0) {
  572. this.logger.warn('Merging inline stylesheets into a single <style> tag skipped, no inline stylesheets to merge');
  573. return;
  574. }
  575. const first = styles[0];
  576. let sheet = first.textContent;
  577. for (let i = 1; i < styles.length; i++) {
  578. const node = styles[i];
  579. sheet += node.textContent;
  580. node.remove();
  581. }
  582. first.textContent = sheet;
  583. }
  584. /**
  585. * Given href, find the corresponding CSS asset
  586. */
  587. async getCssAsset(href) {
  588. const outputPath = this.options.path;
  589. const publicPath = this.options.publicPath; // CHECK - the output path
  590. // path on disk (with output.publicPath removed)
  591. let normalizedPath = href.replace(/^\//, '');
  592. const pathPrefix = (publicPath || '').replace(/(^\/|\/$)/g, '') + '/';
  593. if (normalizedPath.indexOf(pathPrefix) === 0) {
  594. normalizedPath = normalizedPath.substring(pathPrefix.length).replace(/^\//, '');
  595. } // Ignore remote stylesheets
  596. if (/^https?:\/\//.test(normalizedPath) || href.startsWith('//')) {
  597. return undefined;
  598. }
  599. const filename = path.resolve(outputPath, normalizedPath);
  600. let sheet;
  601. try {
  602. sheet = await this.readFile(filename);
  603. } catch (e) {
  604. this.logger.warn(`Unable to locate stylesheet: ${filename}`);
  605. }
  606. return sheet;
  607. }
  608. checkInlineThreshold(link, style, sheet) {
  609. if (this.options.inlineThreshold && sheet.length < this.options.inlineThreshold) {
  610. const href = style.$$name;
  611. style.$$reduce = false;
  612. this.logger.info(`\u001b[32mInlined all of ${href} (${sheet.length} was below the threshold of ${this.options.inlineThreshold})\u001b[39m`);
  613. link.remove();
  614. return true;
  615. }
  616. return false;
  617. }
  618. /**
  619. * Inline the stylesheets from options.additionalStylesheets (assuming it passes `options.filter`)
  620. */
  621. async embedAdditionalStylesheet(document) {
  622. const styleSheetsIncluded = [];
  623. const sources = await Promise.all(this.options.additionalStylesheets.map(cssFile => {
  624. if (styleSheetsIncluded.includes(cssFile)) {
  625. return;
  626. }
  627. styleSheetsIncluded.push(cssFile);
  628. const style = document.createElement('style');
  629. style.$$external = true;
  630. return this.getCssAsset(cssFile, style).then(sheet => [sheet, style]);
  631. }));
  632. sources.forEach(([sheet, style]) => {
  633. if (!sheet) return;
  634. style.textContent = sheet;
  635. document.head.appendChild(style);
  636. });
  637. }
  638. /**
  639. * Inline the target stylesheet referred to by a <link rel="stylesheet"> (assuming it passes `options.filter`)
  640. */
  641. async embedLinkedStylesheet(link, document) {
  642. const href = link.getAttribute('href');
  643. const media = link.getAttribute('media');
  644. const preloadMode = this.options.preload; // skip filtered resources, or network resources if no filter is provided
  645. if (this.urlFilter ? this.urlFilter(href) : !(href || '').match(/\.css$/)) {
  646. return Promise.resolve();
  647. } // the reduced critical CSS gets injected into a new <style> tag
  648. const style = document.createElement('style');
  649. style.$$external = true;
  650. const sheet = await this.getCssAsset(href, style);
  651. if (!sheet) {
  652. return;
  653. }
  654. style.textContent = sheet;
  655. style.$$name = href;
  656. style.$$links = [link];
  657. link.parentNode.insertBefore(style, link);
  658. if (this.checkInlineThreshold(link, style, sheet)) {
  659. return;
  660. } // CSS loader is only injected for the first sheet, then this becomes an empty string
  661. let cssLoaderPreamble = "function $loadcss(u,m,l){(l=document.createElement('link')).rel='stylesheet';l.href=u;document.head.appendChild(l)}";
  662. const lazy = preloadMode === 'js-lazy';
  663. if (lazy) {
  664. cssLoaderPreamble = cssLoaderPreamble.replace('l.href', "l.media='print';l.onload=function(){l.media=m};l.href");
  665. } // Allow disabling any mutation of the stylesheet link:
  666. if (preloadMode === false) return;
  667. let noscriptFallback = false;
  668. if (preloadMode === 'body') {
  669. document.body.appendChild(link);
  670. } else {
  671. link.setAttribute('rel', 'preload');
  672. link.setAttribute('as', 'style');
  673. if (preloadMode === 'js' || preloadMode === 'js-lazy') {
  674. const script = document.createElement('script');
  675. const js = `${cssLoaderPreamble}$loadcss(${JSON.stringify(href)}${lazy ? ',' + JSON.stringify(media || 'all') : ''})`; // script.appendChild(document.createTextNode(js));
  676. script.textContent = js;
  677. link.parentNode.insertBefore(script, link.nextSibling);
  678. style.$$links.push(script);
  679. cssLoaderPreamble = '';
  680. noscriptFallback = true;
  681. } else if (preloadMode === 'media') {
  682. // @see https://github.com/filamentgroup/loadCSS/blob/af1106cfe0bf70147e22185afa7ead96c01dec48/src/loadCSS.js#L26
  683. link.setAttribute('rel', 'stylesheet');
  684. link.removeAttribute('as');
  685. link.setAttribute('media', 'print');
  686. link.setAttribute('onload', `this.media='${media || 'all'}'`);
  687. noscriptFallback = true;
  688. } else if (preloadMode === 'swap-high') {
  689. // @see http://filamentgroup.github.io/loadCSS/test/new-high.html
  690. link.setAttribute('rel', 'alternate stylesheet preload');
  691. link.setAttribute('title', 'styles');
  692. link.setAttribute('onload', `this.title='';this.rel='stylesheet'`);
  693. noscriptFallback = true;
  694. } else if (preloadMode === 'swap') {
  695. link.setAttribute('onload', "this.rel='stylesheet'");
  696. noscriptFallback = true;
  697. } else {
  698. const bodyLink = document.createElement('link');
  699. bodyLink.setAttribute('rel', 'stylesheet');
  700. if (media) bodyLink.setAttribute('media', media);
  701. bodyLink.setAttribute('href', href);
  702. document.body.appendChild(bodyLink);
  703. style.$$links.push(bodyLink);
  704. }
  705. }
  706. if (this.options.noscriptFallback !== false && noscriptFallback) {
  707. const noscript = document.createElement('noscript');
  708. const noscriptLink = document.createElement('link');
  709. noscriptLink.setAttribute('rel', 'stylesheet');
  710. noscriptLink.setAttribute('href', href);
  711. if (media) noscriptLink.setAttribute('media', media);
  712. noscript.appendChild(noscriptLink);
  713. link.parentNode.insertBefore(noscript, link.nextSibling);
  714. style.$$links.push(noscript);
  715. }
  716. }
  717. /**
  718. * Prune the source CSS files
  719. */
  720. pruneSource(style, before, sheetInverse) {
  721. // if external stylesheet would be below minimum size, just inline everything
  722. const minSize = this.options.minimumExternalSize;
  723. const name = style.$$name;
  724. if (minSize && sheetInverse.length < minSize) {
  725. this.logger.info(`\u001b[32mInlined all of ${name} (non-critical external stylesheet would have been ${sheetInverse.length}b, which was below the threshold of ${minSize})\u001b[39m`);
  726. style.textContent = before; // remove any associated external resources/loaders:
  727. if (style.$$links) {
  728. for (const link of style.$$links) {
  729. const parent = link.parentNode;
  730. if (parent) parent.removeChild(link);
  731. }
  732. }
  733. return true;
  734. }
  735. return false;
  736. }
  737. /**
  738. * Parse the stylesheet within a <style> element, then reduce it to contain only rules used by the document.
  739. */
  740. async processStyle(style, document) {
  741. if (style.$$reduce === false) return;
  742. const name = style.$$name ? style.$$name.replace(/^\//, '') : 'inline CSS';
  743. const options = this.options; // const document = style.ownerDocument;
  744. let keyframesMode = options.keyframes || 'critical'; // we also accept a boolean value for options.keyframes
  745. if (keyframesMode === true) keyframesMode = 'all';
  746. if (keyframesMode === false) keyframesMode = 'none';
  747. let sheet = style.textContent; // store a reference to the previous serialized stylesheet for reporting stats
  748. const before = sheet; // Skip empty stylesheets
  749. if (!sheet) return;
  750. const ast = parseStylesheet(sheet);
  751. const astInverse = options.pruneSource ? parseStylesheet(sheet) : null; // a string to search for font names (very loose)
  752. let criticalFonts = '';
  753. const failedSelectors = [];
  754. const criticalKeyframeNames = []; // Walk all CSS rules, marking unused rules with `.$$remove=true` for removal in the second pass.
  755. // This first pass is also used to collect font and keyframe usage used in the second pass.
  756. walkStyleRules(ast, markOnly(rule => {
  757. if (rule.type === 'rule') {
  758. // Filter the selector list down to only those match
  759. rule.filterSelectors(sel => {
  760. // Strip pseudo-elements and pseudo-classes, since we only care that their associated elements exist.
  761. // This means any selector for a pseudo-element or having a pseudo-class will be inlined if the rest of the selector matches.
  762. if (sel === ':root' || sel.match(/^::?(before|after)$/)) {
  763. return true;
  764. }
  765. sel = sel.replace(/(?<!\\)::?[a-z-]+(?![a-z-(])/gi, '').replace(/::?not\(\s*\)/g, '').trim();
  766. if (!sel) return false;
  767. try {
  768. return document.querySelector(sel) != null;
  769. } catch (e) {
  770. failedSelectors.push(sel + ' -> ' + e.message);
  771. return false;
  772. }
  773. }); // If there are no matched selectors, remove the rule:
  774. if (!rule.selector) {
  775. return false;
  776. }
  777. if (rule.nodes) {
  778. for (let i = 0; i < rule.nodes.length; i++) {
  779. const decl = rule.nodes[i]; // detect used fonts
  780. if (decl.prop && decl.prop.match(/\bfont(-family)?\b/i)) {
  781. criticalFonts += ' ' + decl.value;
  782. } // detect used keyframes
  783. if (decl.prop === 'animation' || decl.prop === 'animation-name') {
  784. // @todo: parse animation declarations and extract only the name. for now we'll do a lazy match.
  785. const names = decl.value.split(/\s+/);
  786. for (let j = 0; j < names.length; j++) {
  787. const name = names[j].trim();
  788. if (name) criticalKeyframeNames.push(name);
  789. }
  790. }
  791. }
  792. }
  793. } // keep font rules, they're handled in the second pass:
  794. if (rule.type === 'atrule' && rule.name === 'font-face') return; // If there are no remaining rules, remove the whole rule:
  795. const rules = rule.nodes && rule.nodes.filter(rule => !rule.$$remove);
  796. return !rules || rules.length !== 0;
  797. }));
  798. if (failedSelectors.length !== 0) {
  799. this.logger.warn(`${failedSelectors.length} rules skipped due to selector errors:\n ${failedSelectors.join('\n ')}`);
  800. }
  801. const shouldPreloadFonts = options.fonts === true || options.preloadFonts === true;
  802. const shouldInlineFonts = options.fonts !== false && options.inlineFonts === true;
  803. const preloadedFonts = []; // Second pass, using data picked up from the first
  804. walkStyleRulesWithReverseMirror(ast, astInverse, rule => {
  805. // remove any rules marked in the first pass
  806. if (rule.$$remove === true) return false;
  807. applyMarkedSelectors(rule); // prune @keyframes rules
  808. if (rule.type === 'atrule' && rule.name === 'keyframes') {
  809. if (keyframesMode === 'none') return false;
  810. if (keyframesMode === 'all') return true;
  811. return criticalKeyframeNames.indexOf(rule.params) !== -1;
  812. } // prune @font-face rules
  813. if (rule.type === 'atrule' && rule.name === 'font-face') {
  814. let family, src;
  815. for (let i = 0; i < rule.nodes.length; i++) {
  816. const decl = rule.nodes[i];
  817. if (decl.prop === 'src') {
  818. // @todo parse this properly and generate multiple preloads with type="font/woff2" etc
  819. src = (decl.value.match(/url\s*\(\s*(['"]?)(.+?)\1\s*\)/) || [])[2];
  820. } else if (decl.prop === 'font-family') {
  821. family = decl.value;
  822. }
  823. }
  824. if (src && shouldPreloadFonts && preloadedFonts.indexOf(src) === -1) {
  825. preloadedFonts.push(src);
  826. const preload = document.createElement('link');
  827. preload.setAttribute('rel', 'preload');
  828. preload.setAttribute('as', 'font');
  829. preload.setAttribute('crossorigin', 'anonymous');
  830. preload.setAttribute('href', src.trim());
  831. document.head.appendChild(preload);
  832. } // if we're missing info, if the font is unused, or if critical font inlining is disabled, remove the rule:
  833. if (!family || !src || criticalFonts.indexOf(family) === -1 || !shouldInlineFonts) {
  834. return false;
  835. }
  836. }
  837. });
  838. sheet = serializeStylesheet(ast, {
  839. compress: this.options.compress !== false
  840. }); // If all rules were removed, get rid of the style element entirely
  841. if (sheet.trim().length === 0) {
  842. if (style.parentNode) {
  843. style.remove();
  844. }
  845. return;
  846. }
  847. let afterText = '';
  848. let styleInlinedCompletely = false;
  849. if (options.pruneSource) {
  850. const sheetInverse = serializeStylesheet(astInverse, {
  851. compress: this.options.compress !== false
  852. });
  853. styleInlinedCompletely = this.pruneSource(style, before, sheetInverse);
  854. if (styleInlinedCompletely) {
  855. const percent = sheetInverse.length / before.length * 100;
  856. afterText = `, reducing non-inlined size ${percent | 0}% to ${prettyBytes(sheetInverse.length)}`;
  857. }
  858. } // replace the inline stylesheet with its critical'd counterpart
  859. if (!styleInlinedCompletely) {
  860. style.textContent = sheet;
  861. } // output stats
  862. const percent = sheet.length / before.length * 100 | 0;
  863. this.logger.info('\u001b[32mInlined ' + prettyBytes(sheet.length) + ' (' + percent + '% of original ' + prettyBytes(before.length) + ') of ' + name + afterText + '.\u001b[39m');
  864. }
  865. }
  866. export default Critters;