@paulirish/trace_engine 0.0.60 → 0.0.62

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.
Files changed (302) hide show
  1. package/.tmp/tsbuildinfo/analyze-trace.d.mts.map +1 -1
  2. package/.tmp/tsbuildinfo/tsconfig.tsbuildinfo +1 -1
  3. package/analyze-inspector-issues.mjs +1 -1
  4. package/analyze-trace.mjs +1 -2
  5. package/core/platform/ArrayUtilities.d.ts +2 -0
  6. package/core/platform/ArrayUtilities.js +11 -1
  7. package/core/platform/ArrayUtilities.js.map +1 -1
  8. package/core/platform/HostRuntime.d.ts +4 -0
  9. package/core/platform/HostRuntime.js +25 -0
  10. package/core/platform/HostRuntime.js.map +1 -0
  11. package/core/platform/KeyboardUtilities.d.ts +6 -2
  12. package/core/platform/KeyboardUtilities.js.map +1 -1
  13. package/core/platform/StringUtilities.d.ts +2 -0
  14. package/core/platform/StringUtilities.js +64 -13
  15. package/core/platform/StringUtilities.js.map +1 -1
  16. package/core/platform/api/HostRuntime.d.ts +36 -0
  17. package/core/platform/api/HostRuntime.js +5 -0
  18. package/core/platform/api/HostRuntime.js.map +1 -0
  19. package/core/platform/api/api-tsconfig.json +43 -0
  20. package/core/platform/api/api.d.ts +2 -0
  21. package/core/platform/api/api.js +6 -0
  22. package/core/platform/api/api.js.map +1 -0
  23. package/core/platform/api/api_node_typecheck-tsconfig.json +48 -0
  24. package/core/platform/api/bundle-tsconfig.json +1 -0
  25. package/core/platform/api/devtools_entrypoint-bundle-typescript-tsconfig.json +48 -0
  26. package/core/platform/browser/HostRuntime.d.ts +2 -0
  27. package/core/platform/browser/HostRuntime.js +64 -0
  28. package/core/platform/browser/HostRuntime.js.map +1 -0
  29. package/core/platform/browser/browser-tsconfig.json +48 -0
  30. package/core/platform/browser/browser.d.ts +2 -0
  31. package/core/platform/browser/browser.js +6 -0
  32. package/core/platform/browser/browser.js.map +1 -0
  33. package/core/platform/browser/bundle-tsconfig.json +1 -0
  34. package/core/platform/browser/devtools_entrypoint-bundle-typescript-tsconfig.json +48 -0
  35. package/core/platform/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  36. package/core/platform/node/HostRuntime.d.ts +2 -0
  37. package/core/platform/node/HostRuntime.js +73 -0
  38. package/core/platform/node/HostRuntime.js.map +1 -0
  39. package/core/platform/node/bundle-tsconfig.json +1 -0
  40. package/core/platform/node/devtools_entrypoint-bundle-typescript-tsconfig.json +48 -0
  41. package/core/platform/node/node-tsconfig.json +52 -0
  42. package/core/platform/node/node.d.ts +2 -0
  43. package/core/platform/node/node.js +6 -0
  44. package/core/platform/node/node.js.map +1 -0
  45. package/core/platform/platform-tsconfig.json +17 -5
  46. package/core/platform/platform.d.ts +2 -2
  47. package/core/platform/platform.js +2 -2
  48. package/core/platform/platform.js.map +1 -1
  49. package/core/platform/platform_node_typecheck-tsconfig.json +74 -0
  50. package/generated/protocol.d.ts +1517 -592
  51. package/locales/af.json +83 -38
  52. package/locales/am.json +83 -38
  53. package/locales/ar.json +86 -41
  54. package/locales/as.json +83 -38
  55. package/locales/az.json +83 -38
  56. package/locales/be.json +81 -36
  57. package/locales/bg.json +81 -36
  58. package/locales/bn.json +83 -38
  59. package/locales/bs.json +82 -37
  60. package/locales/ca.json +81 -36
  61. package/locales/cs.json +81 -36
  62. package/locales/cy.json +83 -38
  63. package/locales/da.json +83 -38
  64. package/locales/de.json +81 -36
  65. package/locales/el.json +82 -37
  66. package/locales/en-GB.json +83 -38
  67. package/locales/en-US.json +104 -35
  68. package/locales/en-XL.json +104 -35
  69. package/locales/es-419.json +81 -36
  70. package/locales/es.json +82 -37
  71. package/locales/et.json +83 -38
  72. package/locales/eu.json +81 -36
  73. package/locales/fa.json +84 -39
  74. package/locales/fi.json +81 -36
  75. package/locales/fil.json +83 -38
  76. package/locales/fr-CA.json +82 -37
  77. package/locales/fr.json +168 -123
  78. package/locales/gl.json +82 -37
  79. package/locales/gu.json +82 -37
  80. package/locales/he.json +96 -51
  81. package/locales/hi.json +82 -37
  82. package/locales/hr.json +81 -36
  83. package/locales/hu.json +82 -37
  84. package/locales/hy.json +82 -37
  85. package/locales/id.json +83 -38
  86. package/locales/is.json +82 -37
  87. package/locales/it.json +81 -36
  88. package/locales/ja.json +81 -36
  89. package/locales/ka.json +83 -38
  90. package/locales/kk.json +81 -36
  91. package/locales/km.json +83 -38
  92. package/locales/kn.json +82 -37
  93. package/locales/ko.json +82 -37
  94. package/locales/ky.json +81 -36
  95. package/locales/lo.json +82 -37
  96. package/locales/lt.json +81 -36
  97. package/locales/lv.json +81 -36
  98. package/locales/mk.json +84 -39
  99. package/locales/ml.json +82 -37
  100. package/locales/mn.json +82 -37
  101. package/locales/mr.json +83 -38
  102. package/locales/ms.json +81 -36
  103. package/locales/my.json +82 -37
  104. package/locales/ne.json +82 -37
  105. package/locales/nl.json +82 -37
  106. package/locales/no.json +81 -36
  107. package/locales/or.json +81 -36
  108. package/locales/pa.json +81 -36
  109. package/locales/pl.json +81 -36
  110. package/locales/pt-PT.json +81 -36
  111. package/locales/pt.json +83 -38
  112. package/locales/ro.json +82 -37
  113. package/locales/ru.json +81 -36
  114. package/locales/si.json +81 -36
  115. package/locales/sk.json +81 -36
  116. package/locales/sl.json +81 -36
  117. package/locales/sq.json +82 -37
  118. package/locales/sr-Latn.json +82 -37
  119. package/locales/sr.json +82 -37
  120. package/locales/sv.json +84 -39
  121. package/locales/sw.json +83 -38
  122. package/locales/ta.json +82 -37
  123. package/locales/te.json +82 -37
  124. package/locales/th.json +82 -37
  125. package/locales/tr.json +81 -36
  126. package/locales/uk.json +81 -36
  127. package/locales/ur.json +82 -37
  128. package/locales/uz.json +82 -37
  129. package/locales/vi.json +83 -38
  130. package/locales/zh-HK.json +81 -36
  131. package/locales/zh-TW.json +84 -39
  132. package/locales/zh.json +84 -39
  133. package/locales/zu.json +82 -37
  134. package/models/cpu_profile/CPUProfileDataModel.d.ts +9 -0
  135. package/models/cpu_profile/CPUProfileDataModel.js +9 -7
  136. package/models/cpu_profile/CPUProfileDataModel.js.map +1 -1
  137. package/models/cpu_profile/ProfileTreeModel.d.ts +3 -2
  138. package/models/cpu_profile/ProfileTreeModel.js +6 -7
  139. package/models/cpu_profile/ProfileTreeModel.js.map +1 -1
  140. package/models/cpu_profile/cpu_profile-tsconfig.json +4 -3
  141. package/models/cpu_profile/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  142. package/models/trace/EntityMapper.d.ts +1 -0
  143. package/models/trace/EntityMapper.js +10 -0
  144. package/models/trace/EntityMapper.js.map +1 -1
  145. package/models/trace/EventsSerializer.js +10 -2
  146. package/models/trace/EventsSerializer.js.map +1 -1
  147. package/models/trace/LanternComputationData.d.ts +1 -1
  148. package/models/trace/LanternComputationData.js +3 -8
  149. package/models/trace/LanternComputationData.js.map +1 -1
  150. package/models/trace/ModelImpl.d.ts +1 -0
  151. package/models/trace/ModelImpl.js +9 -6
  152. package/models/trace/ModelImpl.js.map +1 -1
  153. package/models/trace/Processor.js +23 -23
  154. package/models/trace/Processor.js.map +1 -1
  155. package/models/trace/Styles.js +13 -5
  156. package/models/trace/Styles.js.map +1 -1
  157. package/models/trace/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  158. package/models/trace/extras/Initiators.d.ts +12 -0
  159. package/models/trace/extras/Initiators.js +47 -0
  160. package/models/trace/extras/Initiators.js.map +1 -0
  161. package/models/trace/extras/TraceTree.js +13 -5
  162. package/models/trace/extras/TraceTree.js.map +1 -1
  163. package/models/trace/extras/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  164. package/models/trace/extras/extras-tsconfig.json +11 -3
  165. package/models/trace/extras/extras.d.ts +0 -3979
  166. package/models/trace/extras/extras.js +0 -3979
  167. package/models/trace/extras/extras.js.map +1 -1
  168. package/models/trace/handlers/LargestImagePaintHandler.js +2 -2
  169. package/models/trace/handlers/LargestImagePaintHandler.js.map +1 -1
  170. package/models/trace/handlers/LayoutShiftsHandler.js +1 -1
  171. package/models/trace/handlers/LayoutShiftsHandler.js.map +1 -1
  172. package/models/trace/handlers/MetaHandler.d.ts +12 -1
  173. package/models/trace/handlers/MetaHandler.js +10 -1
  174. package/models/trace/handlers/MetaHandler.js.map +1 -1
  175. package/models/trace/handlers/NetworkRequestsHandler.d.ts +8 -1
  176. package/models/trace/handlers/NetworkRequestsHandler.js +22 -4
  177. package/models/trace/handlers/NetworkRequestsHandler.js.map +1 -1
  178. package/models/trace/handlers/PageLoadMetricsHandler.d.ts +13 -3
  179. package/models/trace/handlers/PageLoadMetricsHandler.js +71 -27
  180. package/models/trace/handlers/PageLoadMetricsHandler.js.map +1 -1
  181. package/models/trace/handlers/SamplesHandler.js +59 -6
  182. package/models/trace/handlers/SamplesHandler.js.map +1 -1
  183. package/models/trace/handlers/ScriptsHandler.js +24 -0
  184. package/models/trace/handlers/ScriptsHandler.js.map +1 -1
  185. package/models/trace/handlers/UserTimingsHandler.d.ts +1 -1
  186. package/models/trace/handlers/UserTimingsHandler.js +1 -1
  187. package/models/trace/handlers/UserTimingsHandler.js.map +1 -1
  188. package/models/trace/handlers/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  189. package/models/trace/handlers/handlers-tsconfig.json +13 -3
  190. package/models/trace/helpers/Network.js +1 -1
  191. package/models/trace/helpers/Network.js.map +1 -1
  192. package/models/trace/helpers/SamplesIntegrator.js +1 -8
  193. package/models/trace/helpers/SamplesIntegrator.js.map +1 -1
  194. package/models/trace/helpers/Timing.d.ts +1 -1
  195. package/models/trace/helpers/Timing.js +9 -2
  196. package/models/trace/helpers/Timing.js.map +1 -1
  197. package/models/trace/helpers/Trace.d.ts +1 -0
  198. package/models/trace/helpers/Trace.js +12 -5
  199. package/models/trace/helpers/Trace.js.map +1 -1
  200. package/models/trace/helpers/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  201. package/models/trace/helpers/helpers-tsconfig.json +7 -3
  202. package/models/trace/insights/CLSCulprits.d.ts +1 -1
  203. package/models/trace/insights/CLSCulprits.js +2 -1
  204. package/models/trace/insights/CLSCulprits.js.map +1 -1
  205. package/models/trace/insights/Cache.d.ts +1 -1
  206. package/models/trace/insights/Cache.js +2 -1
  207. package/models/trace/insights/Cache.js.map +1 -1
  208. package/models/trace/insights/CharacterSet.d.ts +49 -0
  209. package/models/trace/insights/CharacterSet.js +132 -0
  210. package/models/trace/insights/CharacterSet.js.map +1 -0
  211. package/models/trace/insights/Common.d.ts +2 -2
  212. package/models/trace/insights/Common.js +1 -6
  213. package/models/trace/insights/Common.js.map +1 -1
  214. package/models/trace/insights/DOMSize.d.ts +1 -1
  215. package/models/trace/insights/DOMSize.js +2 -1
  216. package/models/trace/insights/DOMSize.js.map +1 -1
  217. package/models/trace/insights/DocumentLatency.d.ts +1 -1
  218. package/models/trace/insights/DocumentLatency.js +2 -1
  219. package/models/trace/insights/DocumentLatency.js.map +1 -1
  220. package/models/trace/insights/DuplicatedJavaScript.d.ts +1 -1
  221. package/models/trace/insights/DuplicatedJavaScript.js +2 -1
  222. package/models/trace/insights/DuplicatedJavaScript.js.map +1 -1
  223. package/models/trace/insights/FontDisplay.d.ts +1 -1
  224. package/models/trace/insights/FontDisplay.js +2 -1
  225. package/models/trace/insights/FontDisplay.js.map +1 -1
  226. package/models/trace/insights/ForcedReflow.d.ts +2 -2
  227. package/models/trace/insights/ForcedReflow.js +3 -2
  228. package/models/trace/insights/ForcedReflow.js.map +1 -1
  229. package/models/trace/insights/INPBreakdown.d.ts +1 -1
  230. package/models/trace/insights/INPBreakdown.js +2 -1
  231. package/models/trace/insights/INPBreakdown.js.map +1 -1
  232. package/models/trace/insights/ImageDelivery.d.ts +1 -1
  233. package/models/trace/insights/ImageDelivery.js +2 -1
  234. package/models/trace/insights/ImageDelivery.js.map +1 -1
  235. package/models/trace/insights/LCPBreakdown.d.ts +2 -2
  236. package/models/trace/insights/LCPBreakdown.js +4 -3
  237. package/models/trace/insights/LCPBreakdown.js.map +1 -1
  238. package/models/trace/insights/LCPDiscovery.d.ts +8 -4
  239. package/models/trace/insights/LCPDiscovery.js +18 -11
  240. package/models/trace/insights/LCPDiscovery.js.map +1 -1
  241. package/models/trace/insights/LegacyJavaScript.d.ts +1 -1
  242. package/models/trace/insights/LegacyJavaScript.js +2 -1
  243. package/models/trace/insights/LegacyJavaScript.js.map +1 -1
  244. package/models/trace/insights/Models.d.ts +1 -0
  245. package/models/trace/insights/Models.js +1 -0
  246. package/models/trace/insights/Models.js.map +1 -1
  247. package/models/trace/insights/ModernHTTP.d.ts +1 -1
  248. package/models/trace/insights/ModernHTTP.js +2 -1
  249. package/models/trace/insights/ModernHTTP.js.map +1 -1
  250. package/models/trace/insights/NetworkDependencyTree.d.ts +1 -1
  251. package/models/trace/insights/NetworkDependencyTree.js +6 -4
  252. package/models/trace/insights/NetworkDependencyTree.js.map +1 -1
  253. package/models/trace/insights/RenderBlocking.d.ts +2 -2
  254. package/models/trace/insights/RenderBlocking.js +8 -7
  255. package/models/trace/insights/RenderBlocking.js.map +1 -1
  256. package/models/trace/insights/SlowCSSSelector.d.ts +1 -1
  257. package/models/trace/insights/SlowCSSSelector.js +2 -1
  258. package/models/trace/insights/SlowCSSSelector.js.map +1 -1
  259. package/models/trace/insights/ThirdParties.js +2 -1
  260. package/models/trace/insights/ThirdParties.js.map +1 -1
  261. package/models/trace/insights/Viewport.d.ts +1 -1
  262. package/models/trace/insights/Viewport.js +2 -1
  263. package/models/trace/insights/Viewport.js.map +1 -1
  264. package/models/trace/insights/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  265. package/models/trace/insights/insights-tsconfig.json +26 -3
  266. package/models/trace/insights/types.d.ts +17 -6
  267. package/models/trace/insights/types.js +1 -0
  268. package/models/trace/insights/types.js.map +1 -1
  269. package/models/trace/lantern/core/core-tsconfig.json +4 -3
  270. package/models/trace/lantern/core/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  271. package/models/trace/lantern/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  272. package/models/trace/lantern/graph/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  273. package/models/trace/lantern/graph/graph-tsconfig.json +4 -3
  274. package/models/trace/lantern/lantern-tsconfig.json +4 -3
  275. package/models/trace/lantern/metrics/FirstContentfulPaint.js +6 -6
  276. package/models/trace/lantern/metrics/FirstContentfulPaint.js.map +1 -1
  277. package/models/trace/lantern/metrics/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  278. package/models/trace/lantern/metrics/metrics-tsconfig.json +4 -3
  279. package/models/trace/lantern/simulation/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  280. package/models/trace/lantern/simulation/simulation-tsconfig.json +4 -3
  281. package/models/trace/lantern/types/Lantern.d.ts +7 -7
  282. package/models/trace/lantern/types/Lantern.js.map +1 -1
  283. package/models/trace/lantern/types/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  284. package/models/trace/lantern/types/types-tsconfig.json +4 -3
  285. package/models/trace/trace-tsconfig.json +7 -3
  286. package/models/trace/types/Configuration.d.ts +1 -4
  287. package/models/trace/types/Configuration.js +0 -1
  288. package/models/trace/types/Configuration.js.map +1 -1
  289. package/models/trace/types/File.d.ts +8 -0
  290. package/models/trace/types/File.js.map +1 -1
  291. package/models/trace/types/TraceEvents.d.ts +97 -15
  292. package/models/trace/types/TraceEvents.js +44 -11
  293. package/models/trace/types/TraceEvents.js.map +1 -1
  294. package/models/trace/types/devtools_entrypoint-bundle-typescript-tsconfig.json +4 -3
  295. package/models/trace/types/types-tsconfig.json +10 -3
  296. package/package.json +1 -1
  297. package/test/test-trace-engine.mjs +8 -9
  298. package/.tmp/tsbuildinfo/models/trace/extras/polyfills.d.ts +0 -4
  299. package/.tmp/tsbuildinfo/models/trace/extras/polyfills.d.ts.map +0 -1
  300. package/core/platform/DOMUtilities.d.ts +0 -16
  301. package/core/platform/DOMUtilities.js +0 -123
  302. package/core/platform/DOMUtilities.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ImageDelivery.js","sourceRoot":"","sources":["../../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AAC,CAAC;IACnF,CAAC;IAED,0CAA0C;IAC1C,iBAAiB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QAC9B,IAAI,CAAC,CAAC,WAAW,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;YACpC,OAAO,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC,WAAW,CAAC;QACvC,CAAC;QAED,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,iBAAiB,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC;IACvF,CAAC,CAAC,CAAC;IAEH,OAAO,QAAQ,CAAC;QACd,iBAAiB;QACjB,aAAa,EAAE,2BAA2B,CAAC,sBAAsB,EAAE,OAAO,CAAC;QAC3E,WAAW,EAAE,iBAAiB,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,KAAK,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC;KAClF,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,OAA6C;IACnF,OAAO;QACL,IAAI,EAAE,eAAe;QACrB,KAAK,EAAE,OAAO;QACd,aAAa,EAAE,OAAO;KACvB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,KAAgC;IAC7D,OAAO,KAAK,CAAC,iBAAiB,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,uBAAuB,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;AACtF,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as i18n from '../../../core/i18n/i18n.js';\nimport type * as Platform from '../../../core/platform/platform.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport type * as Types from '../types/types.js';\n\nimport {metricSavingsForWastedBytes} from './Common.js';\nimport {\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n type PartialInsightModel,\n} from './types.js';\n\nexport const UIStrings = {\n /**\n * @description Title of an insight that recommends ways to reduce the size of images downloaded and used on the page.\n */\n title: 'Improve image delivery',\n /**\n * @description Description of an insight that recommends ways to reduce the size of images downloaded and used on the page.\n */\n description:\n 'Reducing the download time of images can improve the perceived load time of the page and LCP. [Learn more about optimizing image size](https://developer.chrome.com/docs/lighthouse/performance/uses-optimized-images/)',\n /**\n * @description Message displayed in a chip explaining that an image file size is large for the # of pixels it has and recommends possible adjustments to improve the image size.\n */\n useCompression: 'Increasing the image compression factor could improve this image\\'s download size.',\n /**\n * @description Message displayed in a chip explaining that an image file size is large for the # of pixels it has and recommends possible adjustments to improve the image size.\n */\n useModernFormat:\n 'Using a modern image format (WebP, AVIF) or increasing the image compression could improve this image\\'s download size.',\n /**\n * @description Message displayed in a chip advising the user to use video formats instead of GIFs because videos generally have smaller file sizes.\n */\n useVideoFormat: 'Using video formats instead of GIFs can improve the download size of animated content.',\n /**\n * @description Message displayed in a chip explaining that an image was displayed on the page with dimensions much smaller than the image file dimensions.\n * @example {1000x500} PH1\n * @example {100x50} PH2\n */\n useResponsiveSize:\n 'This image file is larger than it needs to be ({PH1}) for its displayed dimensions ({PH2}). Use responsive images to reduce the image download size.',\n /**\n * @description Column header for a table column containing network requests for images which can improve their file size (e.g. use a different format, increase compression, etc).\n */\n optimizeFile: 'Optimize file size',\n /**\n * @description Table row value representing the remaining items not shown in the table due to size constraints. This row will always represent at least 2 items.\n * @example {5} PH1\n */\n others: '{PH1} others',\n /**\n * @description Text status indicating that no potential optimizations were found for any image file\n */\n noOptimizableImages: 'No optimizable images',\n /**\n * @description Text describing the estimated number of bytes that an image file optimization can save. This text is appended to another block of text describing the image optimization in more detail. \"Est\" means \"Estimated\".\n * @example {Use the correct image dimensions to reduce the image file size.} PH1\n * @example {50 MB} PH2\n */\n estimatedSavings: '{PH1} (Est {PH2})',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/ImageDelivery.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\n/**\n * Even JPEGs with lots of detail can usually be compressed down to <1 byte per pixel\n * Using 4:2:2 subsampling already gets an uncompressed bitmap to 2 bytes per pixel.\n * The compression ratio for JPEG is usually somewhere around 10:1 depending on content, so\n * 8:1 is a reasonable expectation for web content which is 1.5MB for a 6MP image.\n *\n * WebP usually gives ~20% additional savings on top of that, so we will assume 10:1 for WebP.\n * This is quite pessimistic as their study shows a photographic compression ratio of ~29:1.\n * https://developers.google.com/speed/webp/docs/webp_lossless_alpha_study#results\n *\n * AVIF usually gives ~20% additional savings on top of WebP, so we will use 12:1 for AVIF.\n * This is quite pessimistic as Netflix study shows a photographic compression ratio of ~40:1\n * (0.4 *bits* per pixel at SSIM 0.97).\n * https://netflixtechblog.com/avif-for-next-generation-image-coding-b1d75675fe4\n */\nconst TARGET_BYTES_PER_PIXEL_AVIF = 2 * 1 / 12;\n\n/**\n * If GIFs are above this size, we'll flag them\n * See https://github.com/GoogleChrome/lighthouse/pull/4885#discussion_r178406623 and https://github.com/GoogleChrome/lighthouse/issues/4696#issuecomment-370979920\n */\nconst GIF_SIZE_THRESHOLD = 100 * 1024;\n\nconst BYTE_SAVINGS_THRESHOLD = 4096;\n\n// Ignore up to 12KB of waste for responsive images if an effort was made with breakpoints.\nconst BYTE_SAVINGS_THRESHOLD_RESPONSIVE_BREAKPOINTS = 12288;\n\nexport enum ImageOptimizationType {\n ADJUST_COMPRESSION = 'ADJUST_COMPRESSION',\n MODERN_FORMAT_OR_COMPRESSION = 'MODERN_FORMAT_OR_COMPRESSION',\n VIDEO_FORMAT = 'VIDEO_FORMAT',\n RESPONSIVE_SIZE = 'RESPONSIVE_SIZE',\n}\n\nexport type ImageOptimization = {\n type: Exclude<ImageOptimizationType, ImageOptimizationType.RESPONSIVE_SIZE>,\n byteSavings: number,\n}|{\n type: ImageOptimizationType.RESPONSIVE_SIZE,\n byteSavings: number,\n fileDimensions: {width: number, height: number},\n displayDimensions: {width: number, height: number},\n};\n\nexport interface OptimizableImage {\n request: Types.Events.SyntheticNetworkRequest;\n optimizations: ImageOptimization[];\n byteSavings: number;\n /**\n * If the an image resource has multiple `PaintImage`s, we compare its intrinsic size to the largest of the displayed sizes.\n *\n * It is theoretically possible for `PaintImage` events with the same URL to have different intrinsic sizes.\n * However, this should be rare because it requires serving different images from the same URL.\n */\n largestImagePaint: Types.Events.PaintImage;\n}\n\nexport type ImageDeliveryInsightModel = InsightModel<typeof UIStrings, {\n /** Sorted by potential byte savings, then by size of image. */\n optimizableImages: OptimizableImage[],\n wastedBytes: number,\n}>;\n\nexport function isImageDeliveryInsight(model: InsightModel): model is ImageDeliveryInsightModel {\n return model.insightKey === 'ImageDelivery';\n}\n\nexport function getOptimizationMessage(optimization: ImageOptimization): Platform.UIString.LocalizedString {\n switch (optimization.type) {\n case ImageOptimizationType.ADJUST_COMPRESSION:\n return i18nString(UIStrings.useCompression);\n case ImageOptimizationType.MODERN_FORMAT_OR_COMPRESSION:\n return i18nString(UIStrings.useModernFormat);\n case ImageOptimizationType.VIDEO_FORMAT:\n return i18nString(UIStrings.useVideoFormat);\n case ImageOptimizationType.RESPONSIVE_SIZE:\n return i18nString(UIStrings.useResponsiveSize, {\n PH1: `${optimization.fileDimensions.width}x${optimization.fileDimensions.height}`,\n PH2: `${optimization.displayDimensions.width}x${optimization.displayDimensions.height}`,\n });\n }\n}\n\nexport function getOptimizationMessageWithBytes(optimization: ImageOptimization): Platform.UIString.LocalizedString {\n const byteSavingsText = i18n.ByteUtilities.bytesToString(optimization.byteSavings);\n const optimizationMessage = getOptimizationMessage(optimization);\n return i18nString(UIStrings.estimatedSavings, {PH1: optimizationMessage, PH2: byteSavingsText});\n}\n\nfunction finalize(partialModel: PartialInsightModel<ImageDeliveryInsightModel>): ImageDeliveryInsightModel {\n return {\n insightKey: InsightKeys.IMAGE_DELIVERY,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.LCP,\n state: partialModel.optimizableImages.length > 0 ? 'fail' : 'pass',\n ...partialModel,\n relatedEvents: new Map(partialModel.optimizableImages.map(\n image => [image.request, image.optimizations.map(getOptimizationMessageWithBytes)])),\n };\n}\n\n/**\n * Calculate rough savings percentage based on 1000 real gifs transcoded to video\n * https://github.com/GoogleChrome/lighthouse/issues/4696#issuecomment-380296510\n */\nfunction estimateGIFPercentSavings(request: Types.Events.SyntheticNetworkRequest): number {\n return Math.round((29.1 * Math.log10(request.args.data.decodedBodyLength) - 100.7)) / 100;\n}\n\nfunction getDisplayedSize(\n data: Handlers.Types.HandlerData, paintImage: Types.Events.PaintImage): {width: number, height: number} {\n // Note: for traces made prior to metadata.hostDPR (which means no data in\n // paintEventToCorrectedDisplaySize), the displayed size unexpectedly ignores any\n // emulated DPR and so the results may be very misleading.\n return data.ImagePainting.paintEventToCorrectedDisplaySize.get(paintImage) ?? {\n width: paintImage.args.data.width,\n height: paintImage.args.data.height,\n };\n}\n\nfunction getPixelCounts(data: Handlers.Types.HandlerData, paintImage: Types.Events.PaintImage):\n {displayedPixels: number, filePixels: number} {\n const {width, height} = getDisplayedSize(data, paintImage);\n return {\n filePixels: paintImage.args.data.srcWidth * paintImage.args.data.srcHeight,\n displayedPixels: width * height,\n };\n}\n\nexport function generateInsight(\n data: Handlers.Types.HandlerData, context: InsightSetContext): ImageDeliveryInsightModel {\n const isWithinContext = (event: Types.Events.Event): boolean => Helpers.Timing.eventIsInBounds(event, context.bounds);\n\n const contextRequests = data.NetworkRequests.byTime.filter(isWithinContext);\n\n const optimizableImages: OptimizableImage[] = [];\n for (const request of contextRequests) {\n if (request.args.data.resourceType !== 'Image') {\n continue;\n }\n\n if (request.args.data.mimeType === 'image/svg+xml') {\n continue;\n }\n\n // If the request was redirected, the image paints will have the pre-redirect URL.\n const url = request.args.data.redirects[0]?.url ?? request.args.data.url;\n const imagePaints = data.ImagePainting.paintImageEventForUrl.get(url)?.filter(isWithinContext);\n\n // This will filter out things like preloaded image requests where an image file is downloaded\n // but never rendered on the page.\n if (!imagePaints?.length) {\n continue;\n }\n\n const largestImagePaint = imagePaints.reduce((prev, curr) => {\n const prevPixels = getPixelCounts(data, prev).displayedPixels;\n const currPixels = getPixelCounts(data, curr).displayedPixels;\n return prevPixels > currPixels ? prev : curr;\n });\n\n const {\n filePixels: imageFilePixels,\n displayedPixels: largestImageDisplayPixels,\n } = getPixelCounts(data, largestImagePaint);\n\n // Decoded body length is almost always the right one to be using because of the below:\n // `encodedDataLength = decodedBodyLength + headers`.\n // HOWEVER, there are some cases where an image is compressed again over the network and transfer size\n // is smaller (see https://github.com/GoogleChrome/lighthouse/pull/4968).\n // Use the min of the two numbers to be safe.\n const imageBytes = Math.min(request.args.data.decodedBodyLength, request.args.data.encodedDataLength);\n\n const bytesPerPixel = imageBytes / imageFilePixels;\n\n let optimizations: ImageOptimization[] = [];\n if (request.args.data.mimeType === 'image/gif') {\n if (imageBytes > GIF_SIZE_THRESHOLD) {\n const percentSavings = estimateGIFPercentSavings(request);\n const byteSavings = Math.round(imageBytes * percentSavings);\n optimizations.push({type: ImageOptimizationType.VIDEO_FORMAT, byteSavings});\n }\n } else if (bytesPerPixel > TARGET_BYTES_PER_PIXEL_AVIF) {\n const idealAvifImageSize = Math.round(TARGET_BYTES_PER_PIXEL_AVIF * imageFilePixels);\n const byteSavings = imageBytes - idealAvifImageSize;\n if (request.args.data.mimeType !== 'image/webp' && request.args.data.mimeType !== 'image/avif') {\n optimizations.push({type: ImageOptimizationType.MODERN_FORMAT_OR_COMPRESSION, byteSavings});\n } else {\n optimizations.push({type: ImageOptimizationType.ADJUST_COMPRESSION, byteSavings});\n }\n }\n\n // At this point (before looking at image size), the # of optimizations should only ever be 1 or 0\n // Math.max handles both cases correctly, and is defensive against future patches that would add\n // more than 1 format-specific optimization by this point.\n const imageByteSavingsFromFormat = Math.max(0, ...optimizations.map(o => o.byteSavings));\n let imageByteSavings = imageByteSavingsFromFormat;\n\n const wastedPixelRatio = 1 - (largestImageDisplayPixels / imageFilePixels);\n\n // Ignore CSS images because it's difficult to determine what is a spritesheet,\n // and the reward-to-effort ratio for responsive CSS images is quite low https://css-tricks.com/responsive-images-css/.\n if (wastedPixelRatio > 0 && !largestImagePaint.args.data.isCSS) {\n const byteSavings = Math.round(wastedPixelRatio * imageBytes);\n\n const hadBreakpoints = largestImagePaint.args.data.isPicture || largestImagePaint.args.data.srcsetAttribute;\n if (!hadBreakpoints || byteSavings > BYTE_SAVINGS_THRESHOLD_RESPONSIVE_BREAKPOINTS) {\n // This will compound the byte savings from any potential format changes with the image size\n // optimization added here.\n imageByteSavings += Math.round(wastedPixelRatio * (imageBytes - imageByteSavingsFromFormat));\n\n const {width, height} = getDisplayedSize(data, largestImagePaint);\n\n optimizations.push({\n type: ImageOptimizationType.RESPONSIVE_SIZE,\n byteSavings,\n fileDimensions: {\n width: Math.round(largestImagePaint.args.data.srcWidth),\n height: Math.round(largestImagePaint.args.data.srcHeight),\n },\n displayDimensions: {\n width: Math.round(width),\n height: Math.round(height),\n },\n });\n }\n }\n\n optimizations = optimizations.filter(optimization => optimization.byteSavings > BYTE_SAVINGS_THRESHOLD);\n\n if (optimizations.length > 0) {\n optimizableImages.push({\n request,\n largestImagePaint,\n optimizations,\n byteSavings: imageByteSavings,\n });\n }\n }\n\n const wastedBytesByRequestId = new Map<string, number>();\n for (const image of optimizableImages) {\n wastedBytesByRequestId.set(image.request.args.data.requestId, image.byteSavings);\n }\n\n // Sort by savings, then by size of image.\n optimizableImages.sort((a, b) => {\n if (b.byteSavings !== a.byteSavings) {\n return b.byteSavings - a.byteSavings;\n }\n\n return b.request.args.data.decodedBodyLength - a.request.args.data.decodedBodyLength;\n });\n\n return finalize({\n optimizableImages,\n metricSavings: metricSavingsForWastedBytes(wastedBytesByRequestId, context),\n wastedBytes: optimizableImages.reduce((total, img) => total + img.byteSavings, 0),\n });\n}\n\nexport function createOverlayForRequest(request: Types.Events.SyntheticNetworkRequest): Types.Overlays.EntryOutline {\n return {\n type: 'ENTRY_OUTLINE',\n entry: request,\n outlineReason: 'ERROR',\n };\n}\n\nexport function createOverlays(model: ImageDeliveryInsightModel): Types.Overlays.Overlay[] {\n return model.optimizableImages.map(image => createOverlayForRequest(image.request));\n}\n"]}
1
+ {"version":3,"file":"ImageDelivery.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/ImageDelivery.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AAGnD,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AAGjD,OAAO,EAAC,2BAA2B,EAAC,MAAM,aAAa,CAAC;AACxD,OAAO,EACL,eAAe,EACf,WAAW,GAIZ,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,wBAAwB;IAC/B;;OAEG;IACH,WAAW,EACP,+MAA+M;IACnN;;OAEG;IACH,cAAc,EAAE,oFAAoF;IACpG;;OAEG;IACH,eAAe,EACX,yHAAyH;IAC7H;;OAEG;IACH,cAAc,EAAE,wFAAwF;IACxG;;;;OAIG;IACH,iBAAiB,EACb,sJAAsJ;IAC1J;;OAEG;IACH,YAAY,EAAE,oBAAoB;IAClC;;;OAGG;IACH,MAAM,EAAE,cAAc;IACtB;;OAEG;IACH,mBAAmB,EAAE,uBAAuB;IAC5C;;;;OAIG;IACH,gBAAgB,EAAE,mBAAmB;CAC7B,CAAC;AAEX,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,wCAAwC,EAAE,SAAS,CAAC,CAAC;AAC9F,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAE7E;;;;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AAK,CAAC,OAAO,CAAC,CAAC,CAAC;AACtF,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as i18n from '../../../core/i18n/i18n.js';\nimport type * as Platform from '../../../core/platform/platform.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport type * as Types from '../types/types.js';\n\nimport {metricSavingsForWastedBytes} from './Common.js';\nimport {\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n type PartialInsightModel,\n} from './types.js';\n\nexport const UIStrings = {\n /**\n * @description Title of an insight that recommends ways to reduce the size of images downloaded and used on the page.\n */\n title: 'Improve image delivery',\n /**\n * @description Description of an insight that recommends ways to reduce the size of images downloaded and used on the page.\n */\n description:\n 'Reducing the download time of images can improve the perceived load time of the page and LCP. [Learn more about optimizing image size](https://developer.chrome.com/docs/performance/insights/image-delivery)',\n /**\n * @description Message displayed in a chip explaining that an image file size is large for the # of pixels it has and recommends possible adjustments to improve the image size.\n */\n useCompression: 'Increasing the image compression factor could improve this image\\'s download size.',\n /**\n * @description Message displayed in a chip explaining that an image file size is large for the # of pixels it has and recommends possible adjustments to improve the image size.\n */\n useModernFormat:\n 'Using a modern image format (WebP, AVIF) or increasing the image compression could improve this image\\'s download size.',\n /**\n * @description Message displayed in a chip advising the user to use video formats instead of GIFs because videos generally have smaller file sizes.\n */\n useVideoFormat: 'Using video formats instead of GIFs can improve the download size of animated content.',\n /**\n * @description Message displayed in a chip explaining that an image was displayed on the page with dimensions much smaller than the image file dimensions.\n * @example {1000x500} PH1\n * @example {100x50} PH2\n */\n useResponsiveSize:\n 'This image file is larger than it needs to be ({PH1}) for its displayed dimensions ({PH2}). Use responsive images to reduce the image download size.',\n /**\n * @description Column header for a table column containing network requests for images which can improve their file size (e.g. use a different format, increase compression, etc).\n */\n optimizeFile: 'Optimize file size',\n /**\n * @description Table row value representing the remaining items not shown in the table due to size constraints. This row will always represent at least 2 items.\n * @example {5} PH1\n */\n others: '{PH1} others',\n /**\n * @description Text status indicating that no potential optimizations were found for any image file\n */\n noOptimizableImages: 'No optimizable images',\n /**\n * @description Text describing the estimated number of bytes that an image file optimization can save. This text is appended to another block of text describing the image optimization in more detail. \"Est\" means \"Estimated\".\n * @example {Use the correct image dimensions to reduce the image file size.} PH1\n * @example {50 MB} PH2\n */\n estimatedSavings: '{PH1} (Est {PH2})',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/ImageDelivery.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\n/**\n * Even JPEGs with lots of detail can usually be compressed down to <1 byte per pixel\n * Using 4:2:2 subsampling already gets an uncompressed bitmap to 2 bytes per pixel.\n * The compression ratio for JPEG is usually somewhere around 10:1 depending on content, so\n * 8:1 is a reasonable expectation for web content which is 1.5MB for a 6MP image.\n *\n * WebP usually gives ~20% additional savings on top of that, so we will assume 10:1 for WebP.\n * This is quite pessimistic as their study shows a photographic compression ratio of ~29:1.\n * https://developers.google.com/speed/webp/docs/webp_lossless_alpha_study#results\n *\n * AVIF usually gives ~20% additional savings on top of WebP, so we will use 12:1 for AVIF.\n * This is quite pessimistic as Netflix study shows a photographic compression ratio of ~40:1\n * (0.4 *bits* per pixel at SSIM 0.97).\n * https://netflixtechblog.com/avif-for-next-generation-image-coding-b1d75675fe4\n */\nconst TARGET_BYTES_PER_PIXEL_AVIF = 2 * 1 / 12;\n\n/**\n * If GIFs are above this size, we'll flag them\n * See https://github.com/GoogleChrome/lighthouse/pull/4885#discussion_r178406623 and https://github.com/GoogleChrome/lighthouse/issues/4696#issuecomment-370979920\n */\nconst GIF_SIZE_THRESHOLD = 100 * 1024;\n\nconst BYTE_SAVINGS_THRESHOLD = 4096;\n\n// Ignore up to 12KB of waste for responsive images if an effort was made with breakpoints.\nconst BYTE_SAVINGS_THRESHOLD_RESPONSIVE_BREAKPOINTS = 12288;\n\nexport enum ImageOptimizationType {\n ADJUST_COMPRESSION = 'ADJUST_COMPRESSION',\n MODERN_FORMAT_OR_COMPRESSION = 'MODERN_FORMAT_OR_COMPRESSION',\n VIDEO_FORMAT = 'VIDEO_FORMAT',\n RESPONSIVE_SIZE = 'RESPONSIVE_SIZE',\n}\n\nexport type ImageOptimization = {\n type: Exclude<ImageOptimizationType, ImageOptimizationType.RESPONSIVE_SIZE>,\n byteSavings: number,\n}|{\n type: ImageOptimizationType.RESPONSIVE_SIZE,\n byteSavings: number,\n fileDimensions: {width: number, height: number},\n displayDimensions: {width: number, height: number},\n};\n\nexport interface OptimizableImage {\n request: Types.Events.SyntheticNetworkRequest;\n optimizations: ImageOptimization[];\n byteSavings: number;\n /**\n * If the an image resource has multiple `PaintImage`s, we compare its intrinsic size to the largest of the displayed sizes.\n *\n * It is theoretically possible for `PaintImage` events with the same URL to have different intrinsic sizes.\n * However, this should be rare because it requires serving different images from the same URL.\n */\n largestImagePaint: Types.Events.PaintImage;\n}\n\nexport type ImageDeliveryInsightModel = InsightModel<typeof UIStrings, {\n /** Sorted by potential byte savings, then by size of image. */\n optimizableImages: OptimizableImage[],\n wastedBytes: number,\n}>;\n\nexport function isImageDeliveryInsight(model: InsightModel): model is ImageDeliveryInsightModel {\n return model.insightKey === 'ImageDelivery';\n}\n\nexport function getOptimizationMessage(optimization: ImageOptimization): Platform.UIString.LocalizedString {\n switch (optimization.type) {\n case ImageOptimizationType.ADJUST_COMPRESSION:\n return i18nString(UIStrings.useCompression);\n case ImageOptimizationType.MODERN_FORMAT_OR_COMPRESSION:\n return i18nString(UIStrings.useModernFormat);\n case ImageOptimizationType.VIDEO_FORMAT:\n return i18nString(UIStrings.useVideoFormat);\n case ImageOptimizationType.RESPONSIVE_SIZE:\n return i18nString(UIStrings.useResponsiveSize, {\n PH1: `${optimization.fileDimensions.width}x${optimization.fileDimensions.height}`,\n PH2: `${optimization.displayDimensions.width}x${optimization.displayDimensions.height}`,\n });\n }\n}\n\nexport function getOptimizationMessageWithBytes(optimization: ImageOptimization): Platform.UIString.LocalizedString {\n const byteSavingsText = i18n.ByteUtilities.bytesToString(optimization.byteSavings);\n const optimizationMessage = getOptimizationMessage(optimization);\n return i18nString(UIStrings.estimatedSavings, {PH1: optimizationMessage, PH2: byteSavingsText});\n}\n\nfunction finalize(partialModel: PartialInsightModel<ImageDeliveryInsightModel>): ImageDeliveryInsightModel {\n return {\n insightKey: InsightKeys.IMAGE_DELIVERY,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n docs: 'https://developer.chrome.com/docs/performance/insights/image-delivery',\n category: InsightCategory.LCP,\n state: partialModel.optimizableImages.length > 0 ? 'fail' : 'pass',\n ...partialModel,\n relatedEvents: new Map(partialModel.optimizableImages.map(\n image => [image.request, image.optimizations.map(getOptimizationMessageWithBytes)])),\n };\n}\n\n/**\n * Calculate rough savings percentage based on 1000 real gifs transcoded to video\n * https://github.com/GoogleChrome/lighthouse/issues/4696#issuecomment-380296510\n */\nfunction estimateGIFPercentSavings(request: Types.Events.SyntheticNetworkRequest): number {\n return Math.round((29.1 * Math.log10(request.args.data.decodedBodyLength) - 100.7)) / 100;\n}\n\nfunction getDisplayedSize(\n data: Handlers.Types.HandlerData, paintImage: Types.Events.PaintImage): {width: number, height: number} {\n // Note: for traces made prior to metadata.hostDPR (which means no data in\n // paintEventToCorrectedDisplaySize), the displayed size unexpectedly ignores any\n // emulated DPR and so the results may be very misleading.\n return data.ImagePainting.paintEventToCorrectedDisplaySize.get(paintImage) ?? {\n width: paintImage.args.data.width,\n height: paintImage.args.data.height,\n };\n}\n\nfunction getPixelCounts(data: Handlers.Types.HandlerData, paintImage: Types.Events.PaintImage):\n {displayedPixels: number, filePixels: number} {\n const {width, height} = getDisplayedSize(data, paintImage);\n return {\n filePixels: paintImage.args.data.srcWidth * paintImage.args.data.srcHeight,\n displayedPixels: width * height,\n };\n}\n\nexport function generateInsight(\n data: Handlers.Types.HandlerData, context: InsightSetContext): ImageDeliveryInsightModel {\n const isWithinContext = (event: Types.Events.Event): boolean => Helpers.Timing.eventIsInBounds(event, context.bounds);\n\n const contextRequests = data.NetworkRequests.byTime.filter(isWithinContext);\n\n const optimizableImages: OptimizableImage[] = [];\n for (const request of contextRequests) {\n if (request.args.data.resourceType !== 'Image') {\n continue;\n }\n\n if (request.args.data.mimeType === 'image/svg+xml') {\n continue;\n }\n\n // If the request was redirected, the image paints will have the pre-redirect URL.\n const url = request.args.data.redirects[0]?.url ?? request.args.data.url;\n const imagePaints = data.ImagePainting.paintImageEventForUrl.get(url)?.filter(isWithinContext);\n\n // This will filter out things like preloaded image requests where an image file is downloaded\n // but never rendered on the page.\n if (!imagePaints?.length) {\n continue;\n }\n\n const largestImagePaint = imagePaints.reduce((prev, curr) => {\n const prevPixels = getPixelCounts(data, prev).displayedPixels;\n const currPixels = getPixelCounts(data, curr).displayedPixels;\n return prevPixels > currPixels ? prev : curr;\n });\n\n const {\n filePixels: imageFilePixels,\n displayedPixels: largestImageDisplayPixels,\n } = getPixelCounts(data, largestImagePaint);\n\n // Decoded body length is almost always the right one to be using because of the below:\n // `encodedDataLength = decodedBodyLength + headers`.\n // HOWEVER, there are some cases where an image is compressed again over the network and transfer size\n // is smaller (see https://github.com/GoogleChrome/lighthouse/pull/4968).\n // Use the min of the two numbers to be safe.\n const imageBytes = Math.min(request.args.data.decodedBodyLength, request.args.data.encodedDataLength);\n\n const bytesPerPixel = imageBytes / imageFilePixels;\n\n let optimizations: ImageOptimization[] = [];\n if (request.args.data.mimeType === 'image/gif') {\n if (imageBytes > GIF_SIZE_THRESHOLD) {\n const percentSavings = estimateGIFPercentSavings(request);\n const byteSavings = Math.round(imageBytes * percentSavings);\n optimizations.push({type: ImageOptimizationType.VIDEO_FORMAT, byteSavings});\n }\n } else if (bytesPerPixel > TARGET_BYTES_PER_PIXEL_AVIF) {\n const idealAvifImageSize = Math.round(TARGET_BYTES_PER_PIXEL_AVIF * imageFilePixels);\n const byteSavings = imageBytes - idealAvifImageSize;\n if (request.args.data.mimeType !== 'image/webp' && request.args.data.mimeType !== 'image/avif') {\n optimizations.push({type: ImageOptimizationType.MODERN_FORMAT_OR_COMPRESSION, byteSavings});\n } else {\n optimizations.push({type: ImageOptimizationType.ADJUST_COMPRESSION, byteSavings});\n }\n }\n\n // At this point (before looking at image size), the # of optimizations should only ever be 1 or 0\n // Math.max handles both cases correctly, and is defensive against future patches that would add\n // more than 1 format-specific optimization by this point.\n const imageByteSavingsFromFormat = Math.max(0, ...optimizations.map(o => o.byteSavings));\n let imageByteSavings = imageByteSavingsFromFormat;\n\n const wastedPixelRatio = 1 - (largestImageDisplayPixels / imageFilePixels);\n\n // Ignore CSS images because it's difficult to determine what is a spritesheet,\n // and the reward-to-effort ratio for responsive CSS images is quite low https://css-tricks.com/responsive-images-css/.\n if (wastedPixelRatio > 0 && !largestImagePaint.args.data.isCSS) {\n const byteSavings = Math.round(wastedPixelRatio * imageBytes);\n\n const hadBreakpoints = largestImagePaint.args.data.isPicture || largestImagePaint.args.data.srcsetAttribute;\n if (!hadBreakpoints || byteSavings > BYTE_SAVINGS_THRESHOLD_RESPONSIVE_BREAKPOINTS) {\n // This will compound the byte savings from any potential format changes with the image size\n // optimization added here.\n imageByteSavings += Math.round(wastedPixelRatio * (imageBytes - imageByteSavingsFromFormat));\n\n const {width, height} = getDisplayedSize(data, largestImagePaint);\n\n optimizations.push({\n type: ImageOptimizationType.RESPONSIVE_SIZE,\n byteSavings,\n fileDimensions: {\n width: Math.round(largestImagePaint.args.data.srcWidth),\n height: Math.round(largestImagePaint.args.data.srcHeight),\n },\n displayDimensions: {\n width: Math.round(width),\n height: Math.round(height),\n },\n });\n }\n }\n\n optimizations = optimizations.filter(optimization => optimization.byteSavings > BYTE_SAVINGS_THRESHOLD);\n\n if (optimizations.length > 0) {\n optimizableImages.push({\n request,\n largestImagePaint,\n optimizations,\n byteSavings: imageByteSavings,\n });\n }\n }\n\n const wastedBytesByRequestId = new Map<string, number>();\n for (const image of optimizableImages) {\n wastedBytesByRequestId.set(image.request.args.data.requestId, image.byteSavings);\n }\n\n // Sort by savings, then by size of image.\n optimizableImages.sort((a, b) => {\n if (b.byteSavings !== a.byteSavings) {\n return b.byteSavings - a.byteSavings;\n }\n\n return b.request.args.data.decodedBodyLength - a.request.args.data.decodedBodyLength;\n });\n\n return finalize({\n optimizableImages,\n metricSavings: metricSavingsForWastedBytes(wastedBytesByRequestId, context),\n wastedBytes: optimizableImages.reduce((total, img) => total + img.byteSavings, 0),\n });\n}\n\nexport function createOverlayForRequest(request: Types.Events.SyntheticNetworkRequest): Types.Overlays.EntryOutline {\n return {\n type: 'ENTRY_OUTLINE',\n entry: request,\n outlineReason: 'ERROR',\n };\n}\n\nexport function createOverlays(model: ImageDeliveryInsightModel): Types.Overlays.Overlay[] {\n return model.optimizableImages.map(image => createOverlayForRequest(image.request));\n}\n"]}
@@ -11,7 +11,7 @@ export declare const UIStrings: {
11
11
  * @description Description of a DevTools insight that presents a breakdown for the LCP metric by subparts.
12
12
  * This is displayed after a user expands the section to see more. No character length limits.
13
13
  */
14
- readonly description: "Each [subpart has specific improvement strategies](https://web.dev/articles/optimize-lcp#lcp-breakdown). Ideally, most of the LCP time should be spent on loading the resources, not within delays.";
14
+ readonly description: "Each [subpart has specific improvement strategies](https://developer.chrome.com/docs/performance/insights/lcp-breakdown). Ideally, most of the LCP time should be spent on loading the resources, not within delays.";
15
15
  /**
16
16
  * @description Time to first byte title for the Largest Contentful Paint's subparts timespan breakdown.
17
17
  */
@@ -75,7 +75,7 @@ export declare function isLCPBreakdownInsight(model: InsightModel): model is LCP
75
75
  export type LCPBreakdownInsightModel = InsightModel<typeof UIStrings, {
76
76
  lcpMs?: Types.Timing.Milli;
77
77
  lcpTs?: Types.Timing.Milli;
78
- lcpEvent?: Types.Events.LargestContentfulPaintCandidate;
78
+ lcpEvent?: Types.Events.AnyLargestContentfulPaintCandidate;
79
79
  /** The network request for the LCP image, if there was one. */
80
80
  lcpRequest?: Types.Events.SyntheticNetworkRequest;
81
81
  subparts?: LCPSubparts;
@@ -16,7 +16,7 @@ export const UIStrings = {
16
16
  * @description Description of a DevTools insight that presents a breakdown for the LCP metric by subparts.
17
17
  * This is displayed after a user expands the section to see more. No character length limits.
18
18
  */
19
- description: 'Each [subpart has specific improvement strategies](https://web.dev/articles/optimize-lcp#lcp-breakdown). Ideally, most of the LCP time should be spent on loading the resources, not within delays.',
19
+ description: 'Each [subpart has specific improvement strategies](https://developer.chrome.com/docs/performance/insights/lcp-breakdown). Ideally, most of the LCP time should be spent on loading the resources, not within delays.',
20
20
  /**
21
21
  * @description Time to first byte title for the Largest Contentful Paint's subparts timespan breakdown.
22
22
  */
@@ -139,6 +139,7 @@ function finalize(partialModel) {
139
139
  strings: UIStrings,
140
140
  title: i18nString(UIStrings.title),
141
141
  description: i18nString(UIStrings.description),
142
+ docs: 'https://developer.chrome.com/docs/performance/insights/lcp-breakdown',
142
143
  category: InsightCategory.LCP,
143
144
  state,
144
145
  ...partialModel,
@@ -154,13 +155,13 @@ export function generateInsight(data, context) {
154
155
  if (!frameMetrics) {
155
156
  throw new Error('no frame metrics');
156
157
  }
157
- const navMetrics = frameMetrics.get(context.navigationId);
158
+ const navMetrics = frameMetrics.get(context.navigation);
158
159
  if (!navMetrics) {
159
160
  throw new Error('no navigation metrics');
160
161
  }
161
162
  const metricScore = navMetrics.get(Handlers.ModelHandlers.PageLoadMetrics.MetricName.LCP);
162
163
  const lcpEvent = metricScore?.event;
163
- if (!lcpEvent || !Types.Events.isLargestContentfulPaintCandidate(lcpEvent)) {
164
+ if (!lcpEvent || !Types.Events.isAnyLargestContentfulPaintCandidate(lcpEvent)) {
164
165
  return finalize({ warnings: [InsightWarning.NO_LCP] });
165
166
  }
166
167
  // This helps calculate the subparts.
@@ -1 +1 @@
1
- {"version":3,"file":"LCPBreakdown.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/LCPBreakdown.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,yEAA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,CAAC,CAAC,OAAgB,EAAE,EAAE,CAAC,CAAC,EAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,YAAY,EAAE,IAAI,EAAC,CAAC,CAAC;SACxG;KACF,CAAC;IACF,IAAI,KAAK,CAAC,UAAU,EAAE,CAAC;QACrB,QAAQ,CAAC,IAAI,CAAC,EAAC,IAAI,EAAE,eAAe,EAAE,KAAK,EAAE,KAAK,CAAC,UAAU,EAAE,aAAa,EAAE,MAAM,EAAC,CAAC,CAAC;IACzF,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport type * as Common from '../../../core/common/common.js';\nimport * as i18n from '../../../core/i18n/i18n.js';\nimport * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\nimport {calculateDocFirstByteTs} from './Common.js';\nimport {\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n InsightWarning,\n type PartialInsightModel,\n} from './types.js';\n\nexport const UIStrings = {\n /**\n * @description Title of an insight that provides details about the LCP metric, broken down by parts.\n */\n title: 'LCP breakdown',\n /**\n * @description Description of a DevTools insight that presents a breakdown for the LCP metric by subparts.\n * This is displayed after a user expands the section to see more. No character length limits.\n */\n description:\n 'Each [subpart has specific improvement strategies](https://web.dev/articles/optimize-lcp#lcp-breakdown). Ideally, most of the LCP time should be spent on loading the resources, not within delays.',\n /**\n * @description Time to first byte title for the Largest Contentful Paint's subparts timespan breakdown.\n */\n timeToFirstByte: 'Time to first byte',\n /**\n * @description Resource load delay title for the Largest Contentful Paint subparts timespan breakdown.\n */\n resourceLoadDelay: 'Resource load delay',\n /**\n * @description Resource load duration title for the Largest Contentful Paint subparts timespan breakdown.\n */\n resourceLoadDuration: 'Resource load duration',\n /**\n * @description Element render delay title for the Largest Contentful Paint subparts timespan breakdown.\n */\n elementRenderDelay: 'Element render delay',\n /**\n * @description Label used for the subpart (section) of a larger duration.\n */\n subpart: 'Subpart',\n /**\n * @description Label used for the duration a single subpart (section) takes up of a larger duration.\n */\n duration: 'Duration',\n /**\n * @description Label used for the duration a single subpart (section) takes up of a larger duration. The value will be the 75th percentile of aggregate data. \"Field\" means that the data was collected from real users in the field as opposed to the developers local environment. \"Field\" is synonymous with \"Real user data\".\n */\n fieldDuration: 'Field p75',\n /**\n * @description Text status indicating that the the Largest Contentful Paint (LCP) metric timing was not found. \"LCP\" is an acronym and should not be translated.\n */\n noLcp: 'No LCP detected',\n} as const;\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/LCPBreakdown.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\n/** A TraceWindow plus its UIString. **/\nexport type Subpart = Types.Timing.TraceWindowMicro&{label: Common.UIString.LocalizedString};\ninterface LCPSubparts {\n /**\n * The time between when the user initiates loading the page until when\n * the browser receives the first byte of the html response.\n */\n ttfb: Subpart;\n /**\n * The time between ttfb and the LCP request request being started.\n * For a text LCP, this is undefined given no request is loaded.\n */\n loadDelay?: Subpart;\n /**\n * The time it takes to load the LCP request.\n */\n loadDuration?: Subpart;\n /**\n * The time between when the LCP request finishes loading and when\n * the LCP element is rendered.\n */\n renderDelay: Subpart;\n}\n\nexport function isLCPBreakdownInsight(model: InsightModel): model is LCPBreakdownInsightModel {\n return model.insightKey === 'LCPBreakdown';\n}\nexport type LCPBreakdownInsightModel = InsightModel<typeof UIStrings, {\n lcpMs?: Types.Timing.Milli,\n lcpTs?: Types.Timing.Milli,\n lcpEvent?: Types.Events.LargestContentfulPaintCandidate,\n /** The network request for the LCP image, if there was one. */\n lcpRequest?: Types.Events.SyntheticNetworkRequest,\n subparts?: LCPSubparts,\n}>;\n\nfunction anyValuesNaN(...values: number[]): boolean {\n return values.some(v => Number.isNaN(v));\n}\n/**\n * Calculates the 2–4 subparts of an LCP as bounds.\n * Will return `null` if any required values were missing. We don't ever expect\n * them to be missing on newer traces, but old trace files may lack some of the\n * data we rely on, so we want to handle that case.\n */\nfunction determineSubparts(\n nav: Types.Events.NavigationStart, docRequest: Types.Events.SyntheticNetworkRequest,\n lcpEvent: Types.Events.LargestContentfulPaintCandidate,\n lcpRequest: Types.Events.SyntheticNetworkRequest|undefined): LCPSubparts|null {\n const firstDocByteTs = calculateDocFirstByteTs(docRequest);\n if (firstDocByteTs === null) {\n return null;\n }\n\n const ttfb = Helpers.Timing.traceWindowFromMicroSeconds(nav.ts, firstDocByteTs) as Subpart;\n ttfb.label = i18nString(UIStrings.timeToFirstByte);\n\n let renderDelay = Helpers.Timing.traceWindowFromMicroSeconds(ttfb.max, lcpEvent.ts) as Subpart;\n renderDelay.label = i18nString(UIStrings.elementRenderDelay);\n\n // If the LCP is text, we don't have a request, so just 2 subparts.\n if (!lcpRequest) {\n /**\n * Text LCP. 2 subparts, thus 3 timestamps\n *\n * | ttfb | renderDelay |\n * ^ lcpEvent.ts\n * ^ firstDocByteTs\n * ^ navStartTs\n */\n if (anyValuesNaN(ttfb.range, renderDelay.range)) {\n return null;\n }\n return {ttfb, renderDelay};\n }\n\n /**\n * Image LCP. 4 subparts means 5 timestamps\n *\n * | ttfb | loadDelay | loadTime | renderDelay |\n * ^ lcpEvent.ts\n * ^ lcpReqEndTs\n * ^ lcpStartTs\n * ^ ttfbTs\n * ^ navStartTs\n */\n const lcpStartTs = lcpRequest.ts;\n const lcpReqEndTs = lcpRequest.args.data.syntheticData.finishTime;\n\n const loadDelay = Helpers.Timing.traceWindowFromMicroSeconds(ttfb.max, lcpStartTs) as Subpart;\n const loadDuration = Helpers.Timing.traceWindowFromMicroSeconds(lcpStartTs, lcpReqEndTs) as Subpart;\n renderDelay = Helpers.Timing.traceWindowFromMicroSeconds(lcpReqEndTs, lcpEvent.ts) as Subpart;\n loadDelay.label = i18nString(UIStrings.resourceLoadDelay);\n loadDuration.label = i18nString(UIStrings.resourceLoadDuration);\n renderDelay.label = i18nString(UIStrings.elementRenderDelay);\n if (anyValuesNaN(ttfb.range, loadDelay.range, loadDuration.range, renderDelay.range)) {\n return null;\n }\n\n return {\n ttfb,\n loadDelay,\n loadDuration,\n renderDelay,\n };\n}\n\nfunction finalize(partialModel: PartialInsightModel<LCPBreakdownInsightModel>): LCPBreakdownInsightModel {\n const relatedEvents = [];\n if (partialModel.lcpEvent) {\n relatedEvents.push(partialModel.lcpEvent);\n }\n if (partialModel.lcpRequest) {\n relatedEvents.push(partialModel.lcpRequest);\n }\n\n let state: LCPBreakdownInsightModel['state'] = 'pass';\n if (partialModel.lcpMs !== undefined) {\n const classification = Handlers.ModelHandlers.PageLoadMetrics.scoreClassificationForLargestContentfulPaint(\n Helpers.Timing.milliToMicro(partialModel.lcpMs));\n if (classification === Handlers.ModelHandlers.PageLoadMetrics.ScoreClassification.GOOD) {\n state = 'informative';\n } else {\n state = 'fail';\n }\n }\n\n return {\n insightKey: InsightKeys.LCP_BREAKDOWN,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.LCP,\n state,\n ...partialModel,\n relatedEvents,\n };\n}\n\nexport function generateInsight(\n data: Handlers.Types.HandlerData, context: InsightSetContext): LCPBreakdownInsightModel {\n if (!context.navigation) {\n return finalize({});\n }\n\n const networkRequests = data.NetworkRequests;\n\n const frameMetrics = data.PageLoadMetrics.metricScoresByFrameId.get(context.frameId);\n if (!frameMetrics) {\n throw new Error('no frame metrics');\n }\n\n const navMetrics = frameMetrics.get(context.navigationId);\n if (!navMetrics) {\n throw new Error('no navigation metrics');\n }\n const metricScore = navMetrics.get(Handlers.ModelHandlers.PageLoadMetrics.MetricName.LCP);\n const lcpEvent = metricScore?.event;\n if (!lcpEvent || !Types.Events.isLargestContentfulPaintCandidate(lcpEvent)) {\n return finalize({warnings: [InsightWarning.NO_LCP]});\n }\n\n // This helps calculate the subparts.\n const lcpMs = Helpers.Timing.microToMilli(metricScore.timing);\n // This helps position things on the timeline's UI accurately for a trace.\n const lcpTs = metricScore.event?.ts ? Helpers.Timing.microToMilli(metricScore.event?.ts) : undefined;\n const lcpRequest = data.LargestImagePaint.lcpRequestByNavigationId.get(context.navigationId);\n\n const docRequest = networkRequests.byId.get(context.navigationId);\n if (!docRequest) {\n return finalize({lcpMs, lcpTs, lcpEvent, lcpRequest, warnings: [InsightWarning.NO_DOCUMENT_REQUEST]});\n }\n\n return finalize({\n lcpMs,\n lcpTs,\n lcpEvent,\n lcpRequest,\n subparts: determineSubparts(context.navigation, docRequest, lcpEvent, lcpRequest) ?? undefined,\n });\n}\n\nexport function createOverlays(model: LCPBreakdownInsightModel): Types.Overlays.Overlay[] {\n if (!model.subparts || !model.lcpTs) {\n return [];\n }\n\n const overlays: Types.Overlays.Overlay[] = [\n {\n type: 'TIMESPAN_BREAKDOWN',\n sections: Object.values(model.subparts)\n .map((subpart: Subpart) => ({bounds: subpart, label: subpart.label, showDuration: true})),\n },\n ];\n if (model.lcpRequest) {\n overlays.push({type: 'ENTRY_OUTLINE', entry: model.lcpRequest, outlineReason: 'INFO'});\n }\n\n return overlays;\n}\n"]}
1
+ {"version":3,"file":"LCPBreakdown.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/LCPBreakdown.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,yEAAyE;AACzE,6BAA6B;AAG7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AACnD,OAAO,KAAK,QAAQ,MAAM,yBAAyB,CAAC;AACpD,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAC,uBAAuB,EAAC,MAAM,aAAa,CAAC;AACpD,OAAO,EACL,eAAe,EACf,WAAW,EAGX,cAAc,GAEf,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,eAAe;IACt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AAC;AAClB,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport type * as Common from '../../../core/common/common.js';\nimport * as i18n from '../../../core/i18n/i18n.js';\nimport * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\nimport {calculateDocFirstByteTs} from './Common.js';\nimport {\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n InsightWarning,\n type PartialInsightModel,\n} from './types.js';\n\nexport const UIStrings = {\n /**\n * @description Title of an insight that provides details about the LCP metric, broken down by parts.\n */\n title: 'LCP breakdown',\n /**\n * @description Description of a DevTools insight that presents a breakdown for the LCP metric by subparts.\n * This is displayed after a user expands the section to see more. No character length limits.\n */\n description:\n 'Each [subpart has specific improvement strategies](https://developer.chrome.com/docs/performance/insights/lcp-breakdown). Ideally, most of the LCP time should be spent on loading the resources, not within delays.',\n /**\n * @description Time to first byte title for the Largest Contentful Paint's subparts timespan breakdown.\n */\n timeToFirstByte: 'Time to first byte',\n /**\n * @description Resource load delay title for the Largest Contentful Paint subparts timespan breakdown.\n */\n resourceLoadDelay: 'Resource load delay',\n /**\n * @description Resource load duration title for the Largest Contentful Paint subparts timespan breakdown.\n */\n resourceLoadDuration: 'Resource load duration',\n /**\n * @description Element render delay title for the Largest Contentful Paint subparts timespan breakdown.\n */\n elementRenderDelay: 'Element render delay',\n /**\n * @description Label used for the subpart (section) of a larger duration.\n */\n subpart: 'Subpart',\n /**\n * @description Label used for the duration a single subpart (section) takes up of a larger duration.\n */\n duration: 'Duration',\n /**\n * @description Label used for the duration a single subpart (section) takes up of a larger duration. The value will be the 75th percentile of aggregate data. \"Field\" means that the data was collected from real users in the field as opposed to the developers local environment. \"Field\" is synonymous with \"Real user data\".\n */\n fieldDuration: 'Field p75',\n /**\n * @description Text status indicating that the the Largest Contentful Paint (LCP) metric timing was not found. \"LCP\" is an acronym and should not be translated.\n */\n noLcp: 'No LCP detected',\n} as const;\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/LCPBreakdown.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\n/** A TraceWindow plus its UIString. **/\nexport type Subpart = Types.Timing.TraceWindowMicro&{label: Common.UIString.LocalizedString};\ninterface LCPSubparts {\n /**\n * The time between when the user initiates loading the page until when\n * the browser receives the first byte of the html response.\n */\n ttfb: Subpart;\n /**\n * The time between ttfb and the LCP request request being started.\n * For a text LCP, this is undefined given no request is loaded.\n */\n loadDelay?: Subpart;\n /**\n * The time it takes to load the LCP request.\n */\n loadDuration?: Subpart;\n /**\n * The time between when the LCP request finishes loading and when\n * the LCP element is rendered.\n */\n renderDelay: Subpart;\n}\n\nexport function isLCPBreakdownInsight(model: InsightModel): model is LCPBreakdownInsightModel {\n return model.insightKey === 'LCPBreakdown';\n}\nexport type LCPBreakdownInsightModel = InsightModel<typeof UIStrings, {\n lcpMs?: Types.Timing.Milli,\n lcpTs?: Types.Timing.Milli,\n lcpEvent?: Types.Events.AnyLargestContentfulPaintCandidate,\n /** The network request for the LCP image, if there was one. */\n lcpRequest?: Types.Events.SyntheticNetworkRequest,\n subparts?: LCPSubparts,\n}>;\n\nfunction anyValuesNaN(...values: number[]): boolean {\n return values.some(v => Number.isNaN(v));\n}\n/**\n * Calculates the 2–4 subparts of an LCP as bounds.\n * Will return `null` if any required values were missing. We don't ever expect\n * them to be missing on newer traces, but old trace files may lack some of the\n * data we rely on, so we want to handle that case.\n */\nfunction determineSubparts(\n nav: Types.Events.NavigationStart, docRequest: Types.Events.SyntheticNetworkRequest,\n lcpEvent: Types.Events.AnyLargestContentfulPaintCandidate,\n lcpRequest: Types.Events.SyntheticNetworkRequest|undefined): LCPSubparts|null {\n const firstDocByteTs = calculateDocFirstByteTs(docRequest);\n if (firstDocByteTs === null) {\n return null;\n }\n\n const ttfb = Helpers.Timing.traceWindowFromMicroSeconds(nav.ts, firstDocByteTs) as Subpart;\n ttfb.label = i18nString(UIStrings.timeToFirstByte);\n\n let renderDelay = Helpers.Timing.traceWindowFromMicroSeconds(ttfb.max, lcpEvent.ts) as Subpart;\n renderDelay.label = i18nString(UIStrings.elementRenderDelay);\n\n // If the LCP is text, we don't have a request, so just 2 subparts.\n if (!lcpRequest) {\n /**\n * Text LCP. 2 subparts, thus 3 timestamps\n *\n * | ttfb | renderDelay |\n * ^ lcpEvent.ts\n * ^ firstDocByteTs\n * ^ navStartTs\n */\n if (anyValuesNaN(ttfb.range, renderDelay.range)) {\n return null;\n }\n return {ttfb, renderDelay};\n }\n\n /**\n * Image LCP. 4 subparts means 5 timestamps\n *\n * | ttfb | loadDelay | loadTime | renderDelay |\n * ^ lcpEvent.ts\n * ^ lcpReqEndTs\n * ^ lcpStartTs\n * ^ ttfbTs\n * ^ navStartTs\n */\n const lcpStartTs = lcpRequest.ts;\n const lcpReqEndTs = lcpRequest.args.data.syntheticData.finishTime;\n\n const loadDelay = Helpers.Timing.traceWindowFromMicroSeconds(ttfb.max, lcpStartTs) as Subpart;\n const loadDuration = Helpers.Timing.traceWindowFromMicroSeconds(lcpStartTs, lcpReqEndTs) as Subpart;\n renderDelay = Helpers.Timing.traceWindowFromMicroSeconds(lcpReqEndTs, lcpEvent.ts) as Subpart;\n loadDelay.label = i18nString(UIStrings.resourceLoadDelay);\n loadDuration.label = i18nString(UIStrings.resourceLoadDuration);\n renderDelay.label = i18nString(UIStrings.elementRenderDelay);\n if (anyValuesNaN(ttfb.range, loadDelay.range, loadDuration.range, renderDelay.range)) {\n return null;\n }\n\n return {\n ttfb,\n loadDelay,\n loadDuration,\n renderDelay,\n };\n}\n\nfunction finalize(partialModel: PartialInsightModel<LCPBreakdownInsightModel>): LCPBreakdownInsightModel {\n const relatedEvents = [];\n if (partialModel.lcpEvent) {\n relatedEvents.push(partialModel.lcpEvent);\n }\n if (partialModel.lcpRequest) {\n relatedEvents.push(partialModel.lcpRequest);\n }\n\n let state: LCPBreakdownInsightModel['state'] = 'pass';\n if (partialModel.lcpMs !== undefined) {\n const classification = Handlers.ModelHandlers.PageLoadMetrics.scoreClassificationForLargestContentfulPaint(\n Helpers.Timing.milliToMicro(partialModel.lcpMs));\n if (classification === Handlers.ModelHandlers.PageLoadMetrics.ScoreClassification.GOOD) {\n state = 'informative';\n } else {\n state = 'fail';\n }\n }\n\n return {\n insightKey: InsightKeys.LCP_BREAKDOWN,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n docs: 'https://developer.chrome.com/docs/performance/insights/lcp-breakdown',\n category: InsightCategory.LCP,\n state,\n ...partialModel,\n relatedEvents,\n };\n}\n\nexport function generateInsight(\n data: Handlers.Types.HandlerData, context: InsightSetContext): LCPBreakdownInsightModel {\n if (!context.navigation) {\n return finalize({});\n }\n\n const networkRequests = data.NetworkRequests;\n\n const frameMetrics = data.PageLoadMetrics.metricScoresByFrameId.get(context.frameId);\n if (!frameMetrics) {\n throw new Error('no frame metrics');\n }\n\n const navMetrics = frameMetrics.get(context.navigation);\n if (!navMetrics) {\n throw new Error('no navigation metrics');\n }\n const metricScore = navMetrics.get(Handlers.ModelHandlers.PageLoadMetrics.MetricName.LCP);\n const lcpEvent = metricScore?.event;\n if (!lcpEvent || !Types.Events.isAnyLargestContentfulPaintCandidate(lcpEvent)) {\n return finalize({warnings: [InsightWarning.NO_LCP]});\n }\n\n // This helps calculate the subparts.\n const lcpMs = Helpers.Timing.microToMilli(metricScore.timing);\n // This helps position things on the timeline's UI accurately for a trace.\n const lcpTs = metricScore.event?.ts ? Helpers.Timing.microToMilli(metricScore.event?.ts) : undefined;\n const lcpRequest = data.LargestImagePaint.lcpRequestByNavigationId.get(context.navigationId);\n\n const docRequest = networkRequests.byId.get(context.navigationId);\n if (!docRequest) {\n return finalize({lcpMs, lcpTs, lcpEvent, lcpRequest, warnings: [InsightWarning.NO_DOCUMENT_REQUEST]});\n }\n\n return finalize({\n lcpMs,\n lcpTs,\n lcpEvent,\n lcpRequest,\n subparts: determineSubparts(context.navigation, docRequest, lcpEvent, lcpRequest) ?? undefined,\n });\n}\n\nexport function createOverlays(model: LCPBreakdownInsightModel): Types.Overlays.Overlay[] {\n if (!model.subparts || !model.lcpTs) {\n return [];\n }\n\n const overlays: Types.Overlays.Overlay[] = [\n {\n type: 'TIMESPAN_BREAKDOWN',\n sections: Object.values(model.subparts)\n .map((subpart: Subpart) => ({bounds: subpart, label: subpart.label, showDuration: true})),\n },\n ];\n if (model.lcpRequest) {\n overlays.push({type: 'ENTRY_OUTLINE', entry: model.lcpRequest, outlineReason: 'INFO'});\n }\n\n return overlays;\n}\n"]}
@@ -9,7 +9,7 @@ export declare const UIStrings: {
9
9
  /**
10
10
  * @description Description of an insight that provides details about the LCP metric, and the network requests necessary to load it.
11
11
  */
12
- readonly description: "Optimize LCP by making the LCP image [discoverable](https://web.dev/articles/optimize-lcp#1_eliminate_resource_load_delay) from the HTML immediately, and [avoiding lazy-loading](https://web.dev/articles/lcp-lazy-loading)";
12
+ readonly description: "[Optimize LCP](https://developer.chrome.com/docs/performance/insights/lcp-discovery) by making the LCP image discoverable from the HTML immediately, and avoiding lazy-loading";
13
13
  /**
14
14
  * @description Text to tell the user how long after the earliest discovery time their LCP element loaded.
15
15
  * @example {401ms} PH1
@@ -23,14 +23,18 @@ export declare const UIStrings: {
23
23
  * @description Text to tell the user that a fetchpriority property value of "high" should be applied to the LCP request.
24
24
  */
25
25
  readonly fetchPriorityShouldBeApplied: "fetchpriority=high should be applied";
26
+ /**
27
+ * @description Text to tell the user that a fetchpriority property value of "high" should be applied to the preload request that loads the LCP image.
28
+ */
29
+ readonly fetchPriorityShouldBeAppliedToImagePreload: "fetchpriority=high should be applied to the image preload request";
26
30
  /**
27
31
  * @description Text to tell the user that the LCP request is discoverable in the initial document.
28
32
  */
29
33
  readonly requestDiscoverable: "Request is discoverable in initial document";
30
34
  /**
31
- * @description Text to tell the user that the LCP request does not have the lazy load property applied.
35
+ * @description Text to tell the user that LCP resources should avoid using loading=lazy.
32
36
  */
33
- readonly lazyLoadNotApplied: "lazy load not applied";
37
+ readonly lazyLoadNotApplied: "LCP resources should not use loading=lazy";
34
38
  /**
35
39
  * @description Text status indicating that the the Largest Contentful Paint (LCP) metric timing was not found. "LCP" is an acronym and should not be translated.
36
40
  */
@@ -43,7 +47,7 @@ export declare const UIStrings: {
43
47
  export declare const i18nString: (id: string, values?: Record<string, string> | undefined) => Record<string, string>;
44
48
  export declare function isLCPDiscoveryInsight(model: InsightModel): model is LCPDiscoveryInsightModel;
45
49
  export type LCPDiscoveryInsightModel = InsightModel<typeof UIStrings, {
46
- lcpEvent?: Types.Events.LargestContentfulPaintCandidate;
50
+ lcpEvent?: Types.Events.AnyLargestContentfulPaintCandidate;
47
51
  /** The network request for the LCP image, if there was one. */
48
52
  lcpRequest?: Types.Events.SyntheticNetworkRequest;
49
53
  earliestDiscoveryTimeTs?: Types.Timing.Micro;
@@ -15,7 +15,7 @@ export const UIStrings = {
15
15
  /**
16
16
  * @description Description of an insight that provides details about the LCP metric, and the network requests necessary to load it.
17
17
  */
18
- description: 'Optimize LCP by making the LCP image [discoverable](https://web.dev/articles/optimize-lcp#1_eliminate_resource_load_delay) from the HTML immediately, and [avoiding lazy-loading](https://web.dev/articles/lcp-lazy-loading)',
18
+ description: '[Optimize LCP](https://developer.chrome.com/docs/performance/insights/lcp-discovery) by making the LCP image discoverable from the HTML immediately, and avoiding lazy-loading',
19
19
  /**
20
20
  * @description Text to tell the user how long after the earliest discovery time their LCP element loaded.
21
21
  * @example {401ms} PH1
@@ -29,14 +29,18 @@ export const UIStrings = {
29
29
  * @description Text to tell the user that a fetchpriority property value of "high" should be applied to the LCP request.
30
30
  */
31
31
  fetchPriorityShouldBeApplied: 'fetchpriority=high should be applied',
32
+ /**
33
+ * @description Text to tell the user that a fetchpriority property value of "high" should be applied to the preload request that loads the LCP image.
34
+ */
35
+ fetchPriorityShouldBeAppliedToImagePreload: 'fetchpriority=high should be applied to the image preload request',
32
36
  /**
33
37
  * @description Text to tell the user that the LCP request is discoverable in the initial document.
34
38
  */
35
39
  requestDiscoverable: 'Request is discoverable in initial document',
36
40
  /**
37
- * @description Text to tell the user that the LCP request does not have the lazy load property applied.
41
+ * @description Text to tell the user that LCP resources should avoid using loading=lazy.
38
42
  */
39
- lazyLoadNotApplied: 'lazy load not applied',
43
+ lazyLoadNotApplied: 'LCP resources should not use loading=lazy',
40
44
  /**
41
45
  * @description Text status indicating that the the Largest Contentful Paint (LCP) metric timing was not found. "LCP" is an acronym and should not be translated.
42
46
  */
@@ -61,6 +65,7 @@ function finalize(partialModel) {
61
65
  strings: UIStrings,
62
66
  title: i18nString(UIStrings.title),
63
67
  description: i18nString(UIStrings.description),
68
+ docs: 'https://developer.chrome.com/docs/performance/insights/lcp-discovery',
64
69
  category: InsightCategory.LCP,
65
70
  state: partialModel.lcpRequest && partialModel.checklist &&
66
71
  (!partialModel.checklist.eagerlyLoaded.value || !partialModel.checklist.requestDiscoverable.value ||
@@ -80,13 +85,13 @@ export function generateInsight(data, context) {
80
85
  if (!frameMetrics) {
81
86
  throw new Error('no frame metrics');
82
87
  }
83
- const navMetrics = frameMetrics.get(context.navigationId);
88
+ const navMetrics = frameMetrics.get(context.navigation);
84
89
  if (!navMetrics) {
85
90
  throw new Error('no navigation metrics');
86
91
  }
87
92
  const metricScore = navMetrics.get(Handlers.ModelHandlers.PageLoadMetrics.MetricName.LCP);
88
93
  const lcpEvent = metricScore?.event;
89
- if (!lcpEvent || !Types.Events.isLargestContentfulPaintCandidate(lcpEvent)) {
94
+ if (!lcpEvent || !Types.Events.isAnyLargestContentfulPaintCandidate(lcpEvent)) {
90
95
  return finalize({ warnings: [InsightWarning.NO_LCP] });
91
96
  }
92
97
  const docRequest = networkRequests.byId.get(context.navigationId);
@@ -98,27 +103,29 @@ export function generateInsight(data, context) {
98
103
  return finalize({ lcpEvent });
99
104
  }
100
105
  const initiatorUrl = lcpRequest.args.data.initiator?.url;
101
- // TODO(b/372319476): Explore using trace event HTMLDocumentParser::FetchQueuedPreloads to determine if the request
102
- // is discovered by the preload scanner.
103
106
  const initiatedByMainDoc = lcpRequest?.args.data.initiator?.type === 'parser' && docRequest.args.data.url === initiatorUrl;
104
107
  const imgPreloadedOrFoundInHTML = lcpRequest?.args.data.isLinkPreload || initiatedByMainDoc;
105
- const imageLoadingAttr = lcpEvent.args.data?.loadingAttr;
106
108
  const imageFetchPriorityHint = lcpRequest?.args.data.fetchPriorityHint;
107
109
  // This is the earliest discovery time an LCP request could have - it's TTFB (as an absolute timestamp).
108
110
  const earliestDiscoveryTime = calculateDocFirstByteTs(docRequest);
109
111
  const priorityHintFound = imageFetchPriorityHint === 'high';
112
+ const missingPriorityHintLabel = lcpRequest.args.data.isLinkPreload ?
113
+ i18nString(UIStrings.fetchPriorityShouldBeAppliedToImagePreload) :
114
+ i18nString(UIStrings.fetchPriorityShouldBeApplied);
115
+ // A lazy-loaded LCP image can still be eagerly loaded when its request is
116
+ // initiated by a preload.
117
+ const lcpNotLazyLoaded = lcpEvent.args.data?.loadingAttr !== 'lazy' || lcpRequest.args.data.isLinkPreload;
110
118
  return finalize({
111
119
  lcpEvent,
112
120
  lcpRequest,
113
121
  earliestDiscoveryTimeTs: earliestDiscoveryTime ? Types.Timing.Micro(earliestDiscoveryTime) : undefined,
114
122
  checklist: {
115
123
  priorityHinted: {
116
- label: priorityHintFound ? i18nString(UIStrings.fetchPriorityApplied) :
117
- i18nString(UIStrings.fetchPriorityShouldBeApplied),
124
+ label: priorityHintFound ? i18nString(UIStrings.fetchPriorityApplied) : missingPriorityHintLabel,
118
125
  value: priorityHintFound
119
126
  },
120
127
  requestDiscoverable: { label: i18nString(UIStrings.requestDiscoverable), value: imgPreloadedOrFoundInHTML },
121
- eagerlyLoaded: { label: i18nString(UIStrings.lazyLoadNotApplied), value: imageLoadingAttr !== 'lazy' },
128
+ eagerlyLoaded: { label: i18nString(UIStrings.lazyLoadNotApplied), value: lcpNotLazyLoaded },
122
129
  },
123
130
  });
124
131
  }
@@ -1 +1 @@
1
- {"version":3,"file":"LCPDiscovery.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/LCPDiscovery.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AACnD,OAAO,KAAK,QAAQ,MAAM,yBAAyB,CAAC;AACpD,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAC,uBAAuB,EAAC,MAAM,aAAa,CAAC;AACpD,OAAO,EAEL,eAAe,EACf,WAAW,EAGX,cAAc,GAEf,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,uBAAuB;IAC9B;;OAEG;IACH,WAAW,EACP,8NAA8N;IAClO;;;OAGG;IACH,YAAY,EAAE,oDAAoD;IAClE;;OAEG;IACH,oBAAoB,EAAE,4BAA4B;IAClD;;OAEG;IACH,4BAA4B,EAAE,sCAAsC;IACpE;;OAEG;IACH,mBAAmB,EAAE,6CAA6C;IAClE;;OAEG;IACH,kBAAkB,EAAE,uBAAuB;IAC3C;;OAEG;IACH,KAAK,EAAE,iBAAiB;IACxB;;OAEG;IACH,aAAa,EAAE,0DAA0D;CACjE,CAAC;AAEX,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,uCAAuC,EAAE,SAAS,CAAC,CAAC;AAC7F,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAE7E,MAAM,UAAU,qBAAqB,CAAC,KAAmB;IACvD,OAAO,KAAK,CAAC,UAAU,KAAK,cAAc,CAAC;AAC7C,CAAC;AASD,SAAS,QAAQ,CAAC,YAA2D;IAC3E,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,KAAK,EAAE,YAAY,CAAC,OAAO;YAC3B,aAAa,EAAE,OAAO;SACvB;QACD;YACE,IAAI,EAAE,0BAA0B;YAChC,MAAM,EAAE,KAAK;YACb,KAAK,EAAE,YAAY,CAAC,OAAO;SAC5B;QACD;YACE,IAAI,EAAE,oBAAoB;YAC1B,QAAQ,EAAE,CAAC;oBACT,MAAM,EAAE,KAAK;oBACb,uCAAuC;oBACvC,KAAK,EAAE,GAAG,YAAY,CAAC,cAAc,eAAe;oBACpD,YAAY,EAAE,KAAK;iBACpB,CAAC;YACF,KAAK,EAAE,YAAY,CAAC,OAAO;YAC3B,cAAc,EAAE,aAAa;SAC9B;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as i18n from '../../../core/i18n/i18n.js';\nimport * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\nimport {calculateDocFirstByteTs} from './Common.js';\nimport {\n type Checklist,\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n InsightWarning,\n type PartialInsightModel,\n} from './types.js';\n\nexport const UIStrings = {\n /**\n * @description Title of an insight that provides details about the LCP metric, and the network requests necessary to load it. Details how the LCP request was discoverable - in other words, the path necessary to load it (ex: network requests, JavaScript)\n */\n title: 'LCP request discovery',\n /**\n * @description Description of an insight that provides details about the LCP metric, and the network requests necessary to load it.\n */\n description:\n 'Optimize LCP by making the LCP image [discoverable](https://web.dev/articles/optimize-lcp#1_eliminate_resource_load_delay) from the HTML immediately, and [avoiding lazy-loading](https://web.dev/articles/lcp-lazy-loading)',\n /**\n * @description Text to tell the user how long after the earliest discovery time their LCP element loaded.\n * @example {401ms} PH1\n */\n lcpLoadDelay: 'LCP image loaded {PH1} after earliest start point.',\n /**\n * @description Text to tell the user that a fetchpriority property value of \"high\" is applied to the LCP request.\n */\n fetchPriorityApplied: 'fetchpriority=high applied',\n /**\n * @description Text to tell the user that a fetchpriority property value of \"high\" should be applied to the LCP request.\n */\n fetchPriorityShouldBeApplied: 'fetchpriority=high should be applied',\n /**\n * @description Text to tell the user that the LCP request is discoverable in the initial document.\n */\n requestDiscoverable: 'Request is discoverable in initial document',\n /**\n * @description Text to tell the user that the LCP request does not have the lazy load property applied.\n */\n lazyLoadNotApplied: 'lazy load not applied',\n /**\n * @description Text status indicating that the the Largest Contentful Paint (LCP) metric timing was not found. \"LCP\" is an acronym and should not be translated.\n */\n noLcp: 'No LCP detected',\n /**\n * @description Text status indicating that the Largest Contentful Paint (LCP) metric was text rather than an image. \"LCP\" is an acronym and should not be translated.\n */\n noLcpResource: 'No LCP resource detected because the LCP is not an image',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/LCPDiscovery.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport function isLCPDiscoveryInsight(model: InsightModel): model is LCPDiscoveryInsightModel {\n return model.insightKey === 'LCPDiscovery';\n}\nexport type LCPDiscoveryInsightModel = InsightModel<typeof UIStrings, {\n lcpEvent?: Types.Events.LargestContentfulPaintCandidate,\n /** The network request for the LCP image, if there was one. */\n lcpRequest?: Types.Events.SyntheticNetworkRequest,\n earliestDiscoveryTimeTs?: Types.Timing.Micro,\n checklist?: Checklist<'priorityHinted'|'requestDiscoverable'|'eagerlyLoaded'>,\n}>;\n\nfunction finalize(partialModel: PartialInsightModel<LCPDiscoveryInsightModel>): LCPDiscoveryInsightModel {\n const relatedEvents = partialModel.lcpEvent && partialModel.lcpRequest ?\n // TODO: add entire request initiator chain?\n [partialModel.lcpEvent, partialModel.lcpRequest] :\n [];\n return {\n insightKey: InsightKeys.LCP_DISCOVERY,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.LCP,\n state: partialModel.lcpRequest && partialModel.checklist &&\n (!partialModel.checklist.eagerlyLoaded.value || !partialModel.checklist.requestDiscoverable.value ||\n !partialModel.checklist.priorityHinted.value) ?\n 'fail' :\n 'pass',\n ...partialModel,\n relatedEvents,\n };\n}\n\nexport function generateInsight(\n data: Handlers.Types.HandlerData, context: InsightSetContext): LCPDiscoveryInsightModel {\n if (!context.navigation) {\n return finalize({});\n }\n\n const networkRequests = data.NetworkRequests;\n\n const frameMetrics = data.PageLoadMetrics.metricScoresByFrameId.get(context.frameId);\n if (!frameMetrics) {\n throw new Error('no frame metrics');\n }\n\n const navMetrics = frameMetrics.get(context.navigationId);\n if (!navMetrics) {\n throw new Error('no navigation metrics');\n }\n const metricScore = navMetrics.get(Handlers.ModelHandlers.PageLoadMetrics.MetricName.LCP);\n const lcpEvent = metricScore?.event;\n if (!lcpEvent || !Types.Events.isLargestContentfulPaintCandidate(lcpEvent)) {\n return finalize({warnings: [InsightWarning.NO_LCP]});\n }\n\n const docRequest = networkRequests.byId.get(context.navigationId);\n if (!docRequest) {\n return finalize({warnings: [InsightWarning.NO_DOCUMENT_REQUEST]});\n }\n\n const lcpRequest = data.LargestImagePaint.lcpRequestByNavigationId.get(context.navigationId);\n if (!lcpRequest) {\n return finalize({lcpEvent});\n }\n\n const initiatorUrl = lcpRequest.args.data.initiator?.url;\n // TODO(b/372319476): Explore using trace event HTMLDocumentParser::FetchQueuedPreloads to determine if the request\n // is discovered by the preload scanner.\n const initiatedByMainDoc =\n lcpRequest?.args.data.initiator?.type === 'parser' && docRequest.args.data.url === initiatorUrl;\n const imgPreloadedOrFoundInHTML = lcpRequest?.args.data.isLinkPreload || initiatedByMainDoc;\n\n const imageLoadingAttr = lcpEvent.args.data?.loadingAttr;\n const imageFetchPriorityHint = lcpRequest?.args.data.fetchPriorityHint;\n // This is the earliest discovery time an LCP request could have - it's TTFB (as an absolute timestamp).\n const earliestDiscoveryTime = calculateDocFirstByteTs(docRequest);\n\n const priorityHintFound = imageFetchPriorityHint === 'high';\n\n return finalize({\n lcpEvent,\n lcpRequest,\n earliestDiscoveryTimeTs: earliestDiscoveryTime ? Types.Timing.Micro(earliestDiscoveryTime) : undefined,\n checklist: {\n priorityHinted: {\n label: priorityHintFound ? i18nString(UIStrings.fetchPriorityApplied) :\n i18nString(UIStrings.fetchPriorityShouldBeApplied),\n value: priorityHintFound\n },\n requestDiscoverable: {label: i18nString(UIStrings.requestDiscoverable), value: imgPreloadedOrFoundInHTML},\n eagerlyLoaded: {label: i18nString(UIStrings.lazyLoadNotApplied), value: imageLoadingAttr !== 'lazy'},\n },\n });\n}\n\ninterface LCPImageDiscoveryData {\n checklist: Exclude<LCPDiscoveryInsightModel['checklist'], undefined>;\n request: Types.Events.SyntheticNetworkRequest;\n discoveryDelay: Types.Timing.Micro|null;\n estimatedSavings: Types.Timing.Milli|null;\n}\n\n/**\n * TODO: this extra transformation (getImageData) should not be necessary.\n */\nexport function getImageData(model: LCPDiscoveryInsightModel): LCPImageDiscoveryData|null {\n if (!model.lcpRequest || !model.checklist) {\n return null;\n }\n\n const shouldIncreasePriorityHint = !model.checklist.priorityHinted.value;\n const shouldPreloadImage = !model.checklist.requestDiscoverable.value;\n const shouldRemoveLazyLoading = !model.checklist.eagerlyLoaded.value;\n\n const imageLCP = shouldIncreasePriorityHint !== undefined && shouldPreloadImage !== undefined &&\n shouldRemoveLazyLoading !== undefined;\n\n // Shouldn't render anything if lcp insight is null or lcp is text.\n if (!imageLCP) {\n return null;\n }\n\n const data: LCPImageDiscoveryData = {\n checklist: model.checklist,\n request: model.lcpRequest,\n discoveryDelay: null,\n estimatedSavings: model.metricSavings?.LCP ?? null,\n };\n\n if (model.earliestDiscoveryTimeTs && model.lcpRequest) {\n const discoveryDelay = model.lcpRequest.ts - model.earliestDiscoveryTimeTs;\n data.discoveryDelay = Types.Timing.Micro(discoveryDelay);\n }\n\n return data;\n}\n\nexport function createOverlays(model: LCPDiscoveryInsightModel): Types.Overlays.Overlay[] {\n const imageResults = getImageData(model);\n if (!imageResults?.discoveryDelay) {\n return [];\n }\n\n const delay = Helpers.Timing.traceWindowFromMicroSeconds(\n Types.Timing.Micro(imageResults.request.ts - imageResults.discoveryDelay),\n imageResults.request.ts,\n );\n\n return [\n {\n type: 'ENTRY_OUTLINE',\n entry: imageResults.request,\n outlineReason: 'ERROR',\n },\n {\n type: 'CANDY_STRIPED_TIME_RANGE',\n bounds: delay,\n entry: imageResults.request,\n },\n {\n type: 'TIMESPAN_BREAKDOWN',\n sections: [{\n bounds: delay,\n // This is overridden in the component.\n label: `${imageResults.discoveryDelay} microseconds`,\n showDuration: false,\n }],\n entry: imageResults.request,\n renderLocation: 'ABOVE_EVENT',\n },\n ];\n}\n"]}
1
+ {"version":3,"file":"LCPDiscovery.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/LCPDiscovery.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AACnD,OAAO,KAAK,QAAQ,MAAM,yBAAyB,CAAC;AACpD,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EAAC,uBAAuB,EAAC,MAAM,aAAa,CAAC;AACpD,OAAO,EAEL,eAAe,EACf,WAAW,EAGX,cAAc,GAEf,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,uBAAuB;IAC9B;;OAEG;IACH,WAAW,EACP,gLAAgL;IACpL;;;OAGG;IACH,YAAY,EAAE,oDAAoD;IAClE;;OAEG;IACH,oBAAoB,EAAE,4BAA4B;IAClD;;OAEG;IACH,4BAA4B,EAAE,sCAAsC;IACpE;;OAEG;IACH,0CAA0C,EAAE,mEAAmE;IAC/G;;OAEG;IACH,mBAAmB,EAAE,6CAA6C;IAClE;;OAEG;IACH,kBAAkB,EAAE,2CAA2C;IAC/D;;OAEG;IACH,KAAK,EAAE,iBAAiB;IACxB;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Ac,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,GAAG,KAAK,CAAC,uBAAuB,CAAC;QAC3E,IAAI,CAAC,cAAc,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;IAC3D,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,KAA+B;IAC5D,MAAM,YAAY,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;IACzC,IAAI,CAAC,YAAY,EAAE,cAAc,EAAE,CAAC;QAClC,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,MAAM,KAAK,GAAG,OAAO,CAAC,MAAM,CAAC,2BAA2B,CACpD,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,GAAG,YAAY,CAAC,cAAc,CAAC,EACzE,YAAY,CAAC,OAAO,CAAC,EAAE,CAC1B,CAAC;IAEF,OAAO;QACL;YACE,IAAI,EAAE,eAAe;YACrB,KAAK,EAAE,YAAY,CAAC,OAAO;YAC3B,aAAa,EAAE,OAAO;SACvB;QACD;YACE,IAAI,EAAE,0BAA0B;YAChC,MAAM,EAAE,KAAK;YACb,KAAK,EAAE,YAAY,CAAC,OAAO;SAC5B;QACD;YACE,IAAI,EAAE,oBAAoB;YAC1B,QAAQ,EAAE,CAAC;oBACT,MAAM,EAAE,KAAK;oBACb,uCAAuC;oBACvC,KAAK,EAAE,GAAG,YAAY,CAAC,cAAc,eAAe;oBACpD,YAAY,EAAE,KAAK;iBACpB,CAAC;YACF,KAAK,EAAE,YAAY,CAAC,OAAO;YAC3B,cAAc,EAAE,aAAa;SAC9B;KACF,CAAC;AACJ,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as i18n from '../../../core/i18n/i18n.js';\nimport * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\nimport {calculateDocFirstByteTs} from './Common.js';\nimport {\n type Checklist,\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n InsightWarning,\n type PartialInsightModel,\n} from './types.js';\n\nexport const UIStrings = {\n /**\n * @description Title of an insight that provides details about the LCP metric, and the network requests necessary to load it. Details how the LCP request was discoverable - in other words, the path necessary to load it (ex: network requests, JavaScript)\n */\n title: 'LCP request discovery',\n /**\n * @description Description of an insight that provides details about the LCP metric, and the network requests necessary to load it.\n */\n description:\n '[Optimize LCP](https://developer.chrome.com/docs/performance/insights/lcp-discovery) by making the LCP image discoverable from the HTML immediately, and avoiding lazy-loading',\n /**\n * @description Text to tell the user how long after the earliest discovery time their LCP element loaded.\n * @example {401ms} PH1\n */\n lcpLoadDelay: 'LCP image loaded {PH1} after earliest start point.',\n /**\n * @description Text to tell the user that a fetchpriority property value of \"high\" is applied to the LCP request.\n */\n fetchPriorityApplied: 'fetchpriority=high applied',\n /**\n * @description Text to tell the user that a fetchpriority property value of \"high\" should be applied to the LCP request.\n */\n fetchPriorityShouldBeApplied: 'fetchpriority=high should be applied',\n /**\n * @description Text to tell the user that a fetchpriority property value of \"high\" should be applied to the preload request that loads the LCP image.\n */\n fetchPriorityShouldBeAppliedToImagePreload: 'fetchpriority=high should be applied to the image preload request',\n /**\n * @description Text to tell the user that the LCP request is discoverable in the initial document.\n */\n requestDiscoverable: 'Request is discoverable in initial document',\n /**\n * @description Text to tell the user that LCP resources should avoid using loading=lazy.\n */\n lazyLoadNotApplied: 'LCP resources should not use loading=lazy',\n /**\n * @description Text status indicating that the the Largest Contentful Paint (LCP) metric timing was not found. \"LCP\" is an acronym and should not be translated.\n */\n noLcp: 'No LCP detected',\n /**\n * @description Text status indicating that the Largest Contentful Paint (LCP) metric was text rather than an image. \"LCP\" is an acronym and should not be translated.\n */\n noLcpResource: 'No LCP resource detected because the LCP is not an image',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/LCPDiscovery.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport function isLCPDiscoveryInsight(model: InsightModel): model is LCPDiscoveryInsightModel {\n return model.insightKey === 'LCPDiscovery';\n}\nexport type LCPDiscoveryInsightModel = InsightModel<typeof UIStrings, {\n lcpEvent?: Types.Events.AnyLargestContentfulPaintCandidate,\n /** The network request for the LCP image, if there was one. */\n lcpRequest?: Types.Events.SyntheticNetworkRequest,\n earliestDiscoveryTimeTs?: Types.Timing.Micro,\n checklist?: Checklist<'priorityHinted'|'requestDiscoverable'|'eagerlyLoaded'>,\n}>;\n\nfunction finalize(partialModel: PartialInsightModel<LCPDiscoveryInsightModel>): LCPDiscoveryInsightModel {\n const relatedEvents = partialModel.lcpEvent && partialModel.lcpRequest ?\n // TODO: add entire request initiator chain?\n [partialModel.lcpEvent, partialModel.lcpRequest] :\n [];\n return {\n insightKey: InsightKeys.LCP_DISCOVERY,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n docs: 'https://developer.chrome.com/docs/performance/insights/lcp-discovery',\n category: InsightCategory.LCP,\n state: partialModel.lcpRequest && partialModel.checklist &&\n (!partialModel.checklist.eagerlyLoaded.value || !partialModel.checklist.requestDiscoverable.value ||\n !partialModel.checklist.priorityHinted.value) ?\n 'fail' :\n 'pass',\n ...partialModel,\n relatedEvents,\n };\n}\n\nexport function generateInsight(\n data: Handlers.Types.HandlerData, context: InsightSetContext): LCPDiscoveryInsightModel {\n if (!context.navigation) {\n return finalize({});\n }\n\n const networkRequests = data.NetworkRequests;\n\n const frameMetrics = data.PageLoadMetrics.metricScoresByFrameId.get(context.frameId);\n if (!frameMetrics) {\n throw new Error('no frame metrics');\n }\n\n const navMetrics = frameMetrics.get(context.navigation);\n if (!navMetrics) {\n throw new Error('no navigation metrics');\n }\n const metricScore = navMetrics.get(Handlers.ModelHandlers.PageLoadMetrics.MetricName.LCP);\n const lcpEvent = metricScore?.event;\n if (!lcpEvent || !Types.Events.isAnyLargestContentfulPaintCandidate(lcpEvent)) {\n return finalize({warnings: [InsightWarning.NO_LCP]});\n }\n\n const docRequest = networkRequests.byId.get(context.navigationId);\n if (!docRequest) {\n return finalize({warnings: [InsightWarning.NO_DOCUMENT_REQUEST]});\n }\n\n const lcpRequest = data.LargestImagePaint.lcpRequestByNavigationId.get(context.navigationId);\n if (!lcpRequest) {\n return finalize({lcpEvent});\n }\n\n const initiatorUrl = lcpRequest.args.data.initiator?.url;\n const initiatedByMainDoc =\n lcpRequest?.args.data.initiator?.type === 'parser' && docRequest.args.data.url === initiatorUrl;\n const imgPreloadedOrFoundInHTML = lcpRequest?.args.data.isLinkPreload || initiatedByMainDoc;\n\n const imageFetchPriorityHint = lcpRequest?.args.data.fetchPriorityHint;\n // This is the earliest discovery time an LCP request could have - it's TTFB (as an absolute timestamp).\n const earliestDiscoveryTime = calculateDocFirstByteTs(docRequest);\n\n const priorityHintFound = imageFetchPriorityHint === 'high';\n const missingPriorityHintLabel = lcpRequest.args.data.isLinkPreload ?\n i18nString(UIStrings.fetchPriorityShouldBeAppliedToImagePreload) :\n i18nString(UIStrings.fetchPriorityShouldBeApplied);\n // A lazy-loaded LCP image can still be eagerly loaded when its request is\n // initiated by a preload.\n const lcpNotLazyLoaded = lcpEvent.args.data?.loadingAttr !== 'lazy' || lcpRequest.args.data.isLinkPreload;\n\n return finalize({\n lcpEvent,\n lcpRequest,\n earliestDiscoveryTimeTs: earliestDiscoveryTime ? Types.Timing.Micro(earliestDiscoveryTime) : undefined,\n checklist: {\n priorityHinted: {\n label: priorityHintFound ? i18nString(UIStrings.fetchPriorityApplied) : missingPriorityHintLabel,\n value: priorityHintFound\n },\n requestDiscoverable: {label: i18nString(UIStrings.requestDiscoverable), value: imgPreloadedOrFoundInHTML},\n eagerlyLoaded: {label: i18nString(UIStrings.lazyLoadNotApplied), value: lcpNotLazyLoaded},\n },\n });\n}\n\ninterface LCPImageDiscoveryData {\n checklist: Exclude<LCPDiscoveryInsightModel['checklist'], undefined>;\n request: Types.Events.SyntheticNetworkRequest;\n discoveryDelay: Types.Timing.Micro|null;\n estimatedSavings: Types.Timing.Milli|null;\n}\n\n/**\n * TODO: this extra transformation (getImageData) should not be necessary.\n */\nexport function getImageData(model: LCPDiscoveryInsightModel): LCPImageDiscoveryData|null {\n if (!model.lcpRequest || !model.checklist) {\n return null;\n }\n\n const shouldIncreasePriorityHint = !model.checklist.priorityHinted.value;\n const shouldPreloadImage = !model.checklist.requestDiscoverable.value;\n const shouldRemoveLazyLoading = !model.checklist.eagerlyLoaded.value;\n\n const imageLCP = shouldIncreasePriorityHint !== undefined && shouldPreloadImage !== undefined &&\n shouldRemoveLazyLoading !== undefined;\n\n // Shouldn't render anything if lcp insight is null or lcp is text.\n if (!imageLCP) {\n return null;\n }\n\n const data: LCPImageDiscoveryData = {\n checklist: model.checklist,\n request: model.lcpRequest,\n discoveryDelay: null,\n estimatedSavings: model.metricSavings?.LCP ?? null,\n };\n\n if (model.earliestDiscoveryTimeTs && model.lcpRequest) {\n const discoveryDelay = model.lcpRequest.ts - model.earliestDiscoveryTimeTs;\n data.discoveryDelay = Types.Timing.Micro(discoveryDelay);\n }\n\n return data;\n}\n\nexport function createOverlays(model: LCPDiscoveryInsightModel): Types.Overlays.Overlay[] {\n const imageResults = getImageData(model);\n if (!imageResults?.discoveryDelay) {\n return [];\n }\n\n const delay = Helpers.Timing.traceWindowFromMicroSeconds(\n Types.Timing.Micro(imageResults.request.ts - imageResults.discoveryDelay),\n imageResults.request.ts,\n );\n\n return [\n {\n type: 'ENTRY_OUTLINE',\n entry: imageResults.request,\n outlineReason: 'ERROR',\n },\n {\n type: 'CANDY_STRIPED_TIME_RANGE',\n bounds: delay,\n entry: imageResults.request,\n },\n {\n type: 'TIMESPAN_BREAKDOWN',\n sections: [{\n bounds: delay,\n // This is overridden in the component.\n label: `${imageResults.discoveryDelay} microseconds`,\n showDuration: false,\n }],\n entry: imageResults.request,\n renderLocation: 'ABOVE_EVENT',\n },\n ];\n}\n"]}
@@ -9,7 +9,7 @@ export declare const UIStrings: {
9
9
  /**
10
10
  * @description Description of an insight that identifies polyfills for modern JavaScript features, and recommends their removal.
11
11
  */
12
- readonly description: "Polyfills and transforms enable older browsers to use new JavaScript features. However, many aren't necessary for modern browsers. Consider modifying your JavaScript build process to not transpile [Baseline](https://web.dev/articles/baseline-and-polyfills) features, unless you know you must support older browsers. [Learn why most sites can deploy ES6+ code without transpiling](https://philipwalton.com/articles/the-state-of-es5-on-the-web/)";
12
+ readonly description: "Polyfills and transforms enable older browsers to use new JavaScript features. However, many aren't necessary for modern browsers. Consider modifying your JavaScript build process to not transpile [Baseline](https://web.dev/articles/baseline-and-polyfills) features, unless you know you must support older browsers. [Learn why most sites can deploy ES6+ code without transpiling](https://developer.chrome.com/docs/performance/insights/legacy-javascript)";
13
13
  /** Label for a column in a data table; entries will be the individual JavaScript scripts. */
14
14
  readonly columnScript: "Script";
15
15
  /** Label for a column in a data table; entries will be the number of wasted bytes (aka the estimated savings in terms of bytes). */
@@ -15,7 +15,7 @@ export const UIStrings = {
15
15
  /**
16
16
  * @description Description of an insight that identifies polyfills for modern JavaScript features, and recommends their removal.
17
17
  */
18
- description: 'Polyfills and transforms enable older browsers to use new JavaScript features. However, many aren\'t necessary for modern browsers. Consider modifying your JavaScript build process to not transpile [Baseline](https://web.dev/articles/baseline-and-polyfills) features, unless you know you must support older browsers. [Learn why most sites can deploy ES6+ code without transpiling](https://philipwalton.com/articles/the-state-of-es5-on-the-web/)',
18
+ description: 'Polyfills and transforms enable older browsers to use new JavaScript features. However, many aren\'t necessary for modern browsers. Consider modifying your JavaScript build process to not transpile [Baseline](https://web.dev/articles/baseline-and-polyfills) features, unless you know you must support older browsers. [Learn why most sites can deploy ES6+ code without transpiling](https://developer.chrome.com/docs/performance/insights/legacy-javascript)',
19
19
  /** Label for a column in a data table; entries will be the individual JavaScript scripts. */
20
20
  columnScript: 'Script',
21
21
  /** Label for a column in a data table; entries will be the number of wasted bytes (aka the estimated savings in terms of bytes). */
@@ -31,6 +31,7 @@ function finalize(partialModel) {
31
31
  strings: UIStrings,
32
32
  title: i18nString(UIStrings.title),
33
33
  description: i18nString(UIStrings.description),
34
+ docs: 'https://developer.chrome.com/docs/performance/insights/legacy-javascript',
34
35
  category: InsightCategory.ALL,
35
36
  state: requests.length ? 'fail' : 'pass',
36
37
  relatedEvents: [...new Set(requests)],
@@ -1 +1 @@
1
- {"version":3,"file":"LegacyJavaScript.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/LegacyJavaScript.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AACnD,OAAO,KAAK,mBAAmB,MAAM,6DAA6D,CAAC;AAEnG,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AAGjD,OAAO,EAAC,iCAAiC,EAAE,2BAA2B,EAAC,MAAM,aAAa,CAAC;AAC3F,OAAO,EACL,eAAe,EACf,WAAW,GAIZ,MAAM,YAAY,CAAC;AAEpB,MAAM,EAAC,sBAAsB,EAAC,GAAG,mBAAmB,CAAC,gBAAgB,CAAC;AAEtE,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,mBAAmB;IAC1B;;OAEG;IACH,WAAW,EACP,8bAA8b;IAClc,6FAA6F;IAC7F,YAAY,EAAE,QAAQ;IACtB,oIAAoI;IACpI,iBAAiB,EAAE,cAAc;CACzB,CAAC;AAEX,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,2CAA2C,EAAE,SAAS,CAAC,CAAC;AACjG,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAmB7E,MAAM,cAAc,GAAG,IAAI,CAAC;AAE5B,SAAS,QAAQ,CAA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B,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC;IAEhH,OAAO,QAAQ,CAAC;QACd,uBAAuB,EAAE,MAAM;QAC/B,aAAa,EAAE,2BAA2B,CAAC,sBAAsB,EAAE,OAAO,CAAC;QAC3E,WAAW,EAAE,sBAAsB,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,CAAC,GAAG,GAAG,GAAG,EAAE,CAAC,CAAC;KAChF,CAAC,CAAC;AACL,CAAC;AACD,MAAM,UAAU,cAAc,CAAC,KAAmC;IAChE,OAAO,CAAC,GAAG,KAAK,CAAC,uBAAuB,CAAC,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;QAC5G,OAAO;YACL,IAAI,EAAE,eAAe;YACrB,KAAK,EAAE,OAAO;YACd,aAAa,EAAE,OAAO;SACvB,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2025 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as i18n from '../../../core/i18n/i18n.js';\nimport * as LegacyJavaScriptLib from '../../../third_party/legacy-javascript/legacy-javascript.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport type * as Types from '../types/types.js';\n\nimport {estimateCompressionRatioForScript, metricSavingsForWastedBytes} from './Common.js';\nimport {\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n type PartialInsightModel,\n} from './types.js';\n\nconst {detectLegacyJavaScript} = LegacyJavaScriptLib.LegacyJavaScript;\n\nexport const UIStrings = {\n /**\n * @description Title of an insight that identifies polyfills for modern JavaScript features, and recommends their removal.\n */\n title: 'Legacy JavaScript',\n /**\n * @description Description of an insight that identifies polyfills for modern JavaScript features, and recommends their removal.\n */\n description:\n 'Polyfills and transforms enable older browsers to use new JavaScript features. However, many aren\\'t necessary for modern browsers. Consider modifying your JavaScript build process to not transpile [Baseline](https://web.dev/articles/baseline-and-polyfills) features, unless you know you must support older browsers. [Learn why most sites can deploy ES6+ code without transpiling](https://philipwalton.com/articles/the-state-of-es5-on-the-web/)',\n /** Label for a column in a data table; entries will be the individual JavaScript scripts. */\n columnScript: 'Script',\n /** Label for a column in a data table; entries will be the number of wasted bytes (aka the estimated savings in terms of bytes). */\n columnWastedBytes: 'Wasted bytes',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/LegacyJavaScript.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport interface PatternMatchResult {\n name: string;\n line: number;\n column: number;\n}\n\ninterface LegacyJavaScriptResult {\n matches: PatternMatchResult[];\n estimatedByteSavings: number;\n}\n\ntype LegacyJavaScriptResults = Map<Handlers.ModelHandlers.Scripts.Script, LegacyJavaScriptResult>;\n\nexport type LegacyJavaScriptInsightModel = InsightModel<typeof UIStrings, {\n legacyJavaScriptResults: LegacyJavaScriptResults,\n}>;\n\nconst BYTE_THRESHOLD = 5000;\n\nfunction finalize(partialModel: PartialInsightModel<LegacyJavaScriptInsightModel>): LegacyJavaScriptInsightModel {\n const requests = [...partialModel.legacyJavaScriptResults.keys()].map(script => script.request).filter(e => !!e);\n\n return {\n insightKey: InsightKeys.LEGACY_JAVASCRIPT,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.ALL,\n state: requests.length ? 'fail' : 'pass',\n relatedEvents: [...new Set(requests)],\n ...partialModel,\n };\n}\n\nexport function isLegacyJavaScript(model: InsightModel): model is LegacyJavaScriptInsightModel {\n return model.insightKey === InsightKeys.LEGACY_JAVASCRIPT;\n}\n\nexport function generateInsight(\n data: Handlers.Types.HandlerData, context: InsightSetContext): LegacyJavaScriptInsightModel {\n const scripts = data.Scripts.scripts.filter(script => {\n if (script.frame !== context.frameId) {\n return false;\n }\n\n if (script.url?.startsWith('chrome-extension://')) {\n return false;\n }\n\n return Helpers.Timing.timestampIsInBounds(context.bounds, script.ts) ||\n (script.request && Helpers.Timing.eventIsInBounds(script.request, context.bounds));\n });\n\n const legacyJavaScriptResults: LegacyJavaScriptResults = new Map();\n const wastedBytesByRequestId = new Map<string, number>();\n\n for (const script of scripts) {\n if (!script.content || script.content.length < BYTE_THRESHOLD) {\n continue;\n }\n\n const result = detectLegacyJavaScript(script.content, script.sourceMap);\n if (result.estimatedByteSavings < BYTE_THRESHOLD) {\n continue;\n }\n\n // Translate from resource size to transfer size.\n const compressionRatio = estimateCompressionRatioForScript(script);\n const transferSize = Math.round(result.estimatedByteSavings * compressionRatio);\n result.estimatedByteSavings = transferSize;\n\n legacyJavaScriptResults.set(script, result);\n\n if (script.request) {\n const requestId = script.request.args.data.requestId;\n wastedBytesByRequestId.set(requestId, transferSize);\n }\n }\n\n const sorted =\n new Map([...legacyJavaScriptResults].sort((a, b) => b[1].estimatedByteSavings - a[1].estimatedByteSavings));\n\n return finalize({\n legacyJavaScriptResults: sorted,\n metricSavings: metricSavingsForWastedBytes(wastedBytesByRequestId, context),\n wastedBytes: wastedBytesByRequestId.values().reduce((acc, cur) => acc + cur, 0),\n });\n}\nexport function createOverlays(model: LegacyJavaScriptInsightModel): Types.Overlays.Overlay[] {\n return [...model.legacyJavaScriptResults.keys()].map(script => script.request).filter(e => !!e).map(request => {\n return {\n type: 'ENTRY_OUTLINE',\n entry: request,\n outlineReason: 'ERROR',\n };\n });\n}\n"]}
1
+ {"version":3,"file":"LegacyJavaScript.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/LegacyJavaScript.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,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CAAC,uBAAuB,CAAC,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE;QAC5G,OAAO;YACL,IAAI,EAAE,eAAe;YACrB,KAAK,EAAE,OAAO;YACd,aAAa,EAAE,OAAO;SACvB,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2025 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nimport * as i18n from '../../../core/i18n/i18n.js';\nimport * as LegacyJavaScriptLib from '../../../third_party/legacy-javascript/legacy-javascript.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport type * as Types from '../types/types.js';\n\nimport {estimateCompressionRatioForScript, metricSavingsForWastedBytes} from './Common.js';\nimport {\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n type PartialInsightModel,\n} from './types.js';\n\nconst {detectLegacyJavaScript} = LegacyJavaScriptLib.LegacyJavaScript;\n\nexport const UIStrings = {\n /**\n * @description Title of an insight that identifies polyfills for modern JavaScript features, and recommends their removal.\n */\n title: 'Legacy JavaScript',\n /**\n * @description Description of an insight that identifies polyfills for modern JavaScript features, and recommends their removal.\n */\n description:\n 'Polyfills and transforms enable older browsers to use new JavaScript features. However, many aren\\'t necessary for modern browsers. Consider modifying your JavaScript build process to not transpile [Baseline](https://web.dev/articles/baseline-and-polyfills) features, unless you know you must support older browsers. [Learn why most sites can deploy ES6+ code without transpiling](https://developer.chrome.com/docs/performance/insights/legacy-javascript)',\n /** Label for a column in a data table; entries will be the individual JavaScript scripts. */\n columnScript: 'Script',\n /** Label for a column in a data table; entries will be the number of wasted bytes (aka the estimated savings in terms of bytes). */\n columnWastedBytes: 'Wasted bytes',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/LegacyJavaScript.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport interface PatternMatchResult {\n name: string;\n line: number;\n column: number;\n}\n\ninterface LegacyJavaScriptResult {\n matches: PatternMatchResult[];\n estimatedByteSavings: number;\n}\n\ntype LegacyJavaScriptResults = Map<Handlers.ModelHandlers.Scripts.Script, LegacyJavaScriptResult>;\n\nexport type LegacyJavaScriptInsightModel = InsightModel<typeof UIStrings, {\n legacyJavaScriptResults: LegacyJavaScriptResults,\n}>;\n\nconst BYTE_THRESHOLD = 5000;\n\nfunction finalize(partialModel: PartialInsightModel<LegacyJavaScriptInsightModel>): LegacyJavaScriptInsightModel {\n const requests = [...partialModel.legacyJavaScriptResults.keys()].map(script => script.request).filter(e => !!e);\n\n return {\n insightKey: InsightKeys.LEGACY_JAVASCRIPT,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n docs: 'https://developer.chrome.com/docs/performance/insights/legacy-javascript',\n category: InsightCategory.ALL,\n state: requests.length ? 'fail' : 'pass',\n relatedEvents: [...new Set(requests)],\n ...partialModel,\n };\n}\n\nexport function isLegacyJavaScript(model: InsightModel): model is LegacyJavaScriptInsightModel {\n return model.insightKey === InsightKeys.LEGACY_JAVASCRIPT;\n}\n\nexport function generateInsight(\n data: Handlers.Types.HandlerData, context: InsightSetContext): LegacyJavaScriptInsightModel {\n const scripts = data.Scripts.scripts.filter(script => {\n if (script.frame !== context.frameId) {\n return false;\n }\n\n if (script.url?.startsWith('chrome-extension://')) {\n return false;\n }\n\n return Helpers.Timing.timestampIsInBounds(context.bounds, script.ts) ||\n (script.request && Helpers.Timing.eventIsInBounds(script.request, context.bounds));\n });\n\n const legacyJavaScriptResults: LegacyJavaScriptResults = new Map();\n const wastedBytesByRequestId = new Map<string, number>();\n\n for (const script of scripts) {\n if (!script.content || script.content.length < BYTE_THRESHOLD) {\n continue;\n }\n\n const result = detectLegacyJavaScript(script.content, script.sourceMap);\n if (result.estimatedByteSavings < BYTE_THRESHOLD) {\n continue;\n }\n\n // Translate from resource size to transfer size.\n const compressionRatio = estimateCompressionRatioForScript(script);\n const transferSize = Math.round(result.estimatedByteSavings * compressionRatio);\n result.estimatedByteSavings = transferSize;\n\n legacyJavaScriptResults.set(script, result);\n\n if (script.request) {\n const requestId = script.request.args.data.requestId;\n wastedBytesByRequestId.set(requestId, transferSize);\n }\n }\n\n const sorted =\n new Map([...legacyJavaScriptResults].sort((a, b) => b[1].estimatedByteSavings - a[1].estimatedByteSavings));\n\n return finalize({\n legacyJavaScriptResults: sorted,\n metricSavings: metricSavingsForWastedBytes(wastedBytesByRequestId, context),\n wastedBytes: wastedBytesByRequestId.values().reduce((acc, cur) => acc + cur, 0),\n });\n}\nexport function createOverlays(model: LegacyJavaScriptInsightModel): Types.Overlays.Overlay[] {\n return [...model.legacyJavaScriptResults.keys()].map(script => script.request).filter(e => !!e).map(request => {\n return {\n type: 'ENTRY_OUTLINE',\n entry: request,\n outlineReason: 'ERROR',\n };\n });\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  export * as Cache from './Cache.js';
2
+ export * as CharacterSet from './CharacterSet.js';
2
3
  export * as CLSCulprits from './CLSCulprits.js';
3
4
  export * as DocumentLatency from './DocumentLatency.js';
4
5
  export * as DOMSize from './DOMSize.js';
@@ -2,6 +2,7 @@
2
2
  // Use of this source code is governed by a BSD-style license that can be
3
3
  // found in the LICENSE file.
4
4
  export * as Cache from './Cache.js';
5
+ export * as CharacterSet from './CharacterSet.js';
5
6
  export * as CLSCulprits from './CLSCulprits.js';
6
7
  export * as DocumentLatency from './DocumentLatency.js';
7
8
  export * as DOMSize from './DOMSize.js';
@@ -1 +1 @@
1
- {"version":3,"file":"Models.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/Models.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,WAAW,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,eAAe,MAAM,sBAAsB,CAAC;AACxD,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AACxC,OAAO,KAAK,oBAAoB,MAAM,2BAA2B,CAAC;AAClE,OAAO,KAAK,WAAW,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,aAAa,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,gBAAgB,MAAM,uBAAuB,CAAC;AAC1D,OAAO,KAAK,UAAU,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,qBAAqB,MAAM,4BAA4B,CAAC;AACpE,OAAO,KAAK,cAAc,MAAM,qBAAqB,CAAC;AACtD,OAAO,KAAK,eAAe,MAAM,sBAAsB,CAAC;AACxD,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nexport * as Cache from './Cache.js';\nexport * as CLSCulprits from './CLSCulprits.js';\nexport * as DocumentLatency from './DocumentLatency.js';\nexport * as DOMSize from './DOMSize.js';\nexport * as DuplicatedJavaScript from './DuplicatedJavaScript.js';\nexport * as FontDisplay from './FontDisplay.js';\nexport * as ForcedReflow from './ForcedReflow.js';\nexport * as ImageDelivery from './ImageDelivery.js';\nexport * as INPBreakdown from './INPBreakdown.js';\nexport * as LCPBreakdown from './LCPBreakdown.js';\nexport * as LCPDiscovery from './LCPDiscovery.js';\nexport * as LegacyJavaScript from './LegacyJavaScript.js';\nexport * as ModernHTTP from './ModernHTTP.js';\nexport * as NetworkDependencyTree from './NetworkDependencyTree.js';\nexport * as RenderBlocking from './RenderBlocking.js';\nexport * as SlowCSSSelector from './SlowCSSSelector.js';\nexport * as ThirdParties from './ThirdParties.js';\nexport * as Viewport from './Viewport.js';\n"]}
1
+ {"version":3,"file":"Models.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/Models.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,WAAW,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,eAAe,MAAM,sBAAsB,CAAC;AACxD,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AACxC,OAAO,KAAK,oBAAoB,MAAM,2BAA2B,CAAC;AAClE,OAAO,KAAK,WAAW,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,aAAa,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,gBAAgB,MAAM,uBAAuB,CAAC;AAC1D,OAAO,KAAK,UAAU,MAAM,iBAAiB,CAAC;AAC9C,OAAO,KAAK,qBAAqB,MAAM,4BAA4B,CAAC;AACpE,OAAO,KAAK,cAAc,MAAM,qBAAqB,CAAC;AACtD,OAAO,KAAK,eAAe,MAAM,sBAAsB,CAAC;AACxD,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors\n// Use of this source code is governed by a BSD-style license that can be\n// found in the LICENSE file.\n\nexport * as Cache from './Cache.js';\nexport * as CharacterSet from './CharacterSet.js';\nexport * as CLSCulprits from './CLSCulprits.js';\nexport * as DocumentLatency from './DocumentLatency.js';\nexport * as DOMSize from './DOMSize.js';\nexport * as DuplicatedJavaScript from './DuplicatedJavaScript.js';\nexport * as FontDisplay from './FontDisplay.js';\nexport * as ForcedReflow from './ForcedReflow.js';\nexport * as ImageDelivery from './ImageDelivery.js';\nexport * as INPBreakdown from './INPBreakdown.js';\nexport * as LCPBreakdown from './LCPBreakdown.js';\nexport * as LCPDiscovery from './LCPDiscovery.js';\nexport * as LegacyJavaScript from './LegacyJavaScript.js';\nexport * as ModernHTTP from './ModernHTTP.js';\nexport * as NetworkDependencyTree from './NetworkDependencyTree.js';\nexport * as RenderBlocking from './RenderBlocking.js';\nexport * as SlowCSSSelector from './SlowCSSSelector.js';\nexport * as ThirdParties from './ThirdParties.js';\nexport * as Viewport from './Viewport.js';\n"]}
@@ -10,7 +10,7 @@ export declare const UIStrings: {
10
10
  /**
11
11
  * @description Description of an insight that recommends recommends using HTTP/2 over HTTP/1.1 because of the performance benefits. "HTTP" should not be translated.
12
12
  */
13
- readonly description: "HTTP/2 and HTTP/3 offer many benefits over HTTP/1.1, such as multiplexing. [Learn more about using modern HTTP](https://developer.chrome.com/docs/lighthouse/best-practices/uses-http2/).";
13
+ readonly description: "HTTP/2 and HTTP/3 offer many benefits over HTTP/1.1, such as multiplexing. [Learn more about using modern HTTP](https://developer.chrome.com/docs/performance/insights/modern-http).";
14
14
  /**
15
15
  * @description Column header for a table where each cell represents a network request.
16
16
  */
@@ -14,7 +14,7 @@ export const UIStrings = {
14
14
  /**
15
15
  * @description Description of an insight that recommends recommends using HTTP/2 over HTTP/1.1 because of the performance benefits. "HTTP" should not be translated.
16
16
  */
17
- description: 'HTTP/2 and HTTP/3 offer many benefits over HTTP/1.1, such as multiplexing. [Learn more about using modern HTTP](https://developer.chrome.com/docs/lighthouse/best-practices/uses-http2/).',
17
+ description: 'HTTP/2 and HTTP/3 offer many benefits over HTTP/1.1, such as multiplexing. [Learn more about using modern HTTP](https://developer.chrome.com/docs/performance/insights/modern-http).',
18
18
  /**
19
19
  * @description Column header for a table where each cell represents a network request.
20
20
  */
@@ -169,6 +169,7 @@ function finalize(partialModel) {
169
169
  strings: UIStrings,
170
170
  title: i18nString(UIStrings.title),
171
171
  description: i18nString(UIStrings.description),
172
+ docs: 'https://developer.chrome.com/docs/performance/insights/modern-http',
172
173
  category: InsightCategory.LCP,
173
174
  state: partialModel.http1Requests.length > 0 ? 'fail' : 'pass',
174
175
  ...partialModel,