single-file-core 1.6.35 → 1.6.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/core/helper.js CHANGED
@@ -958,7 +958,7 @@ function getResourcesInfo(win, doc, element, options, data, elementHidden, compu
958
958
  data.markedElements.push(element);
959
959
  element.removeAttribute(LAZY_SRC_ATTRIBUTE_NAME);
960
960
  computedStyle = computedStyle || getComputedStyle(win, element);
961
- if (computedStyle) {
961
+ if (computedStyle && element.complete) {
962
962
  imageData.size = getSize(win, element, computedStyle);
963
963
  const boxShadow = computedStyle.getPropertyValue("box-shadow");
964
964
  const backgroundImage = computedStyle.getPropertyValue("background-image");
package/core/index.js CHANGED
@@ -342,6 +342,41 @@ class Runner {
342
342
  // ------------
343
343
  // BatchRequest
344
344
  // ------------
345
+ // what browsers allow per host over HTTP/1.1: HTTP/2 and HTTP/3 let a batch leave at once, and a rate
346
+ // limiter in front of the site counts requests (linkedin.com answered 429 to 244 of 800 icons)
347
+ const DEFAULT_MAX_PARALLEL_REQUESTS_PER_HOST = 6;
348
+
349
+ // resolves with the function that frees the slot; a data: URL has no host and never waits
350
+ function acquireHostSlot(hostSlots, resourceURL, maxParallelRequests) {
351
+ let host;
352
+ try {
353
+ host = maxParallelRequests > 0 && new URL(resourceURL).host;
354
+ } catch {
355
+ // an unparsable URL fails in the fetch, not here
356
+ }
357
+ if (!host) {
358
+ return Promise.resolve(() => { });
359
+ }
360
+ let slot = hostSlots.get(host);
361
+ if (!slot) {
362
+ slot = { active: 0, waiting: [] };
363
+ hostSlots.set(host, slot);
364
+ }
365
+ const release = () => {
366
+ const next = slot.waiting.shift();
367
+ if (next) {
368
+ next(release);
369
+ } else {
370
+ slot.active--;
371
+ }
372
+ };
373
+ if (slot.active < maxParallelRequests) {
374
+ slot.active++;
375
+ return Promise.resolve(release);
376
+ }
377
+ return new Promise(resolve => slot.waiting.push(resolve));
378
+ }
379
+
345
380
  class BatchRequest {
346
381
  constructor() {
347
382
  this.requests = new Map();
@@ -383,30 +418,38 @@ class BatchRequest {
383
418
  this.running = true;
384
419
  const resourceURLs = [...this.requests.keys()];
385
420
  let indexResource = 0;
421
+ const hostSlots = new Map();
422
+ const maxParallelRequests = options.maxParallelRequestsPerHost === undefined ? DEFAULT_MAX_PARALLEL_REQUESTS_PER_HOST : options.maxParallelRequestsPerHost;
386
423
  return Promise.all(resourceURLs.map(async requestKey => {
387
424
  const [resourceURL, asBinary, expectedType, baseURI, blockMixedContent, contentType, referrerPolicy, stylesheetURL, stylesheetReferrerPolicy] = JSON.parse(requestKey);
388
425
  const resourceRequests = this.requests.get(requestKey);
389
426
  try {
390
427
  const currentIndexResource = indexResource;
391
428
  indexResource = indexResource + 1;
392
- const content = await util.getContent(resourceURL, {
393
- asBinary,
394
- inline: !options.compressContent,
395
- expectedType,
396
- contentType,
397
- maxResourceSize: options.maxResourceSize,
398
- maxResourceSizeEnabled: options.maxResourceSizeEnabled,
399
- frameId: options.windowId,
400
- resourceReferrer: options.resourceReferrer,
401
- referrerPolicy,
402
- stylesheetURL,
403
- stylesheetReferrerPolicy,
404
- baseURI,
405
- blockMixedContent,
406
- acceptHeaders: options.acceptHeaders,
407
- networkTimeout: options.networkTimeout,
408
- manifestEntries: options.manifestEntries
409
- });
429
+ const release = await acquireHostSlot(hostSlots, resourceURL, maxParallelRequests);
430
+ let content;
431
+ try {
432
+ content = await util.getContent(resourceURL, {
433
+ asBinary,
434
+ inline: !options.compressContent,
435
+ expectedType,
436
+ contentType,
437
+ maxResourceSize: options.maxResourceSize,
438
+ maxResourceSizeEnabled: options.maxResourceSizeEnabled,
439
+ frameId: options.windowId,
440
+ resourceReferrer: options.resourceReferrer,
441
+ referrerPolicy,
442
+ stylesheetURL,
443
+ stylesheetReferrerPolicy,
444
+ baseURI,
445
+ blockMixedContent,
446
+ acceptHeaders: options.acceptHeaders,
447
+ networkTimeout: options.networkTimeout,
448
+ manifestEntries: options.manifestEntries
449
+ });
450
+ } finally {
451
+ release();
452
+ }
410
453
  if (content.manifestEntry) {
411
454
  content.manifestEntry.references = resourceRequests.length;
412
455
  }
@@ -1614,9 +1657,10 @@ class Processor {
1614
1657
  }
1615
1658
 
1616
1659
  removeUnusedStyles() {
1617
- const stats = util.minifyCSSRules(this.doc, this.stylesheets);
1660
+ const stats = util.minifyCSSRules(this.doc, this.stylesheets, this.styles);
1618
1661
  this.stats.set("processed", "CSS rules", stats.processed);
1619
1662
  this.stats.set("discarded", "CSS rules", stats.discarded);
1663
+ this.stats.set("discarded", "custom properties", stats.discardedCustomProperties);
1620
1664
  }
1621
1665
 
1622
1666
  removeUnusedFonts() {
package/core/util.js CHANGED
@@ -82,6 +82,7 @@ const MANIFEST_OUTCOME_OVERSIZED = "oversized";
82
82
  const MANIFEST_FETCHED_BY_PAGE = "page";
83
83
  const MANIFEST_FETCHED_BY_FRAME = "frame";
84
84
  const MANIFEST_HEADER_NAMES = ["date", "last-modified", "etag", "content-length", "content-encoding", "cache-control", "age", "expires", "server"];
85
+ const MIN_SERVER_ERROR_STATUS = 500;
85
86
 
86
87
  const URL = globalThis.URL;
87
88
  const DOMParser = globalThis.DOMParser;
@@ -95,7 +96,7 @@ export {
95
96
 
96
97
  function getInstance(utilOptions) {
97
98
  utilOptions = utilOptions || {};
98
- utilOptions.fetch = utilOptions.fetch || ((url, options) => globalThis.fetch(url, { ...options, cache: "force-cache", referrerPolicy: "strict-origin-when-cross-origin" }));
99
+ utilOptions.fetch = utilOptions.fetch || ((url, options) => globalThis.fetch(url, { ...options, cache: options.cache || "force-cache", referrerPolicy: "strict-origin-when-cross-origin" }));
99
100
  utilOptions.frameFetch = utilOptions.frameFetch || utilOptions.fetch;
100
101
  return {
101
102
  getDoctypeString,
@@ -176,8 +177,8 @@ function getInstance(utilOptions) {
176
177
  minifyHTML(doc, options) {
177
178
  return modules.htmlMinifier.process(doc, options);
178
179
  },
179
- minifyCSSRules(doc, stylesheets) {
180
- return modules.cssRulesMinifier.process(doc, stylesheets);
180
+ minifyCSSRules(doc, stylesheets, styles) {
181
+ return modules.cssRulesMinifier.process(doc, stylesheets, styles);
181
182
  },
182
183
  removeUnusedFonts(doc, stylesheets, styles, options) {
183
184
  return modules.fontsMinifier.process(doc, stylesheets, styles, options);
@@ -287,28 +288,32 @@ function getInstance(utilOptions) {
287
288
  resolveNetworkTimeoutPromise = resolve;
288
289
  });
289
290
  }
291
+ const fetchWithRetry = async (fetchFunction, fetchOptions) => {
292
+ let response = await Promise.race([fetchFunction(resourceURL, fetchOptions), networkTimeoutPromise]);
293
+ if (response.status >= MIN_SERVER_ERROR_STATUS) {
294
+ try {
295
+ response = await Promise.race([fetchFunction(resourceURL, { ...fetchOptions, cache: "reload" }), networkTimeoutPromise]);
296
+ // eslint-disable-next-line no-unused-vars
297
+ } catch (error) {
298
+ // the stored error stands when the network cannot do better
299
+ }
300
+ }
301
+ return response;
302
+ };
290
303
  try {
291
- const accept = (options.acceptHeaders && options.acceptHeaders[options.expectedType]) || "*/*";
304
+ const accept =(options.acceptHeaders && options.acceptHeaders[options.expectedType]) || "*/*";
305
+ const fetchOptions = { referrer: options.resourceReferrer, referrerPolicy: options.referrerPolicy || undefined, stylesheetURL: options.stylesheetURL || undefined, stylesheetReferrerPolicy: options.stylesheetReferrerPolicy || undefined, headers: { accept } };
292
306
  if (options.frameId) {
293
307
  try {
294
- response = await Promise.race([
295
- fetchFrameResource(resourceURL, { frameId: options.frameId, referrer: options.resourceReferrer, referrerPolicy: options.referrerPolicy || undefined, stylesheetURL: options.stylesheetURL || undefined, stylesheetReferrerPolicy: options.stylesheetReferrerPolicy || undefined, headers: { accept } }),
296
- networkTimeoutPromise
297
- ]);
308
+ response = await fetchWithRetry(fetchFrameResource, { frameId: options.frameId, ...fetchOptions });
298
309
  setManifestResponse(entry, response, MANIFEST_FETCHED_BY_FRAME);
299
310
  // eslint-disable-next-line no-unused-vars
300
311
  } catch (error) {
301
- response = await Promise.race([
302
- fetchResource(resourceURL, { referrer: options.resourceReferrer, referrerPolicy: options.referrerPolicy || undefined, stylesheetURL: options.stylesheetURL || undefined, stylesheetReferrerPolicy: options.stylesheetReferrerPolicy || undefined, headers: { accept } }),
303
- networkTimeoutPromise
304
- ]);
312
+ response = await fetchWithRetry(fetchResource, fetchOptions);
305
313
  setManifestResponse(entry, response, MANIFEST_FETCHED_BY_PAGE);
306
314
  }
307
315
  } else {
308
- response = await Promise.race([
309
- fetchResource(resourceURL, { referrer: options.resourceReferrer, referrerPolicy: options.referrerPolicy || undefined, stylesheetURL: options.stylesheetURL || undefined, stylesheetReferrerPolicy: options.stylesheetReferrerPolicy || undefined, headers: { accept } }),
310
- networkTimeoutPromise
311
- ]);
316
+ response = await fetchWithRetry(fetchResource, fetchOptions);
312
317
  setManifestResponse(entry, response, MANIFEST_FETCHED_BY_PAGE);
313
318
  }
314
319
  } catch (error) {
@@ -79,6 +79,8 @@ const SELECTOR_SUPPORTS_PREFIX = "selector(";
79
79
  const SELECTOR_SUPPORTS_SUFFIX = ")";
80
80
  const VENDOR_PREFIX = "-";
81
81
  const CUSTOM_PROPERTY_PREFIX = "--";
82
+ // a custom property name in a value or a prelude, up to what ends a CSS identifier or a var() argument
83
+ const CUSTOM_PROPERTY_NAME_TEST = /--[^\s,;:(){}'"!*+/\\]+/g;
82
84
  const LAYER_NAME_SEPARATOR = ".";
83
85
  const LAYER_NAME_KEY_SEPARATOR = "\u0000";
84
86
  const CONTEXT_KEY_SEPARATOR = "|";
@@ -150,10 +152,10 @@ function getValueValidity(property, value) {
150
152
  return VALIDITY_UNKNOWN;
151
153
  }
152
154
 
153
- function process(doc, stylesheets) {
155
+ function process(doc, stylesheets, styles) {
154
156
  const docContext = {
155
157
  doc,
156
- stats: { processed: 0, discarded: 0 },
158
+ stats: { processed: 0, discarded: 0, discardedCustomProperties: 0 },
157
159
  matchedElements: new Set(),
158
160
  revertLayerElements: new Set(),
159
161
  revertLayerRules: new WeakMap(),
@@ -182,6 +184,7 @@ function process(doc, stylesheets) {
182
184
  collectLayerOrder(stylesheets, docContext);
183
185
  minifyRules(stylesheets, docContext);
184
186
  computeCascade(docContext);
187
+ removeUnusedCustomProperties(stylesheets, styles, docContext);
185
188
  removeEmptyRules(stylesheets, docContext);
186
189
  return docContext.stats;
187
190
  }
@@ -1348,6 +1351,98 @@ function compareLayerNames(layersA, layersB, docContext) {
1348
1351
  return layersB.length - layersA.length;
1349
1352
  }
1350
1353
 
1354
+ // a custom property nothing reads is dead weight, and a url() in one is a fetch for nothing: linkedin.com
1355
+ // declares some 680 icons that way under :root, and the rules reading them were removed as unused above.
1356
+ // A name counts as read wherever it appears outside the property position: in the value of another
1357
+ // property, in a style attribute, in an at-rule prelude (@container style(), @property), in a stylesheet
1358
+ // of a shadow root, and transitively in the value of a custom property that is itself read
1359
+ function removeUnusedCustomProperties(stylesheets, styles, docContext) {
1360
+ const usage = { references: new Set(), customValues: new Map(), removableDeclarations: [] };
1361
+ stylesheets.forEach((stylesheetInfo, key) => {
1362
+ if (stylesheetInfo.stylesheet && hasChildNodes(stylesheetInfo.stylesheet)) {
1363
+ collectCustomPropertyUsage(stylesheetInfo.stylesheet.children, !stylesheetInfo.scoped && !key.urlNode, usage);
1364
+ }
1365
+ });
1366
+ if (styles) {
1367
+ styles.forEach(declarationList => {
1368
+ if (hasChildNodes(declarationList)) {
1369
+ collectCustomPropertyUsage(declarationList.children, false, usage);
1370
+ }
1371
+ });
1372
+ }
1373
+ // SVG presentation attributes take CSS values, var() included: linkedin.com switches its logos between
1374
+ // the light and dark variants with display="var(--svgDisplayLight)" on their groups
1375
+ docContext.doc.querySelectorAll("svg, svg *").forEach(element => {
1376
+ for (const attribute of element.attributes) {
1377
+ if (attribute.value.includes(VAR_FUNCTION_NAME + "(")) {
1378
+ collectCustomPropertyNames(attribute.value, name => usage.references.add(name));
1379
+ }
1380
+ }
1381
+ });
1382
+ const pending = [...usage.references];
1383
+ while (pending.length) {
1384
+ const values = usage.customValues.get(pending.pop());
1385
+ if (values) {
1386
+ values.forEach(value => collectCustomPropertyNames(value, name => {
1387
+ if (!usage.references.has(name)) {
1388
+ usage.references.add(name);
1389
+ pending.push(name);
1390
+ }
1391
+ }));
1392
+ }
1393
+ }
1394
+ usage.removableDeclarations.forEach(({ name, item, list }) => {
1395
+ if (!usage.references.has(name)) {
1396
+ list.remove(item);
1397
+ docContext.stats.discardedCustomProperties++;
1398
+ }
1399
+ });
1400
+ }
1401
+
1402
+ function collectCustomPropertyUsage(nodes, removable, usage) {
1403
+ for (let item = nodes.head; item; item = item.next) {
1404
+ const data = item.data;
1405
+ if (data.type === DECLARATION_TYPE) {
1406
+ const valueText = data.value.type === RAW_TYPE ? data.value.value : cssTree.generate(data.value);
1407
+ if (data.property.startsWith(CUSTOM_PROPERTY_PREFIX)) {
1408
+ const name = decodeIdentifier(data.property);
1409
+ let values = usage.customValues.get(name);
1410
+ if (!values) {
1411
+ values = [];
1412
+ usage.customValues.set(name, values);
1413
+ }
1414
+ values.push(valueText);
1415
+ if (removable) {
1416
+ usage.removableDeclarations.push({ name, item, list: nodes });
1417
+ }
1418
+ } else {
1419
+ collectCustomPropertyNames(valueText, name => usage.references.add(name));
1420
+ }
1421
+ } else if (isImportRule(data)) {
1422
+ collectCustomPropertyUsage(data.prelude.children.head.data.importedChildren, removable, usage);
1423
+ } else if (data.type === RULE_TYPE) {
1424
+ if (hasChildNodes(data.block)) {
1425
+ collectCustomPropertyUsage(data.block.children, removable, usage);
1426
+ }
1427
+ } else if (data.type === AT_RULE_TYPE) {
1428
+ if (data.prelude) {
1429
+ collectCustomPropertyNames(cssTree.generate(data.prelude), name => usage.references.add(name));
1430
+ }
1431
+ if (hasChildNodes(data.block)) {
1432
+ collectCustomPropertyUsage(data.block.children, removable && decodeName(data.name) !== KEYFRAMES_NAME, usage);
1433
+ }
1434
+ }
1435
+ }
1436
+ }
1437
+
1438
+ function collectCustomPropertyNames(text, callback) {
1439
+ if (text.includes(CUSTOM_PROPERTY_PREFIX)) {
1440
+ for (const match of text.matchAll(CUSTOM_PROPERTY_NAME_TEST)) {
1441
+ callback(decodeIdentifier(match[0]));
1442
+ }
1443
+ }
1444
+ }
1445
+
1351
1446
  function removeStylesheetEmptyRules(cssRules, docContext) {
1352
1447
  const removedRules = new Set();
1353
1448
  for (let cssRule = cssRules.head; cssRule; cssRule = cssRule.next) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "single-file-core",
3
- "version": "1.6.35",
3
+ "version": "1.6.37",
4
4
  "description": "SingleFile Core",
5
5
  "author": "Gildas Lormeau",
6
6
  "license": "AGPL-3.0-or-later",