@paulirish/trace_engine 0.0.53 → 0.0.54

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 (158) hide show
  1. package/.tmp/tsbuildinfo/analyze-inspector-issues.d.mts +13 -0
  2. package/.tmp/tsbuildinfo/analyze-inspector-issues.d.mts.map +1 -0
  3. package/.tmp/tsbuildinfo/tsconfig.tsbuildinfo +1 -1
  4. package/analyze-inspector-issues.mjs +60 -0
  5. package/core/common/common.d.ts +1 -0
  6. package/core/common/common.js +1 -0
  7. package/core/host/host.d.ts +1 -0
  8. package/core/host/host.js +1 -0
  9. package/core/platform/ServerTiming.d.ts +31 -0
  10. package/core/platform/ServerTiming.js +212 -0
  11. package/core/platform/ServerTiming.js.map +1 -0
  12. package/core/root/root.d.ts +1 -0
  13. package/core/root/root.js +1 -0
  14. package/core/sdk/sdk.d.ts +1 -0
  15. package/core/sdk/sdk.js +1 -0
  16. package/models/issues_manager/CheckFormsIssuesTrigger.d.ts +1 -0
  17. package/models/issues_manager/CheckFormsIssuesTrigger.js +1 -0
  18. package/models/issues_manager/ContrastCheckTrigger.d.ts +1 -0
  19. package/models/issues_manager/ContrastCheckTrigger.js +1 -0
  20. package/models/issues_manager/DeprecationIssue.d.ts +1 -0
  21. package/models/issues_manager/DeprecationIssue.js +1 -0
  22. package/models/issues_manager/IssueResolver.d.ts +1 -0
  23. package/models/issues_manager/IssueResolver.js +1 -0
  24. package/models/issues_manager/RelatedIssue.d.ts +1 -0
  25. package/models/issues_manager/RelatedIssue.js +1 -0
  26. package/models/issues_manager/SourceFrameIssuesManager.d.ts +1 -0
  27. package/models/issues_manager/SourceFrameIssuesManager.js +1 -0
  28. package/models/trace/LanternComputationData.js +2 -2
  29. package/models/trace/LanternComputationData.js.map +1 -1
  30. package/models/trace/ModelImpl.js +1 -1
  31. package/models/trace/ModelImpl.js.map +1 -1
  32. package/models/trace/extras/Metadata.js +2 -2
  33. package/models/trace/extras/Metadata.js.map +1 -1
  34. package/models/trace/extras/ThirdParties.js +1 -1
  35. package/models/trace/extras/ThirdParties.js.map +1 -1
  36. package/models/trace/extras/TimelineJSProfile.d.ts +13 -0
  37. package/models/trace/extras/TimelineJSProfile.js +55 -0
  38. package/models/trace/extras/TimelineJSProfile.js.map +1 -0
  39. package/models/trace/extras/TraceFilter.js +2 -2
  40. package/models/trace/extras/TraceFilter.js.map +1 -1
  41. package/models/trace/extras/URLForEntry.d.ts +12 -0
  42. package/models/trace/extras/URLForEntry.js +43 -0
  43. package/models/trace/extras/URLForEntry.js.map +1 -0
  44. package/models/trace/extras/extras.d.ts +4 -1
  45. package/models/trace/extras/extras.js +4 -1
  46. package/models/trace/handlers/AuctionWorkletsHandler.js +5 -5
  47. package/models/trace/handlers/AuctionWorkletsHandler.js.map +1 -1
  48. package/models/trace/handlers/ExtensionTraceDataHandler.js +4 -4
  49. package/models/trace/handlers/ExtensionTraceDataHandler.js.map +1 -1
  50. package/models/trace/handlers/FlowsHandler.js +3 -3
  51. package/models/trace/handlers/FlowsHandler.js.map +1 -1
  52. package/models/trace/handlers/FramesHandler.js +7 -7
  53. package/models/trace/handlers/FramesHandler.js.map +1 -1
  54. package/models/trace/handlers/LargestImagePaintHandler.js +2 -2
  55. package/models/trace/handlers/LargestImagePaintHandler.js.map +1 -1
  56. package/models/trace/handlers/LayoutShiftsHandler.d.ts +1 -1
  57. package/models/trace/handlers/LayoutShiftsHandler.js +18 -10
  58. package/models/trace/handlers/LayoutShiftsHandler.js.map +1 -1
  59. package/models/trace/handlers/MetaHandler.js +7 -7
  60. package/models/trace/handlers/MetaHandler.js.map +1 -1
  61. package/models/trace/handlers/NetworkRequestsHandler.js +3 -3
  62. package/models/trace/handlers/NetworkRequestsHandler.js.map +1 -1
  63. package/models/trace/handlers/PageLoadMetricsHandler.d.ts +2 -2
  64. package/models/trace/handlers/PageLoadMetricsHandler.js +54 -25
  65. package/models/trace/handlers/PageLoadMetricsHandler.js.map +1 -1
  66. package/models/trace/handlers/RendererHandler.js +1 -1
  67. package/models/trace/handlers/RendererHandler.js.map +1 -1
  68. package/models/trace/handlers/ServerTimingsHandler.d.ts +9 -0
  69. package/models/trace/handlers/ServerTimingsHandler.js +106 -0
  70. package/models/trace/handlers/ServerTimingsHandler.js.map +1 -0
  71. package/models/trace/handlers/Threads.d.ts +1 -1
  72. package/models/trace/handlers/Threads.js +17 -7
  73. package/models/trace/handlers/Threads.js.map +1 -1
  74. package/models/trace/handlers/UserInteractionsHandler.js +4 -3
  75. package/models/trace/handlers/UserInteractionsHandler.js.map +1 -1
  76. package/models/trace/handlers/WarningsHandler.js +2 -2
  77. package/models/trace/handlers/WarningsHandler.js.map +1 -1
  78. package/models/trace/helpers/SamplesIntegrator.d.ts +1 -1
  79. package/models/trace/helpers/SamplesIntegrator.js +19 -12
  80. package/models/trace/helpers/SamplesIntegrator.js.map +1 -1
  81. package/models/trace/helpers/Trace.js +111 -111
  82. package/models/trace/helpers/Trace.js.map +1 -1
  83. package/models/trace/insights/CLSCulprits.d.ts +1 -1
  84. package/models/trace/insights/CLSCulprits.js +43 -22
  85. package/models/trace/insights/CLSCulprits.js.map +1 -1
  86. package/models/trace/insights/Common.js +4 -3
  87. package/models/trace/insights/Common.js.map +1 -1
  88. package/models/trace/insights/CumulativeLayoutShift.d.ts +57 -0
  89. package/models/trace/insights/CumulativeLayoutShift.js +335 -0
  90. package/models/trace/insights/CumulativeLayoutShift.js.map +1 -0
  91. package/models/trace/insights/DOMSize.js +3 -3
  92. package/models/trace/insights/DOMSize.js.map +1 -1
  93. package/models/trace/insights/DocumentLatency.js +2 -2
  94. package/models/trace/insights/DocumentLatency.js.map +1 -1
  95. package/models/trace/insights/DuplicatedJavaScript.js +2 -2
  96. package/models/trace/insights/DuplicatedJavaScript.js.map +1 -1
  97. package/models/trace/insights/FontDisplay.js +2 -2
  98. package/models/trace/insights/FontDisplay.js.map +1 -1
  99. package/models/trace/insights/ForcedReflow.js +2 -2
  100. package/models/trace/insights/ForcedReflow.js.map +1 -1
  101. package/models/trace/insights/ImageDelivery.js +2 -2
  102. package/models/trace/insights/ImageDelivery.js.map +1 -1
  103. package/models/trace/insights/InsightRunners.d.ts +9 -0
  104. package/models/trace/insights/InsightRunners.js +13 -0
  105. package/models/trace/insights/InsightRunners.js.map +1 -0
  106. package/models/trace/insights/InteractionToNextPaint.js +3 -3
  107. package/models/trace/insights/InteractionToNextPaint.js.map +1 -1
  108. package/models/trace/insights/LCPDiscovery.js +3 -3
  109. package/models/trace/insights/LCPDiscovery.js.map +1 -1
  110. package/models/trace/insights/LCPPhases.js +3 -3
  111. package/models/trace/insights/LCPPhases.js.map +1 -1
  112. package/models/trace/insights/LargestContentfulPaint.d.ts +38 -0
  113. package/models/trace/insights/LargestContentfulPaint.js +113 -0
  114. package/models/trace/insights/LargestContentfulPaint.js.map +1 -0
  115. package/models/trace/insights/LegacyJavaScript.js +2 -2
  116. package/models/trace/insights/LegacyJavaScript.js.map +1 -1
  117. package/models/trace/insights/ModernHTTP.js +2 -2
  118. package/models/trace/insights/ModernHTTP.js.map +1 -1
  119. package/models/trace/insights/NetworkDependencyTree.js +2 -2
  120. package/models/trace/insights/NetworkDependencyTree.js.map +1 -1
  121. package/models/trace/insights/RenderBlocking.js +3 -3
  122. package/models/trace/insights/RenderBlocking.js.map +1 -1
  123. package/models/trace/insights/SlowCSSSelector.js +2 -2
  124. package/models/trace/insights/SlowCSSSelector.js.map +1 -1
  125. package/models/trace/insights/ThirdParties.js +2 -2
  126. package/models/trace/insights/ThirdParties.js.map +1 -1
  127. package/models/trace/insights/ThirdPartyWeb.d.ts +13 -0
  128. package/models/trace/insights/ThirdPartyWeb.js +42 -0
  129. package/models/trace/insights/ThirdPartyWeb.js.map +1 -0
  130. package/models/trace/insights/Viewport.js +2 -2
  131. package/models/trace/insights/Viewport.js.map +1 -1
  132. package/models/trace/insights/types.d.ts +1 -1
  133. package/models/trace/insights/types.js +19 -0
  134. package/models/trace/insights/types.js.map +1 -1
  135. package/models/trace/root-causes/LayoutShift.d.ts +125 -0
  136. package/models/trace/root-causes/LayoutShift.js +519 -0
  137. package/models/trace/root-causes/LayoutShift.js.map +1 -0
  138. package/models/trace/root-causes/RootCauses.d.ts +15 -0
  139. package/models/trace/root-causes/RootCauses.js +12 -0
  140. package/models/trace/root-causes/RootCauses.js.map +1 -0
  141. package/models/trace/root-causes/bundle-tsconfig.json +1 -0
  142. package/models/trace/root-causes/devtools_entrypoint-bundle-typescript-tsconfig.json +42 -0
  143. package/models/trace/root-causes/root-causes-tsconfig.json +55 -0
  144. package/models/trace/root-causes/root-causes.d.ts +1 -0
  145. package/models/trace/root-causes/root-causes.js +5 -0
  146. package/models/trace/root-causes/root-causes.js.map +1 -0
  147. package/models/trace/types/File.d.ts +3 -3
  148. package/models/trace/types/File.js +28 -4
  149. package/models/trace/types/File.js.map +1 -1
  150. package/models/trace/types/TraceEvents.d.ts +6 -6
  151. package/models/trace/types/TraceEvents.js +373 -105
  152. package/models/trace/types/TraceEvents.js.map +1 -1
  153. package/package.json +1 -1
  154. package/test/test-trace-engine.mjs +77 -0
  155. package/third_party/marked/marked.d.ts +1 -0
  156. package/third_party/marked/marked.js +1 -0
  157. package/.tmp/tsbuildinfo/models/trace/extras/polyfills.d.ts +0 -4
  158. package/.tmp/tsbuildinfo/models/trace/extras/polyfills.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"DuplicatedJavaScript.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/DuplicatedJavaScript.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AACnD,OAAO,KAAK,MAAM,MAAM,qBAAqB,CAAC;AAE9C,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AAEjD,OAAO,EAAC,iCAAiC,EAAE,2BAA2B,EAAC,MAAM,aAAa,CAAC;AAC3F,OAAO,EACL,eAAe,GAKhB,MAA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K,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAC3C,MAAM,UAAU,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;YACjC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;gBAC/B,SAAS;YACX,CAAC;YAED,MAAM,YAAY,GAAG,UAAU,CAAC,cAAc,CAAC;YAC/C,MAAM,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC;YAChE,sBAAsB,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,sBAAsB,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC;QACrG,CAAC;IACH,CAAC;IAED,OAAO,QAAQ,CAAC;QACd,WAAW;QACX,+BAA+B;QAC/B,sBAAsB,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,sBAAsB,CAAC,CAAC;QAC5D,OAAO;QACP,eAAe,EAAE,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,YAAY;QACpF,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","sourcesContent":["// Copyright 2025 The Chromium Authors. All rights reserved.\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 Extras from '../extras/extras.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.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\nexport const UIStrings = {\n /**\n * @description Title of an insight that identifies multiple copies of the same JavaScript sources, and recommends removing the duplication.\n */\n title: 'Duplicated JavaScript',\n /**\n * @description Description of an insight that identifies multiple copies of the same JavaScript sources, and recommends removing the duplication.\n */\n description:\n 'Remove large, duplicate JavaScript modules from bundles to reduce unnecessary bytes consumed by network activity.',\n /** Label for a column in a data table; entries will be the locations of JavaScript or CSS code, e.g. the name of a Javascript package or module. */\n columnSource: 'Source',\n /** Label for a column in a data table; entries will be the number of wasted bytes due to duplication of a web resource. */\n columnDuplicatedBytes: 'Duplicated bytes',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/DuplicatedJavaScript.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport type DuplicatedJavaScriptInsightModel = InsightModel<typeof UIStrings, {\n duplication: Extras.ScriptDuplication.ScriptDuplication,\n duplicationGroupedByNodeModules: Extras.ScriptDuplication.ScriptDuplication,\n scriptsWithDuplication: Handlers.ModelHandlers.Scripts.Script[],\n scripts: Handlers.ModelHandlers.Scripts.Script[],\n mainDocumentUrl: string,\n}>;\n\nfunction finalize(partialModel: PartialInsightModel<DuplicatedJavaScriptInsightModel>):\n DuplicatedJavaScriptInsightModel {\n const requests = partialModel.scriptsWithDuplication.map(script => script.request).filter(e => !!e);\n\n return {\n insightKey: InsightKeys.DUPLICATE_JAVASCRIPT,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.LCP,\n state: Boolean(partialModel.duplication.values().next().value) ? 'fail' : 'pass',\n relatedEvents: [...new Set(requests)],\n ...partialModel,\n };\n}\n\nexport function generateInsight(\n parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): DuplicatedJavaScriptInsightModel {\n const scripts = parsedTrace.Scripts.scripts.filter(script => {\n if (!context.navigation) {\n return false;\n }\n\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 });\n\n const compressionRatios = new Map<string, number>();\n for (const script of scripts) {\n if (script.request) {\n compressionRatios.set(script.request.args.data.requestId, estimateCompressionRatioForScript(script));\n }\n }\n\n const {duplication, duplicationGroupedByNodeModules} =\n Extras.ScriptDuplication.computeScriptDuplication({scripts}, compressionRatios);\n const scriptsWithDuplication = [...duplication.values().flatMap(data => data.duplicates.map(d => d.script))];\n\n const wastedBytesByRequestId = new Map<string, number>();\n for (const {duplicates} of duplication.values()) {\n for (let i = 1; i < duplicates.length; i++) {\n const sourceData = duplicates[i];\n if (!sourceData.script.request) {\n continue;\n }\n\n const transferSize = sourceData.attributedSize;\n const requestId = sourceData.script.request.args.data.requestId;\n wastedBytesByRequestId.set(requestId, (wastedBytesByRequestId.get(requestId) || 0) + transferSize);\n }\n }\n\n return finalize({\n duplication,\n duplicationGroupedByNodeModules,\n scriptsWithDuplication: [...new Set(scriptsWithDuplication)],\n scripts,\n mainDocumentUrl: context.navigation?.args.data?.url ?? parsedTrace.Meta.mainFrameURL,\n metricSavings: metricSavingsForWastedBytes(wastedBytesByRequestId, context),\n wastedBytes: wastedBytesByRequestId.values().reduce((acc, cur) => acc + cur, 0),\n });\n}\n"]}
1
+ {"version":3,"file":"DuplicatedJavaScript.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/DuplicatedJavaScript.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AACnD,OAAO,KAAK,MAAM,MAAM,qBAAqB,CAAC;AAE9C,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AAEjD,OAAO,EAAC,iCAAiC,EAAE,2BAA2B,EAAC,MAAM,a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AAM,EAAC,UAAU,EAAC,IAAI,WAAW,CAAC,MAAM,EAAE,EAAE,CAAC;QAChD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAC3C,MAAM,UAAU,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;YACjC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;gBAC/B,SAAS;YACX,CAAC;YAED,MAAM,YAAY,GAAG,UAAU,CAAC,cAAc,CAAC;YAC/C,MAAM,SAAS,GAAG,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC;YAChE,sBAAsB,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC,sBAAsB,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC;QACrG,CAAC;IACH,CAAC;IAED,OAAO,QAAQ,CAAC;QACd,WAAW;QACX,+BAA+B;QAC/B,sBAAsB,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,sBAAsB,CAAC,CAAC;QAC5D,OAAO;QACP,eAAe,EAAE,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,IAAI,WAAW,CAAC,IAAI,CAAC,YAAY;QACpF,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","sourcesContent":["// Copyright 2025 The Chromium Authors. All rights reserved.\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 Extras from '../extras/extras.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.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\nexport const UIStrings = {\n /**\n * @description Title of an insight that identifies multiple copies of the same JavaScript sources, and recommends removing the duplication.\n */\n title: 'Duplicated JavaScript',\n /**\n * @description Description of an insight that identifies multiple copies of the same JavaScript sources, and recommends removing the duplication.\n */\n description:\n 'Remove large, duplicate JavaScript modules from bundles to reduce unnecessary bytes consumed by network activity.',\n /** Label for a column in a data table; entries will be the locations of JavaScript or CSS code, e.g. the name of a Javascript package or module. */\n columnSource: 'Source',\n /** Label for a column in a data table; entries will be the number of wasted bytes due to duplication of a web resource. */\n columnDuplicatedBytes: 'Duplicated bytes',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/DuplicatedJavaScript.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport type DuplicatedJavaScriptInsightModel = InsightModel<typeof UIStrings, {\n duplication: Extras.ScriptDuplication.ScriptDuplication,\n duplicationGroupedByNodeModules: Extras.ScriptDuplication.ScriptDuplication,\n scriptsWithDuplication: Handlers.ModelHandlers.Scripts.Script[],\n scripts: Handlers.ModelHandlers.Scripts.Script[],\n mainDocumentUrl: string,\n}>;\n\nfunction finalize(partialModel: PartialInsightModel<DuplicatedJavaScriptInsightModel>):\n DuplicatedJavaScriptInsightModel {\n const requests = partialModel.scriptsWithDuplication.map(script => script.request).filter(e => !!e);\n\n return {\n insightKey: InsightKeys.DUPLICATE_JAVASCRIPT,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.LCP,\n state: Boolean(partialModel.duplication.values().next().value) ? 'fail' : 'pass',\n relatedEvents: [...new Set(requests)],\n ...partialModel,\n };\n}\n\nexport function generateInsight(\n parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): DuplicatedJavaScriptInsightModel {\n const scripts = parsedTrace.Scripts.scripts.filter(script => {\n if (!context.navigation) {\n return false;\n }\n\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 });\n\n const compressionRatios = new Map<string, number>();\n for (const script of scripts) {\n if (script.request) {\n compressionRatios.set(script.request.args.data.requestId, estimateCompressionRatioForScript(script));\n }\n }\n\n const {duplication, duplicationGroupedByNodeModules} =\n Extras.ScriptDuplication.computeScriptDuplication({scripts}, compressionRatios);\n const scriptsWithDuplication = [...duplication.values().flatMap(data => data.duplicates.map(d => d.script))];\n\n const wastedBytesByRequestId = new Map<string, number>();\n for (const {duplicates} of duplication.values()) {\n for (let i = 1; i < duplicates.length; i++) {\n const sourceData = duplicates[i];\n if (!sourceData.script.request) {\n continue;\n }\n\n const transferSize = sourceData.attributedSize;\n const requestId = sourceData.script.request.args.data.requestId;\n wastedBytesByRequestId.set(requestId, (wastedBytesByRequestId.get(requestId) || 0) + transferSize);\n }\n }\n\n return finalize({\n duplication,\n duplicationGroupedByNodeModules,\n scriptsWithDuplication: [...new Set(scriptsWithDuplication)],\n scripts,\n mainDocumentUrl: context.navigation?.args.data?.url ?? parsedTrace.Meta.mainFrameURL,\n metricSavings: metricSavingsForWastedBytes(wastedBytesByRequestId, context),\n wastedBytes: wastedBytesByRequestId.values().reduce((acc, cur) => acc + cur, 0),\n });\n}\n"]}
@@ -5,7 +5,7 @@
5
5
  import * as Platform from '../../../core/platform/platform.js';
6
6
  import * as Helpers from '../helpers/helpers.js';
7
7
  import * as Types from '../types/types.js';
8
- import { InsightCategory, } from './types.js';
8
+ import { InsightCategory, InsightKeys, } from './types.js';
9
9
  export const UIStrings = {
10
10
  /** Title of an insight that provides details about the fonts used on the page, and the value of their `font-display` properties. */
11
11
  title: 'Font display',
@@ -22,7 +22,7 @@ export const UIStrings = {
22
22
  export const i18nString = (i18nId, values) => ({i18nId, values}); // i18n.i18n.getLocalizedString.bind(undefined, str_);
23
23
  function finalize(partialModel) {
24
24
  return {
25
- insightKey: "FontDisplay" /* InsightKeys.FONT_DISPLAY */,
25
+ insightKey: InsightKeys.FONT_DISPLAY,
26
26
  strings: UIStrings,
27
27
  title: i18nString(UIStrings.title),
28
28
  description: i18nString(UIStrings.description),
@@ -1 +1 @@
1
- {"version":3,"file":"FontDisplay.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/FontDisplay.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AACnD,OAAO,KAAK,QAAQ,MAAM,oCAAoC,CAAC;AAE/D,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EACL,eAAe,GAKhB,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,oIAAoI;IACpI,KAAK,EAAE,cAAc;IACrB;;OAEG;IACH,WAAW,EACP,6RAA6R;IACjS,2DAA2D;IAC3D,UAAU,EAAE,MAAM;IAClB,4CAA4C;IAC5C,gBAAgB,EAAE,aAAa;CACvB,CAAC;AAEX,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,sCAAsC,EAAE,SAAS,CAAC,CAAC;AAC5F,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAa7E,SAAS,QAAQ,CAAC,YAA0D;IAC1E,OAAO;QACL,UAAU,8CAA0B;QACpC,OAAO,EAAE,SAAS;QAClB,KAAK,EAAE,UAAU,CAAC,SAAS,CAAC,KAAK,CAAC;QAClC,WAAW,EAAE,UAA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AC,MAAM,CAAC,YAAY,CAAC,eAAe,CAAC,EAAE,CAAC,GAAG,CAAC,CAAuB,CAAC;QAC9G,IAAI,UAAU,KAAK,CAAC,EAAE,CAAC;YACrB,SAAS;QACX,CAAC;QAED,yCAAyC;QACzC,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAuB,CAAC;QAE9D,KAAK,CAAC,IAAI,CAAC;YACT,IAAI,EAAE,UAAU,CAAC,IAAI;YACrB,OAAO;YACP,OAAO,EAAE,UAAU,CAAC,OAAO;YAC3B,UAAU;SACX,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC;IAElD,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAuB,CAAC;IAEhF,OAAO,QAAQ,CAAC;QACd,aAAa,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;QACxC,KAAK;QACL,aAAa,EAAE,EAAC,GAAG,EAAE,OAAO,EAAC;KAC9B,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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 Platform from '../../../core/platform/platform.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\nimport {\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n type PartialInsightModel,\n} from './types.js';\n\nexport const UIStrings = {\n /** Title of an insight that provides details about the fonts used on the page, and the value of their `font-display` properties. */\n title: 'Font display',\n /**\n * @description Text to tell the user about the font-display CSS feature to help improve a the UX of a page.\n */\n description:\n 'Consider setting [`font-display`](https://developer.chrome.com/blog/font-display) to `swap` or `optional` to ensure text is consistently visible. `swap` can be further optimized to mitigate layout shifts with [font metric overrides](https://developer.chrome.com/blog/font-fallbacks).',\n /** Column for a font loaded by the page to render text. */\n fontColumn: 'Font',\n /** Column for the amount of time wasted. */\n wastedTimeColumn: 'Wasted time',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/FontDisplay.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport interface RemoteFont {\n name?: string;\n request: Types.Events.SyntheticNetworkRequest;\n display: string;\n wastedTime: Types.Timing.Milli;\n}\n\nexport type FontDisplayInsightModel = InsightModel<typeof UIStrings, {\n fonts: RemoteFont[],\n}>;\n\nfunction finalize(partialModel: PartialInsightModel<FontDisplayInsightModel>): FontDisplayInsightModel {\n return {\n insightKey: InsightKeys.FONT_DISPLAY,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.INP,\n state: partialModel.fonts.find(font => font.wastedTime > 0) ? 'fail' : 'pass',\n ...partialModel,\n };\n}\n\nexport function generateInsight(\n parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): FontDisplayInsightModel {\n const fonts: RemoteFont[] = [];\n for (const remoteFont of parsedTrace.LayoutShifts.remoteFonts) {\n const event = remoteFont.beginRemoteFontLoadEvent;\n if (!Helpers.Timing.eventIsInBounds(event, context.bounds)) {\n continue;\n }\n\n const requestId = `${event.pid}.${event.args.id}`;\n const request = parsedTrace.NetworkRequests.byId.get(requestId);\n if (!request) {\n continue;\n }\n\n if (!/^(block|fallback|auto)$/.test(remoteFont.display)) {\n continue;\n }\n\n const wastedTimeMicro =\n Types.Timing.Micro(request.args.data.syntheticData.finishTime - request.args.data.syntheticData.sendStartTime);\n // TODO(crbug.com/352244504): should really end at the time of the next Commit trace event.\n let wastedTime =\n Platform.NumberUtilities.floor(Helpers.Timing.microToMilli(wastedTimeMicro), 1 / 5) as Types.Timing.Milli;\n if (wastedTime === 0) {\n continue;\n }\n\n // All browsers wait for no more than 3s.\n wastedTime = Math.min(wastedTime, 3000) as Types.Timing.Milli;\n\n fonts.push({\n name: remoteFont.name,\n request,\n display: remoteFont.display,\n wastedTime,\n });\n }\n\n fonts.sort((a, b) => b.wastedTime - a.wastedTime);\n\n const savings = Math.max(...fonts.map(f => f.wastedTime)) as Types.Timing.Milli;\n\n return finalize({\n relatedEvents: fonts.map(f => f.request),\n fonts,\n metricSavings: {FCP: savings},\n });\n}\n"]}
1
+ {"version":3,"file":"FontDisplay.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/FontDisplay.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AACnD,OAAO,KAAK,QAAQ,MAAM,oCAAoC,CAAC;AAE/D,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EACL,eAAe,EACf,WAAW,GAIZ,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,oIAAoI;IACpI,KAAK,EAAE,cAAc;IACrB;;OAEG;IACH,WAAW,EACP,6RAA6R;IACjS,2DAA2D;IAC3D,UAAU,EAAE,MAAM;IAClB,4CAA4C;IAC5C,gBAAgB,EAAE,aAAa;CACvB,CAAC;AAEX,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,sCAAsC,EAAE,SAAS,CAAC,CAAC;AAC5F,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAa7E,SAAS,QAAQ,CAAC,YA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G,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,aAAa,CAAC,CAAC;QACnH,2FAA2F;QAC3F,IAAI,UAAU,GACV,QAAQ,CAAC,eAAe,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC,eAAe,CAAC,EAAE,CAAC,GAAG,CAAC,CAAuB,CAAC;QAC9G,IAAI,UAAU,KAAK,CAAC,EAAE,CAAC;YACrB,SAAS;QACX,CAAC;QAED,yCAAyC;QACzC,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAuB,CAAC;QAE9D,KAAK,CAAC,IAAI,CAAC;YACT,IAAI,EAAE,UAAU,CAAC,IAAI;YACrB,OAAO;YACP,OAAO,EAAE,UAAU,CAAC,OAAO;YAC3B,UAAU;SACX,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC;IAElD,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAuB,CAAC;IAEhF,OAAO,QAAQ,CAAC;QACd,aAAa,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;QACxC,KAAK;QACL,aAAa,EAAE,EAAC,GAAG,EAAE,OAAO,EAAC;KAC9B,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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 Platform from '../../../core/platform/platform.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\nimport {\n InsightCategory,\n InsightKeys,\n type InsightModel,\n type InsightSetContext,\n type PartialInsightModel,\n} from './types.js';\n\nexport const UIStrings = {\n /** Title of an insight that provides details about the fonts used on the page, and the value of their `font-display` properties. */\n title: 'Font display',\n /**\n * @description Text to tell the user about the font-display CSS feature to help improve a the UX of a page.\n */\n description:\n 'Consider setting [`font-display`](https://developer.chrome.com/blog/font-display) to `swap` or `optional` to ensure text is consistently visible. `swap` can be further optimized to mitigate layout shifts with [font metric overrides](https://developer.chrome.com/blog/font-fallbacks).',\n /** Column for a font loaded by the page to render text. */\n fontColumn: 'Font',\n /** Column for the amount of time wasted. */\n wastedTimeColumn: 'Wasted time',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/FontDisplay.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport interface RemoteFont {\n name?: string;\n request: Types.Events.SyntheticNetworkRequest;\n display: string;\n wastedTime: Types.Timing.Milli;\n}\n\nexport type FontDisplayInsightModel = InsightModel<typeof UIStrings, {\n fonts: RemoteFont[],\n}>;\n\nfunction finalize(partialModel: PartialInsightModel<FontDisplayInsightModel>): FontDisplayInsightModel {\n return {\n insightKey: InsightKeys.FONT_DISPLAY,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.INP,\n state: partialModel.fonts.find(font => font.wastedTime > 0) ? 'fail' : 'pass',\n ...partialModel,\n };\n}\n\nexport function generateInsight(\n parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): FontDisplayInsightModel {\n const fonts: RemoteFont[] = [];\n for (const remoteFont of parsedTrace.LayoutShifts.remoteFonts) {\n const event = remoteFont.beginRemoteFontLoadEvent;\n if (!Helpers.Timing.eventIsInBounds(event, context.bounds)) {\n continue;\n }\n\n const requestId = `${event.pid}.${event.args.id}`;\n const request = parsedTrace.NetworkRequests.byId.get(requestId);\n if (!request) {\n continue;\n }\n\n if (!/^(block|fallback|auto)$/.test(remoteFont.display)) {\n continue;\n }\n\n const wastedTimeMicro =\n Types.Timing.Micro(request.args.data.syntheticData.finishTime - request.args.data.syntheticData.sendStartTime);\n // TODO(crbug.com/352244504): should really end at the time of the next Commit trace event.\n let wastedTime =\n Platform.NumberUtilities.floor(Helpers.Timing.microToMilli(wastedTimeMicro), 1 / 5) as Types.Timing.Milli;\n if (wastedTime === 0) {\n continue;\n }\n\n // All browsers wait for no more than 3s.\n wastedTime = Math.min(wastedTime, 3000) as Types.Timing.Milli;\n\n fonts.push({\n name: remoteFont.name,\n request,\n display: remoteFont.display,\n wastedTime,\n });\n }\n\n fonts.sort((a, b) => b.wastedTime - a.wastedTime);\n\n const savings = Math.max(...fonts.map(f => f.wastedTime)) as Types.Timing.Milli;\n\n return finalize({\n relatedEvents: fonts.map(f => f.request),\n fonts,\n metricSavings: {FCP: savings},\n });\n}\n"]}
@@ -6,7 +6,7 @@ import * as Platform from '../../../core/platform/platform.js';
6
6
  import * as Extras from '../extras/extras.js';
7
7
  import * as Helpers from '../helpers/helpers.js';
8
8
  import * as Types from '../types/types.js';
9
- import { InsightCategory, } from './types.js';
9
+ import { InsightCategory, InsightKeys, } from './types.js';
10
10
  export const UIStrings = {
11
11
  /**
12
12
  *@description Title of an insight that provides details about Forced reflow.
@@ -96,7 +96,7 @@ function getLargestTopLevelFunctionData(forcedReflowEvents, traceParsedData) {
96
96
  }
97
97
  function finalize(partialModel) {
98
98
  return {
99
- insightKey: "ForcedReflow" /* InsightKeys.FORCED_REFLOW */,
99
+ insightKey: InsightKeys.FORCED_REFLOW,
100
100
  strings: UIStrings,
101
101
  title: i18nString(UIStrings.title),
102
102
  description: i18nString(UIStrings.description),
@@ -1 +1 @@
1
- {"version":3,"file":"ForcedReflow.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/ForcedReflow.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,M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Ae,CAAC,MAAM,EAAE,CAAC;KACtD,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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 Platform from '../../../core/platform/platform.js';\nimport type * as Protocol from '../../../generated/protocol.js';\nimport * as Extras from '../extras/extras.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\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 provides details about Forced reflow.\n */\n title: 'Forced reflow',\n /**\n * @description Text to describe the forced reflow.\n */\n description:\n 'Many APIs, typically reading layout geometry, force the rendering engine to pause script execution in order to calculate the style and layout. Learn more about [forced reflow](https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing#avoid-forced-synchronous-layouts) and its mitigations.',\n /**\n *@description Title of a list to provide related stack trace data\n */\n relatedStackTrace: 'Stack trace',\n /**\n *@description Text to describe the top time-consuming function call\n */\n topTimeConsumingFunctionCall: 'Top function call',\n /**\n * @description Text to describe the total reflow time\n */\n totalReflowTime: 'Total reflow time',\n /**\n * @description Text to describe CPU processor tasks that could not be attributed to any specific source code.\n */\n unattributed: '[unattributed]',\n /**\n * @description Text for the name of anonymous functions\n */\n anonymous: '(anonymous)',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/ForcedReflow.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport type ForcedReflowInsightModel = InsightModel<typeof UIStrings, {\n topLevelFunctionCallData: ForcedReflowAggregatedData | undefined,\n aggregatedBottomUpData: BottomUpCallStack[],\n}>;\n\nexport interface BottomUpCallStack {\n /**\n * `null` indicates that this data is for unattributed force reflows.\n */\n bottomUpData: Types.Events.CallFrame|Protocol.Runtime.CallFrame|null;\n totalTime: number;\n relatedEvents: Types.Events.Event[];\n}\n\nexport interface ForcedReflowAggregatedData {\n topLevelFunctionCall: Types.Events.CallFrame|Protocol.Runtime.CallFrame;\n totalReflowTime: number;\n topLevelFunctionCallEvents: Types.Events.Event[];\n}\n\nfunction getCallFrameId(callFrame: Types.Events.CallFrame|Protocol.Runtime.CallFrame): string {\n return callFrame.scriptId + ':' + callFrame.lineNumber + ':' + callFrame.columnNumber;\n}\n\nfunction getLargestTopLevelFunctionData(\n forcedReflowEvents: Types.Events.Event[], traceParsedData: Handlers.Types.ParsedTrace): ForcedReflowAggregatedData|\n undefined {\n const entryToNodeMap = traceParsedData.Renderer.entryToNode;\n const dataByTopLevelFunction = new Map<string, ForcedReflowAggregatedData>();\n if (forcedReflowEvents.length === 0) {\n return;\n }\n\n for (const event of forcedReflowEvents) {\n // Gather the stack traces by searching in the tree\n const traceNode = entryToNodeMap.get(event);\n if (!traceNode) {\n continue;\n }\n\n let node = traceNode.parent;\n let topLevelFunctionCall;\n let topLevelFunctionCallEvent: Types.Events.Event|undefined;\n while (node) {\n const eventData = node.entry;\n if (Types.Events.isProfileCall(eventData)) {\n topLevelFunctionCall = eventData.callFrame;\n topLevelFunctionCallEvent = eventData;\n } else {\n // We have finished searching bottom up data\n if (Types.Events.isFunctionCall(eventData) && eventData.args.data &&\n Types.Events.objectIsCallFrame(eventData.args.data)) {\n topLevelFunctionCall = eventData.args.data;\n topLevelFunctionCallEvent = eventData;\n }\n break;\n }\n node = node.parent;\n }\n\n if (!topLevelFunctionCall || !topLevelFunctionCallEvent) {\n continue;\n }\n\n const aggregatedDataId = getCallFrameId(topLevelFunctionCall);\n const aggregatedData =\n Platform.MapUtilities.getWithDefault(dataByTopLevelFunction, aggregatedDataId, () => ({\n topLevelFunctionCall,\n totalReflowTime: 0,\n topLevelFunctionCallEvents: [],\n }));\n aggregatedData.totalReflowTime += (event.dur ?? 0);\n aggregatedData.topLevelFunctionCallEvents.push(topLevelFunctionCallEvent);\n }\n\n let topTimeConsumingData: ForcedReflowAggregatedData|undefined = undefined;\n dataByTopLevelFunction.forEach(data => {\n if (!topTimeConsumingData || data.totalReflowTime > topTimeConsumingData.totalReflowTime) {\n topTimeConsumingData = data;\n }\n });\n\n return topTimeConsumingData;\n}\n\nfunction finalize(partialModel: PartialInsightModel<ForcedReflowInsightModel>): ForcedReflowInsightModel {\n return {\n insightKey: InsightKeys.FORCED_REFLOW,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.ALL,\n state: partialModel.aggregatedBottomUpData.length !== 0 ? 'fail' : 'pass',\n ...partialModel,\n };\n}\n\nfunction getBottomCallFrameForEvent(event: Types.Events.Event, traceParsedData: Handlers.Types.ParsedTrace):\n Types.Events.CallFrame|Protocol.Runtime.CallFrame|null {\n const profileStackTrace = Extras.StackTraceForEvent.get(event, traceParsedData);\n const eventStackTrace = Helpers.Trace.getZeroIndexedStackTraceInEventPayload(event);\n\n return profileStackTrace?.callFrames[0] ?? eventStackTrace?.[0] ?? null;\n}\n\nexport function generateInsight(\n traceParsedData: Handlers.Types.ParsedTrace, context: InsightSetContext): ForcedReflowInsightModel {\n const isWithinContext = (event: Types.Events.Event): boolean => {\n const frameId = Helpers.Trace.frameIDForEvent(event);\n if (frameId !== context.frameId) {\n return false;\n }\n\n return Helpers.Timing.eventIsInBounds(event, context.bounds);\n };\n\n const bottomUpDataMap = new Map<string, BottomUpCallStack>();\n const events = traceParsedData.Warnings.perWarning.get('FORCED_REFLOW')?.filter(isWithinContext) ?? [];\n for (const event of events) {\n const bottomCallFrame = getBottomCallFrameForEvent(event, traceParsedData);\n const bottomCallId = bottomCallFrame ? getCallFrameId(bottomCallFrame) : 'UNATTRIBUTED';\n const bottomUpData =\n Platform.MapUtilities.getWithDefault(bottomUpDataMap, bottomCallId, () => ({\n bottomUpData: bottomCallFrame,\n totalTime: 0,\n relatedEvents: [],\n }));\n bottomUpData.totalTime += event.dur ?? 0;\n bottomUpData.relatedEvents.push(event);\n }\n\n const topLevelFunctionCallData = getLargestTopLevelFunctionData(events, traceParsedData);\n\n return finalize({\n relatedEvents: events,\n topLevelFunctionCallData,\n aggregatedBottomUpData: [...bottomUpDataMap.values()],\n });\n}\n"]}
1
+ {"version":3,"file":"ForcedReflow.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/ForcedReflow.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AACnD,OAAO,KAAK,QAAQ,MAAM,oCAAoC,CAAC;AAE/D,OAAO,KAAK,MAAM,MAAM,qBAAqB,CAAC;AAE9C,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,MAAM,mBAAmB,CAAC;AAE3C,OAAO,EACL,eAAe,EACf,WAAW,GAIZ,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,eAAe;IACtB;;OAEG;IACH,WAAW,EACP,8VAA8V;IAClW;;OAEG;IACH,iBAAiB,EAAE,aAAa;IAChC;;OAEG;IACH,4BAA4B,EAAE,mBAAmB;IACjD;;OAEG;IACH,eAAe,EAAE,mBAAmB;IACpC;;OAEG;IACH,YAAY,EAAE,gBAAgB;IAC9B;;OAEG;IACH,SAAS,EAAE,aAAa;CAChB,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;AAsB7E,SAAS,cAAc,CAAC,SAA4D;IAClF,OAAO,SAAS,CAAC,QAAQ,GAAG,G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Y,EAAE,eAAe;YAC7B,SAAS,EAAE,CAAC;YACZ,aAAa,EAAE,EAAE;SAClB,CAAC,CAAC,CAAC;QAC5E,YAAY,CAAC,SAAS,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;QACzC,YAAY,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;IAED,MAAM,wBAAwB,GAAG,8BAA8B,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAEzF,OAAO,QAAQ,CAAC;QACd,aAAa,EAAE,MAAM;QACrB,wBAAwB;QACxB,sBAAsB,EAAE,CAAC,GAAG,eAAe,CAAC,MAAM,EAAE,CAAC;KACtD,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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 Platform from '../../../core/platform/platform.js';\nimport type * as Protocol from '../../../generated/protocol.js';\nimport * as Extras from '../extras/extras.js';\nimport type * as Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport * as Types from '../types/types.js';\n\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 provides details about Forced reflow.\n */\n title: 'Forced reflow',\n /**\n * @description Text to describe the forced reflow.\n */\n description:\n 'Many APIs, typically reading layout geometry, force the rendering engine to pause script execution in order to calculate the style and layout. Learn more about [forced reflow](https://developers.google.com/web/fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing#avoid-forced-synchronous-layouts) and its mitigations.',\n /**\n *@description Title of a list to provide related stack trace data\n */\n relatedStackTrace: 'Stack trace',\n /**\n *@description Text to describe the top time-consuming function call\n */\n topTimeConsumingFunctionCall: 'Top function call',\n /**\n * @description Text to describe the total reflow time\n */\n totalReflowTime: 'Total reflow time',\n /**\n * @description Text to describe CPU processor tasks that could not be attributed to any specific source code.\n */\n unattributed: '[unattributed]',\n /**\n * @description Text for the name of anonymous functions\n */\n anonymous: '(anonymous)',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/ForcedReflow.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport type ForcedReflowInsightModel = InsightModel<typeof UIStrings, {\n topLevelFunctionCallData: ForcedReflowAggregatedData | undefined,\n aggregatedBottomUpData: BottomUpCallStack[],\n}>;\n\nexport interface BottomUpCallStack {\n /**\n * `null` indicates that this data is for unattributed force reflows.\n */\n bottomUpData: Types.Events.CallFrame|Protocol.Runtime.CallFrame|null;\n totalTime: number;\n relatedEvents: Types.Events.Event[];\n}\n\nexport interface ForcedReflowAggregatedData {\n topLevelFunctionCall: Types.Events.CallFrame|Protocol.Runtime.CallFrame;\n totalReflowTime: number;\n topLevelFunctionCallEvents: Types.Events.Event[];\n}\n\nfunction getCallFrameId(callFrame: Types.Events.CallFrame|Protocol.Runtime.CallFrame): string {\n return callFrame.scriptId + ':' + callFrame.lineNumber + ':' + callFrame.columnNumber;\n}\n\nfunction getLargestTopLevelFunctionData(\n forcedReflowEvents: Types.Events.Event[], traceParsedData: Handlers.Types.ParsedTrace): ForcedReflowAggregatedData|\n undefined {\n const entryToNodeMap = traceParsedData.Renderer.entryToNode;\n const dataByTopLevelFunction = new Map<string, ForcedReflowAggregatedData>();\n if (forcedReflowEvents.length === 0) {\n return;\n }\n\n for (const event of forcedReflowEvents) {\n // Gather the stack traces by searching in the tree\n const traceNode = entryToNodeMap.get(event);\n if (!traceNode) {\n continue;\n }\n\n let node = traceNode.parent;\n let topLevelFunctionCall;\n let topLevelFunctionCallEvent: Types.Events.Event|undefined;\n while (node) {\n const eventData = node.entry;\n if (Types.Events.isProfileCall(eventData)) {\n topLevelFunctionCall = eventData.callFrame;\n topLevelFunctionCallEvent = eventData;\n } else {\n // We have finished searching bottom up data\n if (Types.Events.isFunctionCall(eventData) && eventData.args.data &&\n Types.Events.objectIsCallFrame(eventData.args.data)) {\n topLevelFunctionCall = eventData.args.data;\n topLevelFunctionCallEvent = eventData;\n }\n break;\n }\n node = node.parent;\n }\n\n if (!topLevelFunctionCall || !topLevelFunctionCallEvent) {\n continue;\n }\n\n const aggregatedDataId = getCallFrameId(topLevelFunctionCall);\n const aggregatedData =\n Platform.MapUtilities.getWithDefault(dataByTopLevelFunction, aggregatedDataId, () => ({\n topLevelFunctionCall,\n totalReflowTime: 0,\n topLevelFunctionCallEvents: [],\n }));\n aggregatedData.totalReflowTime += (event.dur ?? 0);\n aggregatedData.topLevelFunctionCallEvents.push(topLevelFunctionCallEvent);\n }\n\n let topTimeConsumingData: ForcedReflowAggregatedData|undefined = undefined;\n dataByTopLevelFunction.forEach(data => {\n if (!topTimeConsumingData || data.totalReflowTime > topTimeConsumingData.totalReflowTime) {\n topTimeConsumingData = data;\n }\n });\n\n return topTimeConsumingData;\n}\n\nfunction finalize(partialModel: PartialInsightModel<ForcedReflowInsightModel>): ForcedReflowInsightModel {\n return {\n insightKey: InsightKeys.FORCED_REFLOW,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.ALL,\n state: partialModel.aggregatedBottomUpData.length !== 0 ? 'fail' : 'pass',\n ...partialModel,\n };\n}\n\nfunction getBottomCallFrameForEvent(event: Types.Events.Event, traceParsedData: Handlers.Types.ParsedTrace):\n Types.Events.CallFrame|Protocol.Runtime.CallFrame|null {\n const profileStackTrace = Extras.StackTraceForEvent.get(event, traceParsedData);\n const eventStackTrace = Helpers.Trace.getZeroIndexedStackTraceInEventPayload(event);\n\n return profileStackTrace?.callFrames[0] ?? eventStackTrace?.[0] ?? null;\n}\n\nexport function generateInsight(\n traceParsedData: Handlers.Types.ParsedTrace, context: InsightSetContext): ForcedReflowInsightModel {\n const isWithinContext = (event: Types.Events.Event): boolean => {\n const frameId = Helpers.Trace.frameIDForEvent(event);\n if (frameId !== context.frameId) {\n return false;\n }\n\n return Helpers.Timing.eventIsInBounds(event, context.bounds);\n };\n\n const bottomUpDataMap = new Map<string, BottomUpCallStack>();\n const events = traceParsedData.Warnings.perWarning.get('FORCED_REFLOW')?.filter(isWithinContext) ?? [];\n for (const event of events) {\n const bottomCallFrame = getBottomCallFrameForEvent(event, traceParsedData);\n const bottomCallId = bottomCallFrame ? getCallFrameId(bottomCallFrame) : 'UNATTRIBUTED';\n const bottomUpData =\n Platform.MapUtilities.getWithDefault(bottomUpDataMap, bottomCallId, () => ({\n bottomUpData: bottomCallFrame,\n totalTime: 0,\n relatedEvents: [],\n }));\n bottomUpData.totalTime += event.dur ?? 0;\n bottomUpData.relatedEvents.push(event);\n }\n\n const topLevelFunctionCallData = getLargestTopLevelFunctionData(events, traceParsedData);\n\n return finalize({\n relatedEvents: events,\n topLevelFunctionCallData,\n aggregatedBottomUpData: [...bottomUpDataMap.values()],\n });\n}\n"]}
@@ -4,7 +4,7 @@
4
4
  // import * as i18n from '../../../core/i18n/i18n.js';
5
5
  import * as Helpers from '../helpers/helpers.js';
6
6
  import { metricSavingsForWastedBytes } from './Common.js';
7
- import { InsightCategory, } from './types.js';
7
+ import { InsightCategory, InsightKeys, } from './types.js';
8
8
  export const UIStrings = {
9
9
  /**
10
10
  * @description Title of an insight that recommends ways to reduce the size of images downloaded and used on the page.
@@ -107,7 +107,7 @@ export function getOptimizationMessageWithBytes(optimization) {
107
107
  }
108
108
  function finalize(partialModel) {
109
109
  return {
110
- insightKey: "ImageDelivery" /* InsightKeys.IMAGE_DELIVERY */,
110
+ insightKey: InsightKeys.IMAGE_DELIVERY,
111
111
  strings: UIStrings,
112
112
  title: i18nString(UIStrings.title),
113
113
  description: i18nString(UIStrings.description),
@@ -1 +1 @@
1
- {"version":3,"file":"ImageDelivery.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/ImageDelivery.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;A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AW,EAAE,CAAC,CAAC;KAClF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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}>;\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 getPixelCounts(paintImage: Types.Events.PaintImage): {displayedPixels: number, filePixels: number} {\n return {\n filePixels: paintImage.args.data.srcWidth * paintImage.args.data.srcHeight,\n displayedPixels: paintImage.args.data.width * paintImage.args.data.height,\n };\n}\n\nexport function generateInsight(\n parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): ImageDeliveryInsightModel {\n const isWithinContext = (event: Types.Events.Event): boolean => Helpers.Timing.eventIsInBounds(event, context.bounds);\n\n const contextRequests = parsedTrace.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 = parsedTrace.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(prev).displayedPixels;\n const currPixels = getPixelCounts(curr).displayedPixels;\n return prevPixels > currPixels ? prev : curr;\n });\n\n const {\n filePixels: imageFilePixels,\n displayedPixels: largestImageDisplayPixels,\n } = getPixelCounts(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 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(largestImagePaint.args.data.width),\n height: Math.round(largestImagePaint.args.data.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"]}
1
+ {"version":3,"file":"ImageDelivery.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/ImageDeliv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AM,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC,KAAK,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC;KAClF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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}>;\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 getPixelCounts(paintImage: Types.Events.PaintImage): {displayedPixels: number, filePixels: number} {\n return {\n filePixels: paintImage.args.data.srcWidth * paintImage.args.data.srcHeight,\n displayedPixels: paintImage.args.data.width * paintImage.args.data.height,\n };\n}\n\nexport function generateInsight(\n parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): ImageDeliveryInsightModel {\n const isWithinContext = (event: Types.Events.Event): boolean => Helpers.Timing.eventIsInBounds(event, context.bounds);\n\n const contextRequests = parsedTrace.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 = parsedTrace.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(prev).displayedPixels;\n const currPixels = getPixelCounts(curr).displayedPixels;\n return prevPixels > currPixels ? prev : curr;\n });\n\n const {\n filePixels: imageFilePixels,\n displayedPixels: largestImageDisplayPixels,\n } = getPixelCounts(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 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(largestImagePaint.args.data.width),\n height: Math.round(largestImagePaint.args.data.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"]}
@@ -0,0 +1,9 @@
1
+ export * as CumulativeLayoutShift from './CumulativeLayoutShift.js';
2
+ export * as DocumentLatency from './DocumentLatency.js';
3
+ export * as FontDisplay from './FontDisplay.js';
4
+ export * as InteractionToNextPaint from './InteractionToNextPaint.js';
5
+ export * as LargestContentfulPaint from './LargestContentfulPaint.js';
6
+ export * as RenderBlocking from './RenderBlocking.js';
7
+ export * as SlowCSSSelector from './SlowCSSSelector.js';
8
+ export * as ThirdPartyWeb from './ThirdPartyWeb.js';
9
+ export * as Viewport from './Viewport.js';
@@ -0,0 +1,13 @@
1
+ // Copyright 2024 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+ export * as CumulativeLayoutShift from './CumulativeLayoutShift.js';
5
+ export * as DocumentLatency from './DocumentLatency.js';
6
+ export * as FontDisplay from './FontDisplay.js';
7
+ export * as InteractionToNextPaint from './InteractionToNextPaint.js';
8
+ export * as LargestContentfulPaint from './LargestContentfulPaint.js';
9
+ export * as RenderBlocking from './RenderBlocking.js';
10
+ export * as SlowCSSSelector from './SlowCSSSelector.js';
11
+ export * as ThirdPartyWeb from './ThirdPartyWeb.js';
12
+ export * as Viewport from './Viewport.js';
13
+ //# sourceMappingURL=InsightRunners.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InsightRunners.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/InsightRunners.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,qBAAqB,MAAM,4BAA4B,CAAC;AACpE,OAAO,KAAK,eAAe,MAAM,sBAAsB,CAAC;AACxD,OAAO,KAAK,WAAW,MAAM,kBAAkB,CAAC;AAChD,OAAO,KAAK,sBAAsB,MAAM,6BAA6B,CAAC;AACtE,OAAO,KAAK,sBAAsB,MAAM,6BAA6B,CAAC;AACtE,OAAO,KAAK,cAAc,MAAM,qBAAqB,CAAC;AACtD,OAAO,KAAK,eAAe,MAAM,sBAAsB,CAAC;AACxD,OAAO,KAAK,aAAa,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,QAAQ,MAAM,eAAe,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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 CumulativeLayoutShift from './CumulativeLayoutShift.js';\nexport * as DocumentLatency from './DocumentLatency.js';\nexport * as FontDisplay from './FontDisplay.js';\nexport * as InteractionToNextPaint from './InteractionToNextPaint.js';\nexport * as LargestContentfulPaint from './LargestContentfulPaint.js';\nexport * as RenderBlocking from './RenderBlocking.js';\nexport * as SlowCSSSelector from './SlowCSSSelector.js';\nexport * as ThirdPartyWeb from './ThirdPartyWeb.js';\nexport * as Viewport from './Viewport.js';\n"]}
@@ -3,7 +3,7 @@
3
3
  // found in the LICENSE file.
4
4
  // import * as i18n from '../../../core/i18n/i18n.js';
5
5
  import * as Helpers from '../helpers/helpers.js';
6
- import { InsightCategory, } from './types.js';
6
+ import { InsightCategory, InsightKeys, } from './types.js';
7
7
  export const UIStrings = {
8
8
  /**
9
9
  * @description Text to tell the user about the longest user interaction.
@@ -42,11 +42,11 @@ export const UIStrings = {
42
42
  // const str_ = i18n.i18n.registerUIStrings('models/trace/insights/InteractionToNextPaint.ts', UIStrings);
43
43
  export const i18nString = (i18nId, values) => ({i18nId, values}); // i18n.i18n.getLocalizedString.bind(undefined, str_);
44
44
  export function isINP(insight) {
45
- return insight.insightKey === "InteractionToNextPaint" /* InsightKeys.INTERACTION_TO_NEXT_PAINT */;
45
+ return insight.insightKey === InsightKeys.INTERACTION_TO_NEXT_PAINT;
46
46
  }
47
47
  function finalize(partialModel) {
48
48
  return {
49
- insightKey: "InteractionToNextPaint" /* InsightKeys.INTERACTION_TO_NEXT_PAINT */,
49
+ insightKey: InsightKeys.INTERACTION_TO_NEXT_PAINT,
50
50
  strings: UIStrings,
51
51
  title: i18nString(UIStrings.title),
52
52
  description: i18nString(UIStrings.description),
@@ -1 +1 @@
1
- {"version":3,"file":"InteractionToNextPaint.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/InteractionToNextPaint.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AAEnD,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AAGjD,OAAO,EACL,eAAe,GAKhB,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;;OAEG;IACH,WAAW,EACP,8PAA8P;IAClQ;;OAEG;IACH,KAAK,EAAE,cAAc;IACrB;;OAEG;IACH,KAAK,EAAE,OAAO;IACd;;OAEG;IACH,QAAQ,EAAE,UAAU;IAEpB,oFAAoF;IACpF;;OAEG;IACH,UAAU,EAAE,aAAa;IACzB;;OAEG;IACH,kBAAkB,EAAE,qBAAqB;IACzC;;OAEG;IACH,iBAAiB,EAAE,oBAAoB;IACvC;;OAEG;IACH,cAAc,EAAE,0BAA0B;CAClC,CAAC;AAEX,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,iDAAiD,EAAE,SAAS,CAAC,CAAC;AACvG,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAO7E,MAAM,UAAU,KAAK,CAAC,OAAqB;IACzC,OAAO,OAAO,CAAC,UAAU,yEAA0C,CAAC;AACtE,CAAC;AAED,SAAS,QAAQ,CAAC,YAAkD;IAClE,OAAO;QACL,UAAU,sEAAuC;QACjD,OAAO,EAAE,SAAS;QAClB,KAAK,EAAE,UAAU,CAAC,SAAS,CAAC,KAAK,CAAC;QAClC,WAAW,EAAE,UAAU,CAAC,SAAS,CAAC,WAAW,CAAC;QAC9C,QAAQ,EAAE,eAAe,CAAC,GAA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E,IAAI,CAAC,KAAK,CAAC,2BAA2B,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,CAAC;IAE7F,OAAO,QAAQ,CAAC;QACd,aAAa,EAAE,CAAC,2BAA2B,CAAC,CAAC,CAAC,CAAC;QAC/C,uBAAuB,EAAE,2BAA2B,CAAC,CAAC,CAAC;QACvD,8BAA8B,EAAE,2BAA2B,CAAC,mBAAmB,CAAC;KACjF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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 Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport type {SyntheticInteractionPair} from '../types/TraceEvents.js';\n\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 Text to tell the user about the longest user interaction.\n */\n description:\n 'Start investigating with the longest phase. [Delays can be minimized](https://web.dev/articles/optimize-inp#optimize_interactions). To reduce processing duration, [optimize the main-thread costs](https://web.dev/articles/optimize-long-tasks), often JS.',\n /**\n * @description Title for the performance insight \"INP by phase\", which shows a breakdown of INP by phases / sections.\n */\n title: 'INP by phase',\n /**\n *@description Label used for the phase/component/stage/section of a larger duration.\n */\n phase: 'Phase',\n /**\n *@description Label used for a time duration.\n */\n duration: 'Duration',\n\n // TODO: these are repeated in InteractionBreakdown. Add a place for common strings?\n /**\n *@description Text shown next to the interaction event's input delay time in the detail view.\n */\n inputDelay: 'Input delay',\n /**\n *@description Text shown next to the interaction event's thread processing duration in the detail view.\n */\n processingDuration: 'Processing duration',\n /**\n *@description Text shown next to the interaction event's presentation delay time in the detail view.\n */\n presentationDelay: 'Presentation delay',\n /**\n * @description Text status indicating that no user interactions were detected.\n */\n noInteractions: 'No interactions detected',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/InteractionToNextPaint.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport type INPInsightModel = InsightModel<typeof UIStrings, {\n longestInteractionEvent?: SyntheticInteractionPair,\n highPercentileInteractionEvent?: SyntheticInteractionPair,\n}>;\n\nexport function isINP(insight: InsightModel): insight is INPInsightModel {\n return insight.insightKey === InsightKeys.INTERACTION_TO_NEXT_PAINT;\n}\n\nfunction finalize(partialModel: PartialInsightModel<INPInsightModel>): INPInsightModel {\n return {\n insightKey: InsightKeys.INTERACTION_TO_NEXT_PAINT,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.INP,\n state: partialModel.longestInteractionEvent ? 'informative' : 'pass',\n ...partialModel,\n };\n}\n\nexport function generateInsight(parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): INPInsightModel {\n const interactionEvents = parsedTrace.UserInteractions.interactionEventsWithNoNesting.filter(event => {\n return Helpers.Timing.eventIsInBounds(event, context.bounds);\n });\n\n if (!interactionEvents.length) {\n // A valid result, when there is no user interaction.\n return finalize({});\n }\n\n const longestByInteractionId = new Map<number, SyntheticInteractionPair>();\n for (const event of interactionEvents) {\n const key = event.interactionId;\n const longest = longestByInteractionId.get(key);\n if (!longest || event.dur > longest.dur) {\n longestByInteractionId.set(key, event);\n }\n }\n const normalizedInteractionEvents = [...longestByInteractionId.values()];\n normalizedInteractionEvents.sort((a, b) => b.dur - a.dur);\n\n // INP is the \"nearest-rank\"/inverted_cdf 98th percentile, except Chrome only\n // keeps the 10 worst events around, so it can never be more than the 10th from\n // last array element. To keep things simpler, sort desc and pick from front.\n // See https://source.chromium.org/chromium/chromium/src/+/main:components/page_load_metrics/browser/responsiveness_metrics_normalization.cc;l=45-59;drc=cb0f9c8b559d9c7c3cb4ca94fc1118cc015d38ad\n const highPercentileIndex = Math.min(9, Math.floor(normalizedInteractionEvents.length / 50));\n\n return finalize({\n relatedEvents: [normalizedInteractionEvents[0]],\n longestInteractionEvent: normalizedInteractionEvents[0],\n highPercentileInteractionEvent: normalizedInteractionEvents[highPercentileIndex],\n });\n}\n"]}
1
+ {"version":3,"file":"InteractionToNextPaint.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/InteractionToNextPaint.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AAEnD,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AAGjD,OAAO,EACL,eAAe,EACf,WAAW,GAIZ,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;;OAEG;IACH,WAAW,EACP,8PAA8P;IAClQ;;OAEG;IACH,KAAK,EAAE,cAAc;IACrB;;OAEG;IACH,KAAK,EAAE,OAAO;IACd;;OAEG;IACH,QAAQ,EAAE,UAAU;IAEpB,oFAAoF;IACpF;;OAEG;IACH,UAAU,EAAE,aAAa;IACzB;;OAEG;IACH,kBAAkB,EAAE,qBAAqB;IACzC;;OAEG;IACH,iBAAiB,EAAE,oBAAoB;IACvC;;OAEG;IACH,cAAc,EAAE,0BAA0B;CAClC,CAAC;AAEX,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,iDAAiD,EAAE,SAAS,CAAC,CAAC;AACvG,MAAM,CAAC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AAO7E,MAAM,UAAU,KAAK,CAAC,OAAqB;IACzC,OAAO,OAAO,CAAC,UAAU,KAAK,WAAW,CAAC,yBAAyB,CAAC;AACtE,CAAC;AAED,SAAS,QAAQ,CAAC,YAAkD;IAClE,OAAO;QACL,UAAU,EAAE,WAAW,CAAC,yBAAyB;QACjD,OAAO,EAAE,SAAS;QAClB,KAAK,EAAE,UAAU,CAAC,SAAS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E;IAC7E,+EAA+E;IAC/E,6EAA6E;IAC7E,iMAAiM;IACjM,MAAM,mBAAmB,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,2BAA2B,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC,CAAC;IAE7F,OAAO,QAAQ,CAAC;QACd,aAAa,EAAE,CAAC,2BAA2B,CAAC,CAAC,CAAC,CAAC;QAC/C,uBAAuB,EAAE,2BAA2B,CAAC,CAAC,CAAC;QACvD,8BAA8B,EAAE,2BAA2B,CAAC,mBAAmB,CAAC;KACjF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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 Handlers from '../handlers/handlers.js';\nimport * as Helpers from '../helpers/helpers.js';\nimport type {SyntheticInteractionPair} from '../types/TraceEvents.js';\n\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 Text to tell the user about the longest user interaction.\n */\n description:\n 'Start investigating with the longest phase. [Delays can be minimized](https://web.dev/articles/optimize-inp#optimize_interactions). To reduce processing duration, [optimize the main-thread costs](https://web.dev/articles/optimize-long-tasks), often JS.',\n /**\n * @description Title for the performance insight \"INP by phase\", which shows a breakdown of INP by phases / sections.\n */\n title: 'INP by phase',\n /**\n *@description Label used for the phase/component/stage/section of a larger duration.\n */\n phase: 'Phase',\n /**\n *@description Label used for a time duration.\n */\n duration: 'Duration',\n\n // TODO: these are repeated in InteractionBreakdown. Add a place for common strings?\n /**\n *@description Text shown next to the interaction event's input delay time in the detail view.\n */\n inputDelay: 'Input delay',\n /**\n *@description Text shown next to the interaction event's thread processing duration in the detail view.\n */\n processingDuration: 'Processing duration',\n /**\n *@description Text shown next to the interaction event's presentation delay time in the detail view.\n */\n presentationDelay: 'Presentation delay',\n /**\n * @description Text status indicating that no user interactions were detected.\n */\n noInteractions: 'No interactions detected',\n} as const;\n\nconst str_ = i18n.i18n.registerUIStrings('models/trace/insights/InteractionToNextPaint.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\nexport type INPInsightModel = InsightModel<typeof UIStrings, {\n longestInteractionEvent?: SyntheticInteractionPair,\n highPercentileInteractionEvent?: SyntheticInteractionPair,\n}>;\n\nexport function isINP(insight: InsightModel): insight is INPInsightModel {\n return insight.insightKey === InsightKeys.INTERACTION_TO_NEXT_PAINT;\n}\n\nfunction finalize(partialModel: PartialInsightModel<INPInsightModel>): INPInsightModel {\n return {\n insightKey: InsightKeys.INTERACTION_TO_NEXT_PAINT,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.INP,\n state: partialModel.longestInteractionEvent ? 'informative' : 'pass',\n ...partialModel,\n };\n}\n\nexport function generateInsight(parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): INPInsightModel {\n const interactionEvents = parsedTrace.UserInteractions.interactionEventsWithNoNesting.filter(event => {\n return Helpers.Timing.eventIsInBounds(event, context.bounds);\n });\n\n if (!interactionEvents.length) {\n // A valid result, when there is no user interaction.\n return finalize({});\n }\n\n const longestByInteractionId = new Map<number, SyntheticInteractionPair>();\n for (const event of interactionEvents) {\n const key = event.interactionId;\n const longest = longestByInteractionId.get(key);\n if (!longest || event.dur > longest.dur) {\n longestByInteractionId.set(key, event);\n }\n }\n const normalizedInteractionEvents = [...longestByInteractionId.values()];\n normalizedInteractionEvents.sort((a, b) => b.dur - a.dur);\n\n // INP is the \"nearest-rank\"/inverted_cdf 98th percentile, except Chrome only\n // keeps the 10 worst events around, so it can never be more than the 10th from\n // last array element. To keep things simpler, sort desc and pick from front.\n // See https://source.chromium.org/chromium/chromium/src/+/main:components/page_load_metrics/browser/responsiveness_metrics_normalization.cc;l=45-59;drc=cb0f9c8b559d9c7c3cb4ca94fc1118cc015d38ad\n const highPercentileIndex = Math.min(9, Math.floor(normalizedInteractionEvents.length / 50));\n\n return finalize({\n relatedEvents: [normalizedInteractionEvents[0]],\n longestInteractionEvent: normalizedInteractionEvents[0],\n highPercentileInteractionEvent: normalizedInteractionEvents[highPercentileIndex],\n });\n}\n"]}
@@ -5,7 +5,7 @@
5
5
  import * as Handlers from '../handlers/handlers.js';
6
6
  import * as Helpers from '../helpers/helpers.js';
7
7
  import * as Types from '../types/types.js';
8
- import { InsightCategory, InsightWarning, } from './types.js';
8
+ import { InsightCategory, InsightKeys, InsightWarning, } from './types.js';
9
9
  export const UIStrings = {
10
10
  /**
11
11
  *@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)
@@ -56,7 +56,7 @@ function finalize(partialModel) {
56
56
  [partialModel.lcpEvent, partialModel.lcpRequest] :
57
57
  [];
58
58
  return {
59
- insightKey: "LCPDiscovery" /* InsightKeys.LCP_DISCOVERY */,
59
+ insightKey: InsightKeys.LCP_DISCOVERY,
60
60
  strings: UIStrings,
61
61
  title: i18nString(UIStrings.title),
62
62
  description: i18nString(UIStrings.description),
@@ -83,7 +83,7 @@ export function generateInsight(parsedTrace, context) {
83
83
  if (!navMetrics) {
84
84
  throw new Error('no navigation metrics');
85
85
  }
86
- const metricScore = navMetrics.get("LCP" /* Handlers.ModelHandlers.PageLoadMetrics.MetricName.LCP */);
86
+ const metricScore = navMetrics.get(Handlers.ModelHandlers.PageLoadMetrics.MetricName.LCP);
87
87
  const lcpEvent = metricScore?.event;
88
88
  if (!lcpEvent || !Types.Events.isLargestContentfulPaintCandidate(lcpEvent)) {
89
89
  return finalize({ warnings: [InsightWarning.NO_LCP] });
@@ -1 +1 @@
1
- {"version":3,"file":"LCPDiscovery.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/LCPDiscovery.ts"],"names":[],"mappings":"AAAA,4DAA4D;AA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,MAAM,qBAAqB,GAAG,UAAU,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACxD,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;YAClE,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC;QAClF,SAAS,CAAC;IAEd,MAAM,iBAAiB,GAAG,sBAAsB,KAAK,MAAM,CAAC;IAE5D,OAAO,QAAQ,CAAC;QACd,QAAQ;QACR,UAAU;QACV,uBAAuB,EAAE,qBAAqB,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,SAAS;QACtG,SAAS,EAAE;YACT,cAAc,EAAE;gBACd,KAAK,EAAE,iBAAiB,CAAC,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,oBAAoB,CAAC,CAAC,CAAC;oBAC5C,UAAU,CAAC,SAAS,CAAC,4BAA4B,CAAC;gBAC7E,KAAK,EAAE,iBAAiB;aACzB;YACD,mBAAmB,EAAE,EAAC,KAAK,EAAE,UAAU,CAAC,SAAS,CAAC,mBAAmB,CAAC,EAAE,KAAK,EAAE,yBAAyB,EAAC;YACzG,aAAa,EAAE,EAAC,KAAK,EAAE,UAAU,CAAC,SAAS,CAAC,kBAAkB,CAAC,EAAE,KAAK,EAAE,gBAAgB,KAAK,MAAM,EAAC;SACrG;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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 {\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 isLCPDiscovery(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 parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): LCPDiscoveryInsightModel {\n if (!context.navigation) {\n return finalize({});\n }\n\n const networkRequests = parsedTrace.NetworkRequests;\n\n const frameMetrics = parsedTrace.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.byTime.find(req => req.args.data.requestId === context.navigationId);\n if (!docRequest) {\n return finalize({warnings: [InsightWarning.NO_DOCUMENT_REQUEST]});\n }\n\n const lcpRequest = parsedTrace.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.\n const earliestDiscoveryTime = docRequest?.args.data.timing ?\n Helpers.Timing.secondsToMicro(docRequest.args.data.timing.requestTime) +\n Helpers.Timing.milliToMicro(docRequest.args.data.timing.receiveHeadersStart) :\n undefined;\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"]}
1
+ {"version":3,"file":"LCPDiscovery.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/LCPDiscovery.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,IAAI,MAAM,4BAA4B,CAAC;AACnD,OAAO,KAAK,QAAQ,MAAM,yBAAyB,CAAC;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IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACxD,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;YAClE,OAAO,CAAC,MAAM,CAAC,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC,CAAC;QAClF,SAAS,CAAC;IAEd,MAAM,iBAAiB,GAAG,sBAAsB,KAAK,MAAM,CAAC;IAE5D,OAAO,QAAQ,CAAC;QACd,QAAQ;QACR,UAAU;QACV,uBAAuB,EAAE,qBAAqB,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,SAAS;QACtG,SAAS,EAAE;YACT,cAAc,EAAE;gBACd,KAAK,EAAE,iBAAiB,CAAC,CAAC,CAAC,UAAU,CAAC,SAAS,CAAC,oBAAoB,CAAC,CAAC,CAAC;oBAC5C,UAAU,CAAC,SAAS,CAAC,4BAA4B,CAAC;gBAC7E,KAAK,EAAE,iBAAiB;aACzB;YACD,mBAAmB,EAAE,EAAC,KAAK,EAAE,UAAU,CAAC,SAAS,CAAC,mBAAmB,CAAC,EAAE,KAAK,EAAE,yBAAyB,EAAC;YACzG,aAAa,EAAE,EAAC,KAAK,EAAE,UAAU,CAAC,SAAS,CAAC,kBAAkB,CAAC,EAAE,KAAK,EAAE,gBAAgB,KAAK,MAAM,EAAC;SACrG;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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 {\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 isLCPDiscovery(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 parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): LCPDiscoveryInsightModel {\n if (!context.navigation) {\n return finalize({});\n }\n\n const networkRequests = parsedTrace.NetworkRequests;\n\n const frameMetrics = parsedTrace.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.byTime.find(req => req.args.data.requestId === context.navigationId);\n if (!docRequest) {\n return finalize({warnings: [InsightWarning.NO_DOCUMENT_REQUEST]});\n }\n\n const lcpRequest = parsedTrace.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.\n const earliestDiscoveryTime = docRequest?.args.data.timing ?\n Helpers.Timing.secondsToMicro(docRequest.args.data.timing.requestTime) +\n Helpers.Timing.milliToMicro(docRequest.args.data.timing.receiveHeadersStart) :\n undefined;\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"]}
@@ -5,7 +5,7 @@
5
5
  import * as Handlers from '../handlers/handlers.js';
6
6
  import * as Helpers from '../helpers/helpers.js';
7
7
  import * as Types from '../types/types.js';
8
- import { InsightCategory, InsightWarning, } from './types.js';
8
+ import { InsightCategory, InsightKeys, InsightWarning, } from './types.js';
9
9
  export const UIStrings = {
10
10
  /**
11
11
  *@description Title of an insight that provides details about the LCP metric, broken down by phases / parts.
@@ -105,7 +105,7 @@ function finalize(partialModel) {
105
105
  relatedEvents.push(partialModel.lcpRequest);
106
106
  }
107
107
  return {
108
- insightKey: "LCPPhases" /* InsightKeys.LCP_PHASES */,
108
+ insightKey: InsightKeys.LCP_PHASES,
109
109
  strings: UIStrings,
110
110
  title: i18nString(UIStrings.title),
111
111
  description: i18nString(UIStrings.description),
@@ -128,7 +128,7 @@ export function generateInsight(parsedTrace, context) {
128
128
  if (!navMetrics) {
129
129
  throw new Error('no navigation metrics');
130
130
  }
131
- const metricScore = navMetrics.get("LCP" /* Handlers.ModelHandlers.PageLoadMetrics.MetricName.LCP */);
131
+ const metricScore = navMetrics.get(Handlers.ModelHandlers.PageLoadMetrics.MetricName.LCP);
132
132
  const lcpEvent = metricScore?.event;
133
133
  if (!lcpEvent || !Types.Events.isLargestContentfulPaintCandidate(lcpEvent)) {
134
134
  return finalize({ warnings: [InsightWarning.NO_LCP] });
@@ -1 +1 @@
1
- {"version":3,"file":"LCPPhases.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/LCPPhases.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,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,EACL,eAAe,EAIf,cAAc,GAEf,MAAM,YAAY,CAAC;AAEpB,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB;;OAEG;IACH,KAAK,EAAE,cAAc;IACrB;;;OAGG;IACH,WAAW,EACP,mMAAmM;IACvM;;OAEG;IACH,eAAe,EAAE,oBAAoB;IACrC;;OAEG;IACH,iBAAiB,EAAE,qBAAqB;IACxC;;OAEG;IACH,oBAAoB,EAAE,wBAAwB;IAC9C;;OAEG;IACH,kBAAkB,EAAE,sBAAsB;IAC1C;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SAAS;SACxF,CAAC,CAAC;IACL,CAAC;IAED,OAAO,QAAQ,CAAC;QACd,KAAK;QACL,KAAK;QACL,QAAQ;QACR,UAAU;QACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,CAAC,IAAI,SAAS;KACxF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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 {\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 phases / parts.\n */\n title: 'LCP by phase',\n /**\n * @description Description of a DevTools insight that presents a breakdown for the LCP metric by phases.\n * This is displayed after a user expands the section to see more. No character length limits.\n */\n description:\n 'Each [phase 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 phases timespan breakdown.\n */\n timeToFirstByte: 'Time to first byte',\n /**\n *@description Resource load delay title for the Largest Contentful Paint phases timespan breakdown.\n */\n resourceLoadDelay: 'Resource load delay',\n /**\n *@description Resource load duration title for the Largest Contentful Paint phases timespan breakdown.\n */\n resourceLoadDuration: 'Resource load duration',\n /**\n *@description Element render delay title for the Largest Contentful Paint phases timespan breakdown.\n */\n elementRenderDelay: 'Element render delay',\n /**\n *@description Label used for the phase/component/stage/section of a larger duration.\n */\n phase: 'Phase',\n /**\n * @description Label used for the duration a single phase/component/stage/section takes up of a larger duration.\n */\n duration: 'Duration',\n /**\n * @description Label used for the duration a single phase/component/stage/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/LCPPhases.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\ninterface LCPPhases {\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: Types.Timing.Milli;\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?: Types.Timing.Milli;\n /**\n * The time it takes to load the LCP request.\n */\n loadTime?: Types.Timing.Milli;\n /**\n * The time between when the LCP request finishes loading and when\n * the LCP element is rendered.\n */\n renderDelay: Types.Timing.Milli;\n}\n\nexport function isLCPPhases(model: InsightModel): model is LCPPhasesInsightModel {\n return model.insightKey === 'LCPPhases';\n}\nexport type LCPPhasesInsightModel = 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 phases?: LCPPhases,\n}>;\n\nfunction anyValuesNaN(...values: number[]): boolean {\n return values.some(v => Number.isNaN(v));\n}\n/**\n * Calculates the 4 phases of an LCP and the timings of each.\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 breakdownPhases(\n nav: Types.Events.NavigationStart, docRequest: Types.Events.SyntheticNetworkRequest, lcpMs: Types.Timing.Milli,\n lcpRequest: Types.Events.SyntheticNetworkRequest|undefined): LCPPhases|null {\n const docReqTiming = docRequest.args.data.timing;\n if (!docReqTiming) {\n throw new Error('no timing for document request');\n }\n const firstDocByteTs = Helpers.Timing.secondsToMicro(docReqTiming.requestTime) +\n Helpers.Timing.milliToMicro(docReqTiming.receiveHeadersStart);\n\n const firstDocByteTiming = Types.Timing.Micro(firstDocByteTs - nav.ts);\n const ttfb = Helpers.Timing.microToMilli(firstDocByteTiming);\n let renderDelay = Types.Timing.Milli(lcpMs - ttfb);\n\n if (!lcpRequest) {\n if (anyValuesNaN(ttfb, renderDelay)) {\n return null;\n }\n return {ttfb, renderDelay};\n }\n\n const lcpStartTs = Types.Timing.Micro(lcpRequest.ts - nav.ts);\n const requestStart = Helpers.Timing.microToMilli(lcpStartTs);\n\n const lcpReqEndTs = Types.Timing.Micro(lcpRequest.args.data.syntheticData.finishTime - nav.ts);\n const requestEnd = Helpers.Timing.microToMilli(lcpReqEndTs);\n\n const loadDelay = Types.Timing.Milli(requestStart - ttfb);\n const loadTime = Types.Timing.Milli(requestEnd - requestStart);\n renderDelay = Types.Timing.Milli(lcpMs - requestEnd);\n if (anyValuesNaN(ttfb, loadDelay, loadTime, renderDelay)) {\n return null;\n }\n\n return {\n ttfb,\n loadDelay,\n loadTime,\n renderDelay,\n };\n}\n\nfunction finalize(partialModel: PartialInsightModel<LCPPhasesInsightModel>): LCPPhasesInsightModel {\n const relatedEvents = [];\n if (partialModel.lcpEvent) {\n relatedEvents.push(partialModel.lcpEvent);\n }\n if (partialModel.lcpRequest) {\n relatedEvents.push(partialModel.lcpRequest);\n }\n return {\n insightKey: InsightKeys.LCP_PHASES,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.LCP,\n state: partialModel.lcpEvent || partialModel.lcpRequest ? 'informative' : 'pass',\n ...partialModel,\n relatedEvents,\n };\n}\n\nexport function generateInsight(\n parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): LCPPhasesInsightModel {\n if (!context.navigation) {\n return finalize({});\n }\n\n const networkRequests = parsedTrace.NetworkRequests;\n\n const frameMetrics = parsedTrace.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 phases.\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 = parsedTrace.LargestImagePaint.lcpRequestByNavigationId.get(context.navigationId);\n\n const docRequest = networkRequests.byTime.find(req => req.args.data.requestId === context.navigationId);\n if (!docRequest) {\n return finalize({lcpMs, lcpTs, lcpEvent, lcpRequest, warnings: [InsightWarning.NO_DOCUMENT_REQUEST]});\n }\n\n if (!lcpRequest) {\n return finalize({\n lcpMs,\n lcpTs,\n lcpEvent,\n lcpRequest,\n phases: breakdownPhases(context.navigation, docRequest, lcpMs, lcpRequest) ?? undefined,\n });\n }\n\n return finalize({\n lcpMs,\n lcpTs,\n lcpEvent,\n lcpRequest,\n phases: breakdownPhases(context.navigation, docRequest, lcpMs, lcpRequest) ?? undefined,\n });\n}\n"]}
1
+ {"version":3,"file":"LCPPhases.js","sourceRoot":"","sources":["../../../../../../../front_end/models/trace/insights/LCPPhases.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,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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SAAS,KAAK,OAAO,CAAC,YAAY,CAAC,CAAC;IACxG,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,QAAQ,CAAC,EAAC,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC,cAAc,CAAC,mBAAmB,CAAC,EAAC,CAAC,CAAC;IACxG,CAAC;IAED,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,QAAQ,CAAC;YACd,KAAK;YACL,KAAK;YACL,QAAQ;YACR,UAAU;YACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,CAAC,IAAI,SAAS;SACxF,CAAC,CAAC;IACL,CAAC;IAED,OAAO,QAAQ,CAAC;QACd,KAAK;QACL,KAAK;QACL,QAAQ;QACR,UAAU;QACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,CAAC,IAAI,SAAS;KACxF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Copyright 2024 The Chromium Authors. All rights reserved.\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 {\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 phases / parts.\n */\n title: 'LCP by phase',\n /**\n * @description Description of a DevTools insight that presents a breakdown for the LCP metric by phases.\n * This is displayed after a user expands the section to see more. No character length limits.\n */\n description:\n 'Each [phase 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 phases timespan breakdown.\n */\n timeToFirstByte: 'Time to first byte',\n /**\n *@description Resource load delay title for the Largest Contentful Paint phases timespan breakdown.\n */\n resourceLoadDelay: 'Resource load delay',\n /**\n *@description Resource load duration title for the Largest Contentful Paint phases timespan breakdown.\n */\n resourceLoadDuration: 'Resource load duration',\n /**\n *@description Element render delay title for the Largest Contentful Paint phases timespan breakdown.\n */\n elementRenderDelay: 'Element render delay',\n /**\n *@description Label used for the phase/component/stage/section of a larger duration.\n */\n phase: 'Phase',\n /**\n * @description Label used for the duration a single phase/component/stage/section takes up of a larger duration.\n */\n duration: 'Duration',\n /**\n * @description Label used for the duration a single phase/component/stage/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/LCPPhases.ts', UIStrings);\nexport const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);\n\ninterface LCPPhases {\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: Types.Timing.Milli;\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?: Types.Timing.Milli;\n /**\n * The time it takes to load the LCP request.\n */\n loadTime?: Types.Timing.Milli;\n /**\n * The time between when the LCP request finishes loading and when\n * the LCP element is rendered.\n */\n renderDelay: Types.Timing.Milli;\n}\n\nexport function isLCPPhases(model: InsightModel): model is LCPPhasesInsightModel {\n return model.insightKey === 'LCPPhases';\n}\nexport type LCPPhasesInsightModel = 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 phases?: LCPPhases,\n}>;\n\nfunction anyValuesNaN(...values: number[]): boolean {\n return values.some(v => Number.isNaN(v));\n}\n/**\n * Calculates the 4 phases of an LCP and the timings of each.\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 breakdownPhases(\n nav: Types.Events.NavigationStart, docRequest: Types.Events.SyntheticNetworkRequest, lcpMs: Types.Timing.Milli,\n lcpRequest: Types.Events.SyntheticNetworkRequest|undefined): LCPPhases|null {\n const docReqTiming = docRequest.args.data.timing;\n if (!docReqTiming) {\n throw new Error('no timing for document request');\n }\n const firstDocByteTs = Helpers.Timing.secondsToMicro(docReqTiming.requestTime) +\n Helpers.Timing.milliToMicro(docReqTiming.receiveHeadersStart);\n\n const firstDocByteTiming = Types.Timing.Micro(firstDocByteTs - nav.ts);\n const ttfb = Helpers.Timing.microToMilli(firstDocByteTiming);\n let renderDelay = Types.Timing.Milli(lcpMs - ttfb);\n\n if (!lcpRequest) {\n if (anyValuesNaN(ttfb, renderDelay)) {\n return null;\n }\n return {ttfb, renderDelay};\n }\n\n const lcpStartTs = Types.Timing.Micro(lcpRequest.ts - nav.ts);\n const requestStart = Helpers.Timing.microToMilli(lcpStartTs);\n\n const lcpReqEndTs = Types.Timing.Micro(lcpRequest.args.data.syntheticData.finishTime - nav.ts);\n const requestEnd = Helpers.Timing.microToMilli(lcpReqEndTs);\n\n const loadDelay = Types.Timing.Milli(requestStart - ttfb);\n const loadTime = Types.Timing.Milli(requestEnd - requestStart);\n renderDelay = Types.Timing.Milli(lcpMs - requestEnd);\n if (anyValuesNaN(ttfb, loadDelay, loadTime, renderDelay)) {\n return null;\n }\n\n return {\n ttfb,\n loadDelay,\n loadTime,\n renderDelay,\n };\n}\n\nfunction finalize(partialModel: PartialInsightModel<LCPPhasesInsightModel>): LCPPhasesInsightModel {\n const relatedEvents = [];\n if (partialModel.lcpEvent) {\n relatedEvents.push(partialModel.lcpEvent);\n }\n if (partialModel.lcpRequest) {\n relatedEvents.push(partialModel.lcpRequest);\n }\n return {\n insightKey: InsightKeys.LCP_PHASES,\n strings: UIStrings,\n title: i18nString(UIStrings.title),\n description: i18nString(UIStrings.description),\n category: InsightCategory.LCP,\n state: partialModel.lcpEvent || partialModel.lcpRequest ? 'informative' : 'pass',\n ...partialModel,\n relatedEvents,\n };\n}\n\nexport function generateInsight(\n parsedTrace: Handlers.Types.ParsedTrace, context: InsightSetContext): LCPPhasesInsightModel {\n if (!context.navigation) {\n return finalize({});\n }\n\n const networkRequests = parsedTrace.NetworkRequests;\n\n const frameMetrics = parsedTrace.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 phases.\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 = parsedTrace.LargestImagePaint.lcpRequestByNavigationId.get(context.navigationId);\n\n const docRequest = networkRequests.byTime.find(req => req.args.data.requestId === context.navigationId);\n if (!docRequest) {\n return finalize({lcpMs, lcpTs, lcpEvent, lcpRequest, warnings: [InsightWarning.NO_DOCUMENT_REQUEST]});\n }\n\n if (!lcpRequest) {\n return finalize({\n lcpMs,\n lcpTs,\n lcpEvent,\n lcpRequest,\n phases: breakdownPhases(context.navigation, docRequest, lcpMs, lcpRequest) ?? undefined,\n });\n }\n\n return finalize({\n lcpMs,\n lcpTs,\n lcpEvent,\n lcpRequest,\n phases: breakdownPhases(context.navigation, docRequest, lcpMs, lcpRequest) ?? undefined,\n });\n}\n"]}