@paulirish/trace_engine 0.0.49 → 0.0.51

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 (225) hide show
  1. package/.tmp/tsbuildinfo/tsconfig.tsbuildinfo +1 -1
  2. package/core/platform/Constructor.d.ts +2 -2
  3. package/core/platform/Constructor.js.map +1 -1
  4. package/core/platform/StringUtilities.d.ts +2 -5
  5. package/core/platform/StringUtilities.js +0 -3
  6. package/core/platform/StringUtilities.js.map +1 -1
  7. package/core/platform/TypescriptUtilities.d.ts +1 -1
  8. package/core/platform/TypescriptUtilities.js +1 -1
  9. package/core/platform/TypescriptUtilities.js.map +1 -1
  10. package/core/platform/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  11. package/core/platform/platform-tsconfig.json +2 -3
  12. package/core/platform/platform.d.ts +1 -2
  13. package/core/platform/platform.js +1 -2
  14. package/core/platform/platform.js.map +1 -1
  15. package/generated/protocol.d.ts +156 -31
  16. package/locales/af.json +63 -3
  17. package/locales/am.json +63 -3
  18. package/locales/ar.json +63 -3
  19. package/locales/as.json +63 -3
  20. package/locales/az.json +63 -3
  21. package/locales/be.json +64 -4
  22. package/locales/bg.json +62 -2
  23. package/locales/bn.json +63 -3
  24. package/locales/bs.json +63 -3
  25. package/locales/ca.json +62 -2
  26. package/locales/cs.json +62 -2
  27. package/locales/cy.json +63 -3
  28. package/locales/da.json +63 -3
  29. package/locales/de.json +63 -3
  30. package/locales/el.json +62 -2
  31. package/locales/en-GB.json +63 -3
  32. package/locales/en-US.json +55 -22
  33. package/locales/en-XL.json +55 -22
  34. package/locales/es-419.json +63 -3
  35. package/locales/es.json +64 -4
  36. package/locales/et.json +64 -4
  37. package/locales/eu.json +79 -19
  38. package/locales/fa.json +62 -2
  39. package/locales/fi.json +63 -3
  40. package/locales/fil.json +63 -3
  41. package/locales/fr-CA.json +63 -3
  42. package/locales/fr.json +63 -3
  43. package/locales/gl.json +62 -2
  44. package/locales/gu.json +63 -3
  45. package/locales/he.json +63 -3
  46. package/locales/hi.json +62 -2
  47. package/locales/hr.json +63 -3
  48. package/locales/hu.json +62 -2
  49. package/locales/hy.json +63 -3
  50. package/locales/id.json +62 -2
  51. package/locales/is.json +64 -4
  52. package/locales/it.json +64 -4
  53. package/locales/ja.json +63 -3
  54. package/locales/ka.json +63 -3
  55. package/locales/kk.json +62 -2
  56. package/locales/km.json +62 -2
  57. package/locales/kn.json +63 -3
  58. package/locales/ko.json +63 -3
  59. package/locales/ky.json +63 -3
  60. package/locales/lo.json +63 -3
  61. package/locales/lt.json +62 -2
  62. package/locales/lv.json +62 -2
  63. package/locales/mk.json +62 -2
  64. package/locales/ml.json +63 -3
  65. package/locales/mn.json +63 -3
  66. package/locales/mr.json +64 -4
  67. package/locales/ms.json +63 -3
  68. package/locales/my.json +63 -3
  69. package/locales/ne.json +64 -4
  70. package/locales/nl.json +63 -3
  71. package/locales/no.json +62 -2
  72. package/locales/or.json +63 -3
  73. package/locales/pa.json +62 -2
  74. package/locales/pl.json +62 -2
  75. package/locales/pt-PT.json +62 -2
  76. package/locales/pt.json +63 -3
  77. package/locales/ro.json +63 -3
  78. package/locales/ru.json +63 -3
  79. package/locales/si.json +63 -3
  80. package/locales/sk.json +63 -3
  81. package/locales/sl.json +62 -2
  82. package/locales/sq.json +63 -3
  83. package/locales/sr-Latn.json +62 -2
  84. package/locales/sr.json +62 -2
  85. package/locales/sv.json +62 -2
  86. package/locales/sw.json +63 -3
  87. package/locales/ta.json +66 -6
  88. package/locales/te.json +63 -3
  89. package/locales/th.json +63 -3
  90. package/locales/tr.json +63 -3
  91. package/locales/uk.json +63 -3
  92. package/locales/ur.json +64 -4
  93. package/locales/uz.json +62 -2
  94. package/locales/vi.json +62 -2
  95. package/locales/zh-HK.json +63 -3
  96. package/locales/zh-TW.json +63 -3
  97. package/locales/zh.json +62 -2
  98. package/locales/zu.json +63 -3
  99. package/models/cpu_profile/CPUProfileDataModel.d.ts +8 -0
  100. package/models/cpu_profile/CPUProfileDataModel.js.map +1 -1
  101. package/models/cpu_profile/cpu_profile-tsconfig.json +2 -2
  102. package/models/cpu_profile/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  103. package/models/trace/Processor.d.ts +1 -1
  104. package/models/trace/Processor.js +94 -74
  105. package/models/trace/Processor.js.map +1 -1
  106. package/models/trace/TracingManager.js.map +1 -1
  107. package/models/trace/bundle-tsconfig.json +1 -1
  108. package/models/trace/devtools_entrypoint-bundle-typescript-tsconfig.json +20 -2
  109. package/models/trace/extras/ScriptDuplication.d.ts +11 -15
  110. package/models/trace/extras/ScriptDuplication.js +59 -77
  111. package/models/trace/extras/ScriptDuplication.js.map +1 -1
  112. package/models/trace/extras/ThirdParties.d.ts +6 -13
  113. package/models/trace/extras/ThirdParties.js +69 -133
  114. package/models/trace/extras/ThirdParties.js.map +1 -1
  115. package/models/trace/extras/TraceTree.d.ts +15 -3
  116. package/models/trace/extras/TraceTree.js +36 -8
  117. package/models/trace/extras/TraceTree.js.map +1 -1
  118. package/models/trace/extras/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  119. package/models/trace/extras/extras-tsconfig.json +2 -2
  120. package/models/trace/extras/extras.d.ts +881 -787
  121. package/models/trace/extras/extras.js +881 -787
  122. package/models/trace/handlers/AsyncJSCallsHandler.js +36 -4
  123. package/models/trace/handlers/AsyncJSCallsHandler.js.map +1 -1
  124. package/models/trace/handlers/InvalidationsHandler.js +1 -0
  125. package/models/trace/handlers/InvalidationsHandler.js.map +1 -1
  126. package/models/trace/handlers/ModelHandlers.d.ts +0 -1
  127. package/models/trace/handlers/ModelHandlers.js +0 -1
  128. package/models/trace/handlers/ModelHandlers.js.map +1 -1
  129. package/models/trace/handlers/NetworkRequestsHandler.js +1 -1
  130. package/models/trace/handlers/NetworkRequestsHandler.js.map +1 -1
  131. package/models/trace/handlers/RendererHandler.d.ts +1 -1
  132. package/models/trace/handlers/RendererHandler.js +2 -2
  133. package/models/trace/handlers/RendererHandler.js.map +1 -1
  134. package/models/trace/handlers/ScreenshotsHandler.js +3 -1
  135. package/models/trace/handlers/ScreenshotsHandler.js.map +1 -1
  136. package/models/trace/handlers/ScriptsHandler.d.ts +12 -0
  137. package/models/trace/handlers/ScriptsHandler.js +93 -1
  138. package/models/trace/handlers/ScriptsHandler.js.map +1 -1
  139. package/models/trace/handlers/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  140. package/models/trace/handlers/handlers-tsconfig.json +2 -3
  141. package/models/trace/helpers/Network.d.ts +5 -0
  142. package/models/trace/helpers/Network.js +17 -0
  143. package/models/trace/helpers/Network.js.map +1 -1
  144. package/models/trace/helpers/SamplesIntegrator.js +19 -23
  145. package/models/trace/helpers/SamplesIntegrator.js.map +1 -1
  146. package/models/trace/helpers/SyntheticEvents.d.ts +0 -1
  147. package/models/trace/helpers/SyntheticEvents.js +0 -4
  148. package/models/trace/helpers/SyntheticEvents.js.map +1 -1
  149. package/models/trace/helpers/Trace.d.ts +2 -1
  150. package/models/trace/helpers/Trace.js +101 -1
  151. package/models/trace/helpers/Trace.js.map +1 -1
  152. package/models/trace/helpers/TreeHelpers.d.ts +2 -5
  153. package/models/trace/helpers/TreeHelpers.js +0 -4
  154. package/models/trace/helpers/TreeHelpers.js.map +1 -1
  155. package/models/trace/helpers/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  156. package/models/trace/helpers/helpers-tsconfig.json +2 -2
  157. package/models/trace/insights/{UseCache.d.ts → Cache.d.ts} +2 -2
  158. package/models/trace/insights/{UseCache.js → Cache.js} +11 -5
  159. package/models/trace/insights/Cache.js.map +1 -0
  160. package/models/trace/insights/Common.d.ts +21 -2
  161. package/models/trace/insights/Common.js +86 -2
  162. package/models/trace/insights/Common.js.map +1 -1
  163. package/models/trace/insights/DocumentLatency.js +2 -8
  164. package/models/trace/insights/DocumentLatency.js.map +1 -1
  165. package/models/trace/insights/DuplicatedJavaScript.d.ts +7 -4
  166. package/models/trace/insights/DuplicatedJavaScript.js +25 -5
  167. package/models/trace/insights/DuplicatedJavaScript.js.map +1 -1
  168. package/models/trace/insights/ForcedReflow.d.ts +5 -1
  169. package/models/trace/insights/ForcedReflow.js +6 -2
  170. package/models/trace/insights/ForcedReflow.js.map +1 -1
  171. package/models/trace/insights/InteractionToNextPaint.d.ts +1 -0
  172. package/models/trace/insights/InteractionToNextPaint.js +3 -0
  173. package/models/trace/insights/InteractionToNextPaint.js.map +1 -1
  174. package/models/trace/insights/LegacyJavaScript.d.ts +32 -0
  175. package/models/trace/insights/LegacyJavaScript.js +77 -0
  176. package/models/trace/insights/LegacyJavaScript.js.map +1 -0
  177. package/models/trace/insights/Models.d.ts +3 -1
  178. package/models/trace/insights/Models.js +3 -1
  179. package/models/trace/insights/Models.js.map +1 -1
  180. package/models/trace/insights/ModernHTTP.d.ts +51 -0
  181. package/models/trace/insights/ModernHTTP.js +187 -0
  182. package/models/trace/insights/ModernHTTP.js.map +1 -0
  183. package/models/trace/insights/NetworkDependencyTree.js +1 -1
  184. package/models/trace/insights/NetworkDependencyTree.js.map +1 -1
  185. package/models/trace/insights/ThirdParties.d.ts +1 -5
  186. package/models/trace/insights/ThirdParties.js +8 -21
  187. package/models/trace/insights/ThirdParties.js.map +1 -1
  188. package/models/trace/insights/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  189. package/models/trace/insights/insights-tsconfig.json +8 -3
  190. package/models/trace/insights/types.d.ts +1 -0
  191. package/models/trace/insights/types.js.map +1 -1
  192. package/models/trace/lantern/core/core-tsconfig.json +2 -2
  193. package/models/trace/lantern/core/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  194. package/models/trace/lantern/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  195. package/models/trace/lantern/graph/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  196. package/models/trace/lantern/graph/graph-tsconfig.json +2 -2
  197. package/models/trace/lantern/lantern-tsconfig.json +2 -2
  198. package/models/trace/lantern/metrics/Metric.d.ts +4 -4
  199. package/models/trace/lantern/metrics/Metric.js +4 -6
  200. package/models/trace/lantern/metrics/Metric.js.map +1 -1
  201. package/models/trace/lantern/metrics/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  202. package/models/trace/lantern/metrics/metrics-tsconfig.json +2 -2
  203. package/models/trace/lantern/simulation/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  204. package/models/trace/lantern/simulation/simulation-tsconfig.json +2 -2
  205. package/models/trace/lantern/types/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  206. package/models/trace/lantern/types/types-tsconfig.json +2 -2
  207. package/models/trace/trace-tsconfig.json +2 -2
  208. package/models/trace/types/Configuration.d.ts +2 -0
  209. package/models/trace/types/Configuration.js.map +1 -1
  210. package/models/trace/types/TraceEvents.d.ts +28 -50
  211. package/models/trace/types/TraceEvents.js +8 -23
  212. package/models/trace/types/TraceEvents.js.map +1 -1
  213. package/models/trace/types/devtools_entrypoint-bundle-typescript-tsconfig.json +2 -2
  214. package/models/trace/types/types-tsconfig.json +2 -2
  215. package/package.json +3 -2
  216. package/test/test-trace-engine.mjs +19 -17
  217. package/third_party/legacy-javascript/legacy-javascript.d.ts +1 -0
  218. package/third_party/legacy-javascript/legacy-javascript.js +1 -0
  219. package/core/platform/ServerTiming.d.ts +0 -31
  220. package/core/platform/ServerTiming.js +0 -212
  221. package/core/platform/ServerTiming.js.map +0 -1
  222. package/models/trace/handlers/ServerTimingsHandler.d.ts +0 -9
  223. package/models/trace/handlers/ServerTimingsHandler.js +0 -106
  224. package/models/trace/handlers/ServerTimingsHandler.js.map +0 -1
  225. package/models/trace/insights/UseCache.js.map +0 -1
@@ -283,7 +283,7 @@ export class TraceProcessor extends EventTarget {
283
283
  * Sort the insight models based on the impact of each insight's estimated savings, additionally weighted by the
284
284
  * worst metrics according to field data (if present).
285
285
  */
286
- sortInsightSet(insights, insightSet, metadata) {
286
+ sortInsightSet(insightSet, metadata) {
287
287
  // The initial order of the insights is alphabetical, based on `front_end/models/trace/insights/Models.ts`.
288
288
  // The order here provides a baseline that groups insights in a more logical way.
289
289
  const baselineOrder = {
@@ -302,18 +302,22 @@ export class TraceProcessor extends EventTarget {
302
302
  DuplicatedJavaScript: null,
303
303
  SlowCSSSelector: null,
304
304
  ForcedReflow: null,
305
- UseCache: null,
305
+ Cache: null,
306
+ ModernHTTP: null,
307
+ LegacyJavaScript: null,
306
308
  };
307
309
  // Determine the weights for each metric based on field data, utilizing the same scoring curve that Lighthouse uses.
308
310
  const weights = Insights.Common.calculateMetricWeightsForSorting(insightSet, metadata);
309
311
  // Normalize the estimated savings to a single number, weighted by its relative impact
310
312
  // to the page experience based on the same scoring curve that Lighthouse uses.
311
- const observedLcp = Insights.Common.getLCP(insights, insightSet.id)?.value;
312
- const observedCls = Insights.Common.getCLS(insights, insightSet.id).value;
313
+ const observedLcpMicro = Insights.Common.getLCP(this.#insights, insightSet.id)?.value;
314
+ const observedLcp = observedLcpMicro ? Helpers.Timing.microToMilli(observedLcpMicro) : Types.Timing.Milli(0);
315
+ const observedCls = Insights.Common.getCLS(this.#insights, insightSet.id).value;
313
316
  // INP is special - if users did not interact with the page, we'll have no INP, but we should still
314
317
  // be able to prioritize insights based on this metric. When we observe no interaction, instead use
315
318
  // a default value for the baseline INP.
316
- const observedInp = Insights.Common.getINP(insights, insightSet.id)?.value ?? 200;
319
+ const observedInpMicro = Insights.Common.getINP(this.#insights, insightSet.id)?.value;
320
+ const observedInp = observedInpMicro ? Helpers.Timing.microToMilli(observedInpMicro) : Types.Timing.Milli(200);
317
321
  const observedLcpScore = observedLcp !== undefined ? Insights.Common.evaluateLCPMetricScore(observedLcp) : undefined;
318
322
  const observedInpScore = Insights.Common.evaluateINPMetricScore(observedInp);
319
323
  const observedClsScore = Insights.Common.evaluateCLSMetricScore(observedCls);
@@ -363,7 +367,7 @@ export class TraceProcessor extends EventTarget {
363
367
  }
364
368
  insightSet.model = newModel;
365
369
  }
366
- #computeInsightSet(insights, parsedTrace, context, options) {
370
+ #computeInsightSet(parsedTrace, context, options) {
367
371
  let id, urlString, navigation;
368
372
  if (context.navigation) {
369
373
  id = context.navigationId;
@@ -412,88 +416,104 @@ export class TraceProcessor extends EventTarget {
412
416
  bounds: context.bounds,
413
417
  model,
414
418
  };
415
- insights.set(insightSet.id, insightSet);
416
- this.sortInsightSet(insights, insightSet, options.metadata ?? null);
419
+ if (!this.#insights) {
420
+ this.#insights = new Map();
421
+ }
422
+ this.#insights.set(insightSet.id, insightSet);
423
+ this.sortInsightSet(insightSet, options.metadata ?? null);
417
424
  }
418
425
  /**
419
426
  * Run all the insights and set the result to `#insights`.
420
427
  */
421
428
  #computeInsights(parsedTrace, traceEvents, options) {
429
+ // This insights map will be populated by the helper methods.
422
430
  this.#insights = new Map();
431
+ // Filter main frame navigations to those that have the necessary data (frameId and navigationId).
432
+ // TODO(cjamcl): Does this filtering makes the "use the next nav as the end time" logic potentially broken? Are navs without nav id or frame even real?
423
433
  const navigations = parsedTrace.Meta.mainFrameNavigations.filter(navigation => navigation.args.frame && navigation.args.data?.navigationId);
424
- // Check if there is a meaningful chunk of work happening prior to the first navigation.
425
- // If so, we run the insights on that initial bounds.
426
- // Otherwise, there are no navigations and we do a no-navigation insights pass on the entire trace.
427
- if (navigations.length) {
428
- const bounds = Helpers.Timing.traceWindowFromMicroSeconds(parsedTrace.Meta.traceBounds.min, navigations[0].ts);
429
- // When using "Record and reload" option, it typically takes ~5ms. So use 50ms to be safe.
430
- const threshold = Helpers.Timing.milliToMicro(50);
431
- if (bounds.range > threshold) {
432
- const context = {
433
- bounds,
434
- frameId: parsedTrace.Meta.mainFrameId,
435
- };
436
- this.#computeInsightSet(this.#insights, parsedTrace, context, options);
437
- }
438
- // If threshold is not met, then the very beginning of the trace is ignored by the insights engine.
434
+ this.#computeInsightsForInitialTracePeriod(parsedTrace, navigations, options);
435
+ for (const [index, navigation] of navigations.entries()) {
436
+ const min = navigation.ts;
437
+ // Use trace end for the last navigation, otherwise use the start of the next navigation.
438
+ const max = index + 1 < navigations.length ? navigations[index + 1].ts : parsedTrace.Meta.traceBounds.max;
439
+ const bounds = Helpers.Timing.traceWindowFromMicroSeconds(min, max);
440
+ this.#computeInsightsForNavigation(navigation, bounds, parsedTrace, traceEvents, options);
439
441
  }
440
- else {
442
+ }
443
+ /**
444
+ * Computes insights for the period before the first navigation, or for the entire trace if no navigations exist.
445
+ */
446
+ #computeInsightsForInitialTracePeriod(parsedTrace, navigations, options) {
447
+ // Determine bounds: Use the period before the first navigation if navigations exist, otherwise use the entire trace bounds.
448
+ const bounds = navigations.length > 0 ?
449
+ Helpers.Timing.traceWindowFromMicroSeconds(parsedTrace.Meta.traceBounds.min, navigations[0].ts) :
450
+ parsedTrace.Meta.traceBounds;
451
+ // Define threshold for considering the pre-navigation period significant enough to analyze.
452
+ // When using "Record and reload" option, it typically takes ~5ms. So use 50ms to be safe.
453
+ const threshold = Helpers.Timing.milliToMicro(50);
454
+ // Compute insights if either:
455
+ // 1. There are no navigations (we analyze the whole trace).
456
+ // 2. There are navigations, AND the initial period before the first navigation is longer than the threshold.
457
+ const shouldComputeInsights = navigations.length === 0 || bounds.range > threshold;
458
+ // If navigations exist but the initial period is below the threshold, we intentionally do nothing for this portion of the trace.
459
+ if (shouldComputeInsights) {
441
460
  const context = {
442
- bounds: parsedTrace.Meta.traceBounds,
461
+ bounds,
443
462
  frameId: parsedTrace.Meta.mainFrameId,
463
+ // No navigation or lantern context applies to this initial/no-navigation period.
444
464
  };
445
- this.#computeInsightSet(this.#insights, parsedTrace, context, options);
446
- }
447
- // Now run the insights for each navigation in isolation.
448
- for (const [i, navigation] of navigations.entries()) {
449
- // The above filter guarantees these are present.
450
- const frameId = navigation.args.frame;
451
- const navigationId = navigation.args.data?.navigationId;
452
- // The lantern sub-context is optional on InsightSetContext, so not setting it is OK.
453
- // This is also a hedge against an error inside Lantern resulting in breaking the entire performance panel.
454
- // Additionally, many trace fixtures are too old to be processed by Lantern.
455
- let lantern;
456
- try {
457
- options.logger?.start('insights:createLanternContext');
458
- lantern = this.#createLanternContext(parsedTrace, traceEvents, frameId, navigationId, options);
459
- }
460
- catch (e) {
461
- // Don't allow an error in constructing the Lantern graphs to break the rest of the trace processor.
462
- // Log unexpected errors, but suppress anything that occurs from a trace being too old.
463
- // Otherwise tests using old fixtures become way too noisy.
464
- const expectedErrors = [
465
- 'mainDocumentRequest not found',
466
- 'missing metric scores for main frame',
467
- 'missing metric: FCP',
468
- 'missing metric: LCP',
469
- 'No network requests found in trace',
470
- 'Trace is too old',
471
- ];
472
- if (!(e instanceof Lantern.Core.LanternError)) {
473
- // If this wasn't a managed LanternError, the stack trace is likely needed for debugging.
474
- console.error(e);
475
- }
476
- else if (!expectedErrors.some(err => e.message === err)) {
477
- // To reduce noise from tests, only print errors that are not expected to occur because a trace is
478
- // too old (for which there is no single check).
479
- console.error(e);
480
- }
465
+ this.#computeInsightSet(parsedTrace, context, options);
466
+ }
467
+ }
468
+ /**
469
+ * Computes insights for a specific navigation event.
470
+ */
471
+ #computeInsightsForNavigation(navigation, bounds, parsedTrace, traceEvents, options) {
472
+ const frameId = navigation.args.frame;
473
+ // Guaranteed by the filter in #computeInsights
474
+ const navigationId = navigation.args.data?.navigationId;
475
+ // The lantern sub-context is optional on InsightSetContext, so not setting it is OK.
476
+ // This is also a hedge against an error inside Lantern resulting in breaking the entire performance panel.
477
+ // Additionally, many trace fixtures are too old to be processed by Lantern.
478
+ let lantern;
479
+ try {
480
+ options.logger?.start('insights:createLanternContext');
481
+ lantern = this.#createLanternContext(parsedTrace, traceEvents, frameId, navigationId, options);
482
+ }
483
+ catch (e) {
484
+ // Handle Lantern errors gracefully
485
+ // Don't allow an error in constructing the Lantern graphs to break the rest of the trace processor.
486
+ // Log unexpected errors, but suppress anything that occurs from a trace being too old.
487
+ // Otherwise tests using old fixtures become way too noisy.
488
+ const expectedErrors = [
489
+ 'mainDocumentRequest not found',
490
+ 'missing metric scores for main frame',
491
+ 'missing metric: FCP',
492
+ 'missing metric: LCP',
493
+ 'No network requests found in trace',
494
+ 'Trace is too old',
495
+ ];
496
+ if (!(e instanceof Lantern.Core.LanternError)) {
497
+ // If this wasn't a managed LanternError, the stack trace is likely needed for debugging.
498
+ console.error(e);
481
499
  }
482
- finally {
483
- options.logger?.end('insights:createLanternContext');
500
+ else if (!expectedErrors.some(err => e.message === err)) {
501
+ // To reduce noise from tests, only print errors that are not expected to occur because a trace is
502
+ // too old (for which there is no single check).
503
+ console.error(e);
484
504
  }
485
- const min = navigation.ts;
486
- const max = i + 1 < navigations.length ? navigations[i + 1].ts : parsedTrace.Meta.traceBounds.max;
487
- const bounds = Helpers.Timing.traceWindowFromMicroSeconds(min, max);
488
- const context = {
489
- bounds,
490
- frameId,
491
- navigation,
492
- navigationId,
493
- lantern,
494
- };
495
- this.#computeInsightSet(this.#insights, parsedTrace, context, options);
496
505
  }
506
+ finally {
507
+ options.logger?.end('insights:createLanternContext');
508
+ }
509
+ const context = {
510
+ bounds,
511
+ frameId,
512
+ navigation,
513
+ navigationId,
514
+ lantern,
515
+ };
516
+ this.#computeInsightSet(parsedTrace, context, options);
497
517
  }
498
518
  }
499
519
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"Processor.js","sourceRoot":"","sources":["../../../../../../front_end/models/trace/Processor.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,QAAQ,MAAM,wBAAwB,CAAC;AACnD,OAAO,KAAK,OAAO,MAAM,sBAAsB,CAAC;AAChD,OAAO,KAAK,QAAQ,MAAM,wBAAwB,CAAC;AACnD,OAAO,KAAK,OAAO,MAAM,sBAAsB,CAAC;AAChD,OAAO,KAAK,sBAAsB,MAAM,6BAA6B,CAAC;AAEtE,OAAO,KAAK,KAAK,MAAM,kBAAkB,CAAC;AAS1C,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAE7B;IADnB,MAAM,CAAU,SAAS,GAAG,oBAAoB,CAAC;IACjD,YAAmB,IAAuC,EAAE,OAAkB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CAAC","sourcesContent":["// Copyright 2023 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 Handlers from './handlers/handlers.js';\nimport * as Helpers from './helpers/helpers.js';\nimport * as Insights from './insights/insights.js';\nimport * as Lantern from './lantern/lantern.js';\nimport * as LanternComputationData from './LanternComputationData.js';\nimport type * as Model from './ModelImpl.js';\nimport * as Types from './types/types.js';\n\nconst enum Status {\n IDLE = 'IDLE',\n PARSING = 'PARSING',\n FINISHED_PARSING = 'FINISHED_PARSING',\n ERRORED_WHILE_PARSING = 'ERRORED_WHILE_PARSING',\n}\n\nexport class TraceParseProgressEvent extends Event {\n static readonly eventName = 'traceparseprogress';\n constructor(public data: Model.TraceParseEventProgressData, init: EventInit = {bubbles: true}) {\n super(TraceParseProgressEvent.eventName, init);\n }\n}\n\n/**\n * Parsing a trace can take time. On large traces we see a breakdown of time like so:\n * - handleEvent() loop: ~20%\n * - finalize() loop: ~60%\n * - shallowClone calls: ~20%\n * The numbers below are set so we can report a progress percentage of [0...1]\n */\nconst enum ProgressPhase {\n HANDLE_EVENT = 0.2,\n FINALIZE = 0.8,\n CLONE = 1.0,\n}\nfunction calculateProgress(value: number, phase: ProgressPhase): number {\n // Finalize values should be [0.2...0.8]\n if (phase === ProgressPhase.FINALIZE) {\n return (value * (ProgressPhase.FINALIZE - ProgressPhase.HANDLE_EVENT)) + ProgressPhase.HANDLE_EVENT;\n }\n return value * phase;\n}\n\ndeclare global {\n interface HTMLElementEventMap {\n [TraceParseProgressEvent.eventName]: TraceParseProgressEvent;\n }\n}\n\nexport class TraceProcessor extends EventTarget {\n // We force the Meta handler to be enabled, so the TraceHandlers type here is\n // the model handlers the user passes in and the Meta handler.\n readonly #traceHandlers: Partial<Handlers.Types.Handlers>;\n #status = Status.IDLE;\n #modelConfiguration = Types.Configuration.defaults();\n #data: Handlers.Types.ParsedTrace|null = null;\n #insights: Insights.Types.TraceInsightSets|null = null;\n\n static createWithAllHandlers(): TraceProcessor {\n return new TraceProcessor(Handlers.ModelHandlers, Types.Configuration.defaults());\n }\n\n /**\n * This function is kept for testing with `stub`.\n */\n static getInsightRunners(): Insights.Types.InsightModelsType {\n return {...Insights.Models};\n }\n\n constructor(traceHandlers: Partial<Handlers.Types.Handlers>, modelConfiguration?: Types.Configuration.Configuration) {\n super();\n\n this.#verifyHandlers(traceHandlers);\n this.#traceHandlers = {\n Meta: Handlers.ModelHandlers.Meta,\n ...traceHandlers,\n };\n if (modelConfiguration) {\n this.#modelConfiguration = modelConfiguration;\n }\n this.#passConfigToHandlers();\n }\n\n #passConfigToHandlers(): void {\n for (const handler of Object.values(this.#traceHandlers)) {\n // Bit of an odd double check, but without this TypeScript refuses to let\n // you call the function as it thinks it might be undefined.\n if ('handleUserConfig' in handler && handler.handleUserConfig) {\n handler.handleUserConfig(this.#modelConfiguration);\n }\n }\n }\n\n /**\n * When the user passes in a set of handlers, we want to ensure that we have all\n * the required handlers. Handlers can depend on other handlers, so if the user\n * passes in FooHandler which depends on BarHandler, they must also pass in\n * BarHandler too. This method verifies that all dependencies are met, and\n * throws if not.\n **/\n #verifyHandlers(providedHandlers: Partial<Handlers.Types.Handlers>): void {\n // Tiny optimisation: if the amount of provided handlers matches the amount\n // of handlers in the Handlers.ModelHandlers object, that means that the\n // user has passed in every handler we have. So therefore they cannot have\n // missed any, and there is no need to iterate through the handlers and\n // check the dependencies.\n if (Object.keys(providedHandlers).length === Object.keys(Handlers.ModelHandlers).length) {\n return;\n }\n const requiredHandlerKeys = new Set<Handlers.Types.HandlerName>();\n for (const [handlerName, handler] of Object.entries(providedHandlers)) {\n requiredHandlerKeys.add(handlerName as Handlers.Types.HandlerName);\n const deps = 'deps' in handler ? handler.deps() : [];\n for (const depName of deps) {\n requiredHandlerKeys.add(depName);\n }\n }\n\n const providedHandlerKeys = new Set(Object.keys(providedHandlers));\n // We always force the Meta handler to be enabled when creating the\n // Processor, so if it is missing from the set the user gave us that is OK,\n // as we will have enabled it anyway.\n requiredHandlerKeys.delete('Meta');\n\n for (const requiredKey of requiredHandlerKeys) {\n if (!providedHandlerKeys.has(requiredKey)) {\n throw new Error(`Required handler ${requiredKey} not provided.`);\n }\n }\n }\n\n reset(): void {\n if (this.#status === Status.PARSING) {\n throw new Error('Trace processor can\\'t reset while parsing.');\n }\n\n const handlers = Object.values(this.#traceHandlers);\n for (const handler of handlers) {\n handler.reset();\n }\n\n this.#data = null;\n this.#insights = null;\n this.#status = Status.IDLE;\n }\n\n async parse(traceEvents: readonly Types.Events.Event[], options: Types.Configuration.ParseOptions): Promise<void> {\n if (this.#status !== Status.IDLE) {\n throw new Error(`Trace processor can't start parsing when not idle. Current state: ${this.#status}`);\n }\n\n options.logger?.start('total');\n try {\n this.#status = Status.PARSING;\n options.logger?.start('parse');\n await this.#computeParsedTrace(traceEvents, options);\n options.logger?.end('parse');\n if (this.#data && !options.isCPUProfile) { // We do not calculate insights for CPU Profiles.\n options.logger?.start('insights');\n this.#computeInsights(this.#data, traceEvents, options);\n options.logger?.end('insights');\n }\n this.#status = Status.FINISHED_PARSING;\n } catch (e) {\n this.#status = Status.ERRORED_WHILE_PARSING;\n throw e;\n } finally {\n options.logger?.end('total');\n }\n }\n\n /**\n * Run all the handlers and set the result to `#data`.\n */\n async #computeParsedTrace(traceEvents: readonly Types.Events.Event[], options: Types.Configuration.ParseOptions):\n Promise<void> {\n /**\n * We want to yield regularly to maintain responsiveness. If we yield too often, we're wasting idle time.\n * We could do this by checking `performance.now()` regularly, but it's an expensive call in such a hot loop.\n * `eventsPerChunk` is an approximated proxy metric.\n * But how big a chunk? We're aiming for long tasks that are no smaller than 100ms and not bigger than 200ms.\n * It's CPU dependent, so it should be calibrated on oldish hardware.\n * Illustration of a previous change to `eventsPerChunk`: https://imgur.com/wzp8BnR\n */\n const eventsPerChunk = 50_000;\n // Convert to array so that we are able to iterate all handlers multiple times.\n const sortedHandlers = [...sortHandlers(this.#traceHandlers).entries()];\n\n // Reset.\n for (const [, handler] of sortedHandlers) {\n handler.reset();\n }\n\n options.logger?.start('parse:handleEvent');\n\n // Handle each event.\n for (let i = 0; i < traceEvents.length; ++i) {\n // Every so often we take a break just to render.\n if (i % eventsPerChunk === 0 && i) {\n // Take the opportunity to provide status update events.\n const percent = calculateProgress(i / traceEvents.length, ProgressPhase.HANDLE_EVENT);\n this.dispatchEvent(new TraceParseProgressEvent({percent}));\n // TODO(paulirish): consider using `scheduler.yield()` or `scheduler.postTask(() => {}, {priority: 'user-blocking'})`\n await new Promise(resolve => setTimeout(resolve, 0));\n }\n const event = traceEvents[i];\n for (let j = 0; j < sortedHandlers.length; ++j) {\n const [, handler] = sortedHandlers[j];\n handler.handleEvent(event);\n }\n }\n\n options.logger?.end('parse:handleEvent');\n\n // Finalize.\n for (let i = 0; i < sortedHandlers.length; i++) {\n const [name, handler] = sortedHandlers[i];\n if (handler.finalize) {\n options.logger?.start(`parse:${name}:finalize`);\n // Yield to the UI because finalize() calls can be expensive\n // TODO(jacktfranklin): consider using `scheduler.yield()` or `scheduler.postTask(() => {}, {priority: 'user-blocking'})`\n await new Promise(resolve => setTimeout(resolve, 0));\n await handler.finalize(options);\n options.logger?.end(`parse:${name}:finalize`);\n }\n const percent = calculateProgress(i / sortedHandlers.length, ProgressPhase.FINALIZE);\n this.dispatchEvent(new TraceParseProgressEvent({percent}));\n }\n\n // Handlers that depend on other handlers do so via .data(), which used to always\n // return a shallow clone of its internal data structures. However, that pattern\n // easily results in egregious amounts of allocation. Now .data() does not do any\n // cloning, and it happens here instead so that users of the trace processor may\n // still assume that the parsed data is theirs.\n // See: crbug/41484172\n const shallowClone = (value: unknown, recurse = true): unknown => {\n if (value instanceof Map) {\n return new Map(value);\n }\n if (value instanceof Set) {\n return new Set(value);\n }\n if (Array.isArray(value)) {\n return [...value];\n }\n if (typeof value === 'object' && value && recurse) {\n const obj: Record<string, unknown> = {};\n for (const [key, v] of Object.entries(value)) {\n obj[key] = shallowClone(v, false);\n }\n return obj;\n }\n return value;\n };\n\n options.logger?.start('parse:clone');\n const parsedTrace = {};\n for (const [name, handler] of Object.entries(this.#traceHandlers)) {\n const data = shallowClone(handler.data());\n Object.assign(parsedTrace, {[name]: data});\n }\n options.logger?.end('parse:clone');\n\n this.dispatchEvent(new TraceParseProgressEvent({percent: ProgressPhase.CLONE}));\n\n this.#data = parsedTrace as Handlers.Types.ParsedTrace;\n }\n\n get parsedTrace(): Handlers.Types.ParsedTrace|null {\n if (this.#status !== Status.FINISHED_PARSING) {\n return null;\n }\n\n return this.#data;\n }\n\n get insights(): Insights.Types.TraceInsightSets|null {\n if (this.#status !== Status.FINISHED_PARSING) {\n return null;\n }\n\n return this.#insights;\n }\n\n #createLanternContext(\n parsedTrace: Handlers.Types.ParsedTrace, traceEvents: readonly Types.Events.Event[], frameId: string,\n navigationId: string, options: Types.Configuration.ParseOptions): Insights.Types.LanternContext|undefined {\n // Check for required handlers.\n if (!parsedTrace.NetworkRequests || !parsedTrace.Workers || !parsedTrace.PageLoadMetrics) {\n return;\n }\n if (!parsedTrace.NetworkRequests.byTime.length) {\n throw new Lantern.Core.LanternError('No network requests found in trace');\n }\n\n const navStarts = parsedTrace.Meta.navigationsByFrameId.get(frameId);\n const navStartIndex = navStarts?.findIndex(n => n.args.data?.navigationId === navigationId);\n if (!navStarts || navStartIndex === undefined || navStartIndex === -1) {\n throw new Lantern.Core.LanternError('Could not find navigation start');\n }\n\n const startTime = navStarts[navStartIndex].ts;\n const endTime = navStartIndex + 1 < navStarts.length ? navStarts[navStartIndex + 1].ts : Number.POSITIVE_INFINITY;\n const boundedTraceEvents = traceEvents.filter(e => e.ts >= startTime && e.ts < endTime);\n\n // Lantern.Types.TraceEvent and Types.Events.Event represent the same\n // object - a trace event - but one is more flexible than the other. It should be safe to cast between them.\n const trace: Lantern.Types.Trace = {\n traceEvents: boundedTraceEvents as unknown as Lantern.Types.TraceEvent[],\n };\n\n const requests = LanternComputationData.createNetworkRequests(trace, parsedTrace, startTime, endTime);\n const graph = LanternComputationData.createGraph(requests, trace, parsedTrace);\n const processedNavigation = LanternComputationData.createProcessedNavigation(parsedTrace, frameId, navigationId);\n\n const networkAnalysis = Lantern.Core.NetworkAnalyzer.analyze(requests);\n if (!networkAnalysis) {\n return;\n }\n\n const lanternSettings: Lantern.Types.Simulation.Settings = {\n // TODO(crbug.com/372674229): if devtools throttling was on, does this network analysis capture\n // that? Do we need to set 'devtools' throttlingMethod?\n networkAnalysis,\n throttlingMethod: 'provided',\n ...options.lanternSettings,\n };\n const simulator: Lantern.Simulation.Simulator<Types.Events.SyntheticNetworkRequest> =\n Lantern.Simulation.Simulator.createSimulator(lanternSettings);\n\n const computeData = {graph, simulator, processedNavigation};\n const fcpResult = Lantern.Metrics.FirstContentfulPaint.compute(computeData);\n const lcpResult = Lantern.Metrics.LargestContentfulPaint.compute(computeData, {fcpResult});\n const interactiveResult = Lantern.Metrics.Interactive.compute(computeData, {lcpResult});\n const tbtResult = Lantern.Metrics.TotalBlockingTime.compute(computeData, {fcpResult, interactiveResult});\n const metrics = {\n firstContentfulPaint: fcpResult,\n interactive: interactiveResult,\n largestContentfulPaint: lcpResult,\n totalBlockingTime: tbtResult,\n };\n\n return {graph, simulator, metrics};\n }\n\n /**\n * Sort the insight models based on the impact of each insight's estimated savings, additionally weighted by the\n * worst metrics according to field data (if present).\n */\n sortInsightSet(\n insights: Insights.Types.TraceInsightSets, insightSet: Insights.Types.InsightSet,\n metadata: Types.File.MetaData|null): void {\n // The initial order of the insights is alphabetical, based on `front_end/models/trace/insights/Models.ts`.\n // The order here provides a baseline that groups insights in a more logical way.\n const baselineOrder: Record<keyof Insights.Types.InsightModels, null> = {\n InteractionToNextPaint: null,\n LCPPhases: null,\n LCPDiscovery: null,\n CLSCulprits: null,\n RenderBlocking: null,\n NetworkDependencyTree: null,\n ImageDelivery: null,\n DocumentLatency: null,\n FontDisplay: null,\n Viewport: null,\n DOMSize: null,\n ThirdParties: null,\n DuplicatedJavaScript: null,\n SlowCSSSelector: null,\n ForcedReflow: null,\n UseCache: null,\n };\n\n // Determine the weights for each metric based on field data, utilizing the same scoring curve that Lighthouse uses.\n const weights = Insights.Common.calculateMetricWeightsForSorting(insightSet, metadata);\n\n // Normalize the estimated savings to a single number, weighted by its relative impact\n // to the page experience based on the same scoring curve that Lighthouse uses.\n const observedLcp = Insights.Common.getLCP(insights, insightSet.id)?.value;\n const observedCls = Insights.Common.getCLS(insights, insightSet.id).value;\n\n // INP is special - if users did not interact with the page, we'll have no INP, but we should still\n // be able to prioritize insights based on this metric. When we observe no interaction, instead use\n // a default value for the baseline INP.\n const observedInp = Insights.Common.getINP(insights, insightSet.id)?.value ?? 200;\n\n const observedLcpScore =\n observedLcp !== undefined ? Insights.Common.evaluateLCPMetricScore(observedLcp) : undefined;\n const observedInpScore = Insights.Common.evaluateINPMetricScore(observedInp);\n const observedClsScore = Insights.Common.evaluateCLSMetricScore(observedCls);\n\n const insightToSortingRank = new Map<string, number>();\n for (const [name, model] of Object.entries(insightSet.model)) {\n const lcp = model.metricSavings?.LCP ?? 0;\n const inp = model.metricSavings?.INP ?? 0;\n const cls = model.metricSavings?.CLS ?? 0;\n\n const lcpPostSavings = observedLcp !== undefined ? Math.max(0, observedLcp - lcp) : undefined;\n const inpPostSavings = Math.max(0, observedInp - inp);\n const clsPostSavings = Math.max(0, observedCls - cls);\n\n let score = 0;\n if (weights.lcp && lcp && observedLcpScore !== undefined && lcpPostSavings !== undefined) {\n score += weights.lcp * (Insights.Common.evaluateLCPMetricScore(lcpPostSavings) - observedLcpScore);\n }\n if (weights.inp && inp && observedInpScore !== undefined) {\n score += weights.inp * (Insights.Common.evaluateINPMetricScore(inpPostSavings) - observedInpScore);\n }\n if (weights.cls && cls && observedClsScore !== undefined) {\n score += weights.cls * (Insights.Common.evaluateCLSMetricScore(clsPostSavings) - observedClsScore);\n }\n\n insightToSortingRank.set(name, score);\n }\n\n // Now perform the actual sorting.\n const baselineOrderKeys = Object.keys(baselineOrder);\n const orderedKeys = Object.keys(insightSet.model);\n orderedKeys.sort((a, b) => {\n const a1 = baselineOrderKeys.indexOf(a);\n const b1 = baselineOrderKeys.indexOf(b);\n if (a1 >= 0 && b1 >= 0) {\n return a1 - b1;\n }\n if (a1 >= 0) {\n return -1;\n }\n if (b1 >= 0) {\n return 1;\n }\n return 0;\n });\n orderedKeys.sort((a, b) => (insightToSortingRank.get(b) ?? 0) - (insightToSortingRank.get(a) ?? 0));\n\n const newModel = {} as Insights.Types.InsightModels;\n for (const key of orderedKeys as Array<keyof Insights.Types.InsightModels>) {\n const model = insightSet.model[key];\n // @ts-expect-error Maybe someday typescript will be powerful enough to handle this.\n newModel[key] = model;\n }\n insightSet.model = newModel;\n }\n\n #computeInsightSet(\n insights: Insights.Types.TraceInsightSets, parsedTrace: Handlers.Types.ParsedTrace,\n context: Insights.Types.InsightSetContext, options: Types.Configuration.ParseOptions): void {\n let id, urlString, navigation;\n if (context.navigation) {\n id = context.navigationId;\n urlString =\n parsedTrace.Meta.finalDisplayUrlByNavigationId.get(context.navigationId) ?? parsedTrace.Meta.mainFrameURL;\n navigation = context.navigation;\n } else {\n id = Types.Events.NO_NAVIGATION;\n urlString = parsedTrace.Meta.finalDisplayUrlByNavigationId.get('') ?? parsedTrace.Meta.mainFrameURL;\n }\n\n const model = {} as Insights.Types.InsightSet['model'];\n\n for (const [name, insight] of Object.entries(TraceProcessor.getInsightRunners())) {\n let insightResult;\n try {\n options.logger?.start(`insights:${name}`);\n insightResult = insight.generateInsight(parsedTrace, context);\n insightResult.frameId = context.frameId;\n const navId = context.navigation?.args.data?.navigationId;\n if (navId) {\n insightResult.navigationId = navId;\n }\n } catch (err) {\n insightResult = err;\n } finally {\n options.logger?.end(`insights:${name}`);\n }\n Object.assign(model, {[name]: insightResult});\n }\n\n let url;\n try {\n url = new URL(urlString);\n } catch {\n // We're pretty sure this only happens for our test fixture: missing-url.json.gz. Shouldn't\n // happen for real traces.\n return;\n }\n\n const insightSet: Insights.Types.InsightSet = {\n id,\n url,\n navigation,\n frameId: context.frameId,\n bounds: context.bounds,\n model,\n };\n insights.set(insightSet.id, insightSet);\n this.sortInsightSet(insights, insightSet, options.metadata ?? null);\n }\n\n /**\n * Run all the insights and set the result to `#insights`.\n */\n #computeInsights(\n parsedTrace: Handlers.Types.ParsedTrace, traceEvents: readonly Types.Events.Event[],\n options: Types.Configuration.ParseOptions): void {\n this.#insights = new Map();\n\n const navigations = parsedTrace.Meta.mainFrameNavigations.filter(\n navigation => navigation.args.frame && navigation.args.data?.navigationId);\n\n // Check if there is a meaningful chunk of work happening prior to the first navigation.\n // If so, we run the insights on that initial bounds.\n // Otherwise, there are no navigations and we do a no-navigation insights pass on the entire trace.\n if (navigations.length) {\n const bounds = Helpers.Timing.traceWindowFromMicroSeconds(parsedTrace.Meta.traceBounds.min, navigations[0].ts);\n // When using \"Record and reload\" option, it typically takes ~5ms. So use 50ms to be safe.\n const threshold = Helpers.Timing.milliToMicro(50 as Types.Timing.Milli);\n if (bounds.range > threshold) {\n const context: Insights.Types.InsightSetContext = {\n bounds,\n frameId: parsedTrace.Meta.mainFrameId,\n };\n this.#computeInsightSet(this.#insights, parsedTrace, context, options);\n }\n // If threshold is not met, then the very beginning of the trace is ignored by the insights engine.\n } else {\n const context: Insights.Types.InsightSetContext = {\n bounds: parsedTrace.Meta.traceBounds,\n frameId: parsedTrace.Meta.mainFrameId,\n };\n this.#computeInsightSet(this.#insights, parsedTrace, context, options);\n }\n\n // Now run the insights for each navigation in isolation.\n for (const [i, navigation] of navigations.entries()) {\n // The above filter guarantees these are present.\n const frameId = navigation.args.frame;\n const navigationId = navigation.args.data?.navigationId as string;\n\n // The lantern sub-context is optional on InsightSetContext, so not setting it is OK.\n // This is also a hedge against an error inside Lantern resulting in breaking the entire performance panel.\n // Additionally, many trace fixtures are too old to be processed by Lantern.\n let lantern;\n try {\n options.logger?.start('insights:createLanternContext');\n lantern = this.#createLanternContext(parsedTrace, traceEvents, frameId, navigationId, options);\n } catch (e) {\n // Don't allow an error in constructing the Lantern graphs to break the rest of the trace processor.\n // Log unexpected errors, but suppress anything that occurs from a trace being too old.\n // Otherwise tests using old fixtures become way too noisy.\n const expectedErrors = [\n 'mainDocumentRequest not found',\n 'missing metric scores for main frame',\n 'missing metric: FCP',\n 'missing metric: LCP',\n 'No network requests found in trace',\n 'Trace is too old',\n ];\n if (!(e instanceof Lantern.Core.LanternError)) {\n // If this wasn't a managed LanternError, the stack trace is likely needed for debugging.\n console.error(e);\n } else if (!expectedErrors.some(err => e.message === err)) {\n // To reduce noise from tests, only print errors that are not expected to occur because a trace is\n // too old (for which there is no single check).\n console.error(e);\n }\n } finally {\n options.logger?.end('insights:createLanternContext');\n }\n\n const min = navigation.ts;\n const max = i + 1 < navigations.length ? navigations[i + 1].ts : parsedTrace.Meta.traceBounds.max;\n const bounds = Helpers.Timing.traceWindowFromMicroSeconds(min, max);\n const context: Insights.Types.InsightSetContext = {\n bounds,\n frameId,\n navigation,\n navigationId,\n lantern,\n };\n\n this.#computeInsightSet(this.#insights, parsedTrace, context, options);\n }\n }\n}\n\n/**\n * Some Handlers need data provided by others. Dependencies of a handler handler are\n * declared in the `deps` field.\n * @returns A map from trace event handler name to trace event handler whose entries\n * iterate in such a way that each handler is visited after its dependencies.\n */\nexport function sortHandlers(traceHandlers: Partial<{[key in Handlers.Types.HandlerName]: Handlers.Types.Handler}>):\n Map<Handlers.Types.HandlerName, Handlers.Types.Handler> {\n const sortedMap = new Map<Handlers.Types.HandlerName, Handlers.Types.Handler>();\n const visited = new Set<Handlers.Types.HandlerName>();\n const visitHandler = (handlerName: Handlers.Types.HandlerName): void => {\n if (sortedMap.has(handlerName)) {\n return;\n }\n if (visited.has(handlerName)) {\n let stackPath = '';\n for (const handler of visited) {\n if (stackPath || handler === handlerName) {\n stackPath += `${handler}->`;\n }\n }\n stackPath += handlerName;\n throw new Error(`Found dependency cycle in trace event handlers: ${stackPath}`);\n }\n visited.add(handlerName);\n const handler = traceHandlers[handlerName];\n if (!handler) {\n return;\n }\n const deps = handler.deps?.();\n if (deps) {\n deps.forEach(visitHandler);\n }\n sortedMap.set(handlerName, handler);\n };\n\n for (const handlerName of Object.keys(traceHandlers)) {\n visitHandler(handlerName as Handlers.Types.HandlerName);\n }\n return sortedMap;\n}\n"]}
1
+ {"version":3,"file":"Processor.js","sourceRoot":"","sources":["../../../../../../front_end/models/trace/Processor.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,QAAQ,MAAM,wBAAwB,CAAC;AACnD,OAAO,KAAK,OAAO,MAAM,sBAAsB,CAAC;AAChD,OAAO,KAAK,QAAQ,MAAM,wBAAwB,CAAC;AACnD,OAAO,KAAK,OAAO,MAAM,sBAAsB,CAAC;AAChD,OAAO,KAAK,sBAAsB,MAAM,6BAA6B,CAAC;AAEtE,OAAO,KAAK,KAAK,MAAM,kBAAkB,CAAC;AAS1C,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IAE7B;IADnB,MAAM,CAAU,SAAS,GAAG,oBAAoB,CAAC;IACjD,YAAmB,IAAuC,EAAE,OAAkB,EAAC,OAAO,EAAE,IAAI,EAAC;QAC3F,KAAK,CAAC,uBAAuB,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;QAD9B,SAAI,GAAJ,IAAI,CAAmC;IAE1D,CAAC;;AAeH,SAAS,iBAAiB,CAAC,KAAa,EAAE,KAAoB;IAC5D,wCAAwC;IACxC,IAAI,KAAK,qCAA2B,EAAE,CAAC;QACrC,OAAO,CAAC,KAAK,GAAG,CAAC,uEAAmD,CAAC,CAAC,uCAA6B,CAAC;IACtG,CAAC;IACD,OAAO,KAAK,GAAG,KAAK,CAAC;AACvB,CAAC;AAQD,MAAM,OAAO,cAAe,SAAQ,WAAW;IAC7C,6EAA6E;IAC7E,8DAA8D;IACrD,cAAc,CAAmC;IAC1D,OAAO,4BAAe;IACtB,mBAAmB,GAAG,KAAK,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC;IACrD,KAAK,GAAoC,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C,GAAG,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;IACtC,CAAC,CAAC;IAEF,KAAK,MAAM,WAAW,IAAI,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,EAAE,CAAC;QACrD,YAAY,CAAC,WAAyC,CAAC,CAAC;IAC1D,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Copyright 2023 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 Handlers from './handlers/handlers.js';\nimport * as Helpers from './helpers/helpers.js';\nimport * as Insights from './insights/insights.js';\nimport * as Lantern from './lantern/lantern.js';\nimport * as LanternComputationData from './LanternComputationData.js';\nimport type * as Model from './ModelImpl.js';\nimport * as Types from './types/types.js';\n\nconst enum Status {\n IDLE = 'IDLE',\n PARSING = 'PARSING',\n FINISHED_PARSING = 'FINISHED_PARSING',\n ERRORED_WHILE_PARSING = 'ERRORED_WHILE_PARSING',\n}\n\nexport class TraceParseProgressEvent extends Event {\n static readonly eventName = 'traceparseprogress';\n constructor(public data: Model.TraceParseEventProgressData, init: EventInit = {bubbles: true}) {\n super(TraceParseProgressEvent.eventName, init);\n }\n}\n\n/**\n * Parsing a trace can take time. On large traces we see a breakdown of time like so:\n * - handleEvent() loop: ~20%\n * - finalize() loop: ~60%\n * - shallowClone calls: ~20%\n * The numbers below are set so we can report a progress percentage of [0...1]\n */\nconst enum ProgressPhase {\n HANDLE_EVENT = 0.2,\n FINALIZE = 0.8,\n CLONE = 1.0,\n}\nfunction calculateProgress(value: number, phase: ProgressPhase): number {\n // Finalize values should be [0.2...0.8]\n if (phase === ProgressPhase.FINALIZE) {\n return (value * (ProgressPhase.FINALIZE - ProgressPhase.HANDLE_EVENT)) + ProgressPhase.HANDLE_EVENT;\n }\n return value * phase;\n}\n\ndeclare global {\n interface HTMLElementEventMap {\n [TraceParseProgressEvent.eventName]: TraceParseProgressEvent;\n }\n}\n\nexport class TraceProcessor extends EventTarget {\n // We force the Meta handler to be enabled, so the TraceHandlers type here is\n // the model handlers the user passes in and the Meta handler.\n readonly #traceHandlers: Partial<Handlers.Types.Handlers>;\n #status = Status.IDLE;\n #modelConfiguration = Types.Configuration.defaults();\n #data: Handlers.Types.ParsedTrace|null = null;\n #insights: Insights.Types.TraceInsightSets|null = null;\n\n static createWithAllHandlers(): TraceProcessor {\n return new TraceProcessor(Handlers.ModelHandlers, Types.Configuration.defaults());\n }\n\n /**\n * This function is kept for testing with `stub`.\n */\n static getInsightRunners(): Insights.Types.InsightModelsType {\n return {...Insights.Models};\n }\n\n constructor(traceHandlers: Partial<Handlers.Types.Handlers>, modelConfiguration?: Types.Configuration.Configuration) {\n super();\n\n this.#verifyHandlers(traceHandlers);\n this.#traceHandlers = {\n Meta: Handlers.ModelHandlers.Meta,\n ...traceHandlers,\n };\n if (modelConfiguration) {\n this.#modelConfiguration = modelConfiguration;\n }\n this.#passConfigToHandlers();\n }\n\n #passConfigToHandlers(): void {\n for (const handler of Object.values(this.#traceHandlers)) {\n // Bit of an odd double check, but without this TypeScript refuses to let\n // you call the function as it thinks it might be undefined.\n if ('handleUserConfig' in handler && handler.handleUserConfig) {\n handler.handleUserConfig(this.#modelConfiguration);\n }\n }\n }\n\n /**\n * When the user passes in a set of handlers, we want to ensure that we have all\n * the required handlers. Handlers can depend on other handlers, so if the user\n * passes in FooHandler which depends on BarHandler, they must also pass in\n * BarHandler too. This method verifies that all dependencies are met, and\n * throws if not.\n **/\n #verifyHandlers(providedHandlers: Partial<Handlers.Types.Handlers>): void {\n // Tiny optimisation: if the amount of provided handlers matches the amount\n // of handlers in the Handlers.ModelHandlers object, that means that the\n // user has passed in every handler we have. So therefore they cannot have\n // missed any, and there is no need to iterate through the handlers and\n // check the dependencies.\n if (Object.keys(providedHandlers).length === Object.keys(Handlers.ModelHandlers).length) {\n return;\n }\n const requiredHandlerKeys = new Set<Handlers.Types.HandlerName>();\n for (const [handlerName, handler] of Object.entries(providedHandlers)) {\n requiredHandlerKeys.add(handlerName as Handlers.Types.HandlerName);\n const deps = 'deps' in handler ? handler.deps() : [];\n for (const depName of deps) {\n requiredHandlerKeys.add(depName);\n }\n }\n\n const providedHandlerKeys = new Set(Object.keys(providedHandlers));\n // We always force the Meta handler to be enabled when creating the\n // Processor, so if it is missing from the set the user gave us that is OK,\n // as we will have enabled it anyway.\n requiredHandlerKeys.delete('Meta');\n\n for (const requiredKey of requiredHandlerKeys) {\n if (!providedHandlerKeys.has(requiredKey)) {\n throw new Error(`Required handler ${requiredKey} not provided.`);\n }\n }\n }\n\n reset(): void {\n if (this.#status === Status.PARSING) {\n throw new Error('Trace processor can\\'t reset while parsing.');\n }\n\n const handlers = Object.values(this.#traceHandlers);\n for (const handler of handlers) {\n handler.reset();\n }\n\n this.#data = null;\n this.#insights = null;\n this.#status = Status.IDLE;\n }\n\n async parse(traceEvents: readonly Types.Events.Event[], options: Types.Configuration.ParseOptions): Promise<void> {\n if (this.#status !== Status.IDLE) {\n throw new Error(`Trace processor can't start parsing when not idle. Current state: ${this.#status}`);\n }\n\n options.logger?.start('total');\n try {\n this.#status = Status.PARSING;\n options.logger?.start('parse');\n await this.#computeParsedTrace(traceEvents, options);\n options.logger?.end('parse');\n if (this.#data && !options.isCPUProfile) { // We do not calculate insights for CPU Profiles.\n options.logger?.start('insights');\n this.#computeInsights(this.#data, traceEvents, options);\n options.logger?.end('insights');\n }\n this.#status = Status.FINISHED_PARSING;\n } catch (e) {\n this.#status = Status.ERRORED_WHILE_PARSING;\n throw e;\n } finally {\n options.logger?.end('total');\n }\n }\n\n /**\n * Run all the handlers and set the result to `#data`.\n */\n async #computeParsedTrace(traceEvents: readonly Types.Events.Event[], options: Types.Configuration.ParseOptions):\n Promise<void> {\n /**\n * We want to yield regularly to maintain responsiveness. If we yield too often, we're wasting idle time.\n * We could do this by checking `performance.now()` regularly, but it's an expensive call in such a hot loop.\n * `eventsPerChunk` is an approximated proxy metric.\n * But how big a chunk? We're aiming for long tasks that are no smaller than 100ms and not bigger than 200ms.\n * It's CPU dependent, so it should be calibrated on oldish hardware.\n * Illustration of a previous change to `eventsPerChunk`: https://imgur.com/wzp8BnR\n */\n const eventsPerChunk = 50_000;\n // Convert to array so that we are able to iterate all handlers multiple times.\n const sortedHandlers = [...sortHandlers(this.#traceHandlers).entries()];\n\n // Reset.\n for (const [, handler] of sortedHandlers) {\n handler.reset();\n }\n\n options.logger?.start('parse:handleEvent');\n\n // Handle each event.\n for (let i = 0; i < traceEvents.length; ++i) {\n // Every so often we take a break just to render.\n if (i % eventsPerChunk === 0 && i) {\n // Take the opportunity to provide status update events.\n const percent = calculateProgress(i / traceEvents.length, ProgressPhase.HANDLE_EVENT);\n this.dispatchEvent(new TraceParseProgressEvent({percent}));\n // TODO(paulirish): consider using `scheduler.yield()` or `scheduler.postTask(() => {}, {priority: 'user-blocking'})`\n await new Promise(resolve => setTimeout(resolve, 0));\n }\n const event = traceEvents[i];\n for (let j = 0; j < sortedHandlers.length; ++j) {\n const [, handler] = sortedHandlers[j];\n handler.handleEvent(event);\n }\n }\n\n options.logger?.end('parse:handleEvent');\n\n // Finalize.\n for (let i = 0; i < sortedHandlers.length; i++) {\n const [name, handler] = sortedHandlers[i];\n if (handler.finalize) {\n options.logger?.start(`parse:${name}:finalize`);\n // Yield to the UI because finalize() calls can be expensive\n // TODO(jacktfranklin): consider using `scheduler.yield()` or `scheduler.postTask(() => {}, {priority: 'user-blocking'})`\n await new Promise(resolve => setTimeout(resolve, 0));\n await handler.finalize(options);\n options.logger?.end(`parse:${name}:finalize`);\n }\n const percent = calculateProgress(i / sortedHandlers.length, ProgressPhase.FINALIZE);\n this.dispatchEvent(new TraceParseProgressEvent({percent}));\n }\n\n // Handlers that depend on other handlers do so via .data(), which used to always\n // return a shallow clone of its internal data structures. However, that pattern\n // easily results in egregious amounts of allocation. Now .data() does not do any\n // cloning, and it happens here instead so that users of the trace processor may\n // still assume that the parsed data is theirs.\n // See: crbug/41484172\n const shallowClone = (value: unknown, recurse = true): unknown => {\n if (value instanceof Map) {\n return new Map(value);\n }\n if (value instanceof Set) {\n return new Set(value);\n }\n if (Array.isArray(value)) {\n return [...value];\n }\n if (typeof value === 'object' && value && recurse) {\n const obj: Record<string, unknown> = {};\n for (const [key, v] of Object.entries(value)) {\n obj[key] = shallowClone(v, false);\n }\n return obj;\n }\n return value;\n };\n\n options.logger?.start('parse:clone');\n const parsedTrace = {};\n for (const [name, handler] of Object.entries(this.#traceHandlers)) {\n const data = shallowClone(handler.data());\n Object.assign(parsedTrace, {[name]: data});\n }\n options.logger?.end('parse:clone');\n\n this.dispatchEvent(new TraceParseProgressEvent({percent: ProgressPhase.CLONE}));\n\n this.#data = parsedTrace as Handlers.Types.ParsedTrace;\n }\n\n get parsedTrace(): Handlers.Types.ParsedTrace|null {\n if (this.#status !== Status.FINISHED_PARSING) {\n return null;\n }\n\n return this.#data;\n }\n\n get insights(): Insights.Types.TraceInsightSets|null {\n if (this.#status !== Status.FINISHED_PARSING) {\n return null;\n }\n\n return this.#insights;\n }\n\n #createLanternContext(\n parsedTrace: Handlers.Types.ParsedTrace, traceEvents: readonly Types.Events.Event[], frameId: string,\n navigationId: string, options: Types.Configuration.ParseOptions): Insights.Types.LanternContext|undefined {\n // Check for required handlers.\n if (!parsedTrace.NetworkRequests || !parsedTrace.Workers || !parsedTrace.PageLoadMetrics) {\n return;\n }\n if (!parsedTrace.NetworkRequests.byTime.length) {\n throw new Lantern.Core.LanternError('No network requests found in trace');\n }\n\n const navStarts = parsedTrace.Meta.navigationsByFrameId.get(frameId);\n const navStartIndex = navStarts?.findIndex(n => n.args.data?.navigationId === navigationId);\n if (!navStarts || navStartIndex === undefined || navStartIndex === -1) {\n throw new Lantern.Core.LanternError('Could not find navigation start');\n }\n\n const startTime = navStarts[navStartIndex].ts;\n const endTime = navStartIndex + 1 < navStarts.length ? navStarts[navStartIndex + 1].ts : Number.POSITIVE_INFINITY;\n const boundedTraceEvents = traceEvents.filter(e => e.ts >= startTime && e.ts < endTime);\n\n // Lantern.Types.TraceEvent and Types.Events.Event represent the same\n // object - a trace event - but one is more flexible than the other. It should be safe to cast between them.\n const trace: Lantern.Types.Trace = {\n traceEvents: boundedTraceEvents as unknown as Lantern.Types.TraceEvent[],\n };\n\n const requests = LanternComputationData.createNetworkRequests(trace, parsedTrace, startTime, endTime);\n const graph = LanternComputationData.createGraph(requests, trace, parsedTrace);\n const processedNavigation = LanternComputationData.createProcessedNavigation(parsedTrace, frameId, navigationId);\n\n const networkAnalysis = Lantern.Core.NetworkAnalyzer.analyze(requests);\n if (!networkAnalysis) {\n return;\n }\n\n const lanternSettings: Lantern.Types.Simulation.Settings = {\n // TODO(crbug.com/372674229): if devtools throttling was on, does this network analysis capture\n // that? Do we need to set 'devtools' throttlingMethod?\n networkAnalysis,\n throttlingMethod: 'provided',\n ...options.lanternSettings,\n };\n const simulator: Lantern.Simulation.Simulator<Types.Events.SyntheticNetworkRequest> =\n Lantern.Simulation.Simulator.createSimulator(lanternSettings);\n\n const computeData = {graph, simulator, processedNavigation};\n const fcpResult = Lantern.Metrics.FirstContentfulPaint.compute(computeData);\n const lcpResult = Lantern.Metrics.LargestContentfulPaint.compute(computeData, {fcpResult});\n const interactiveResult = Lantern.Metrics.Interactive.compute(computeData, {lcpResult});\n const tbtResult = Lantern.Metrics.TotalBlockingTime.compute(computeData, {fcpResult, interactiveResult});\n const metrics = {\n firstContentfulPaint: fcpResult,\n interactive: interactiveResult,\n largestContentfulPaint: lcpResult,\n totalBlockingTime: tbtResult,\n };\n\n return {graph, simulator, metrics};\n }\n\n /**\n * Sort the insight models based on the impact of each insight's estimated savings, additionally weighted by the\n * worst metrics according to field data (if present).\n */\n sortInsightSet(insightSet: Insights.Types.InsightSet, metadata: Types.File.MetaData|null): void {\n // The initial order of the insights is alphabetical, based on `front_end/models/trace/insights/Models.ts`.\n // The order here provides a baseline that groups insights in a more logical way.\n const baselineOrder: Record<keyof Insights.Types.InsightModels, null> = {\n InteractionToNextPaint: null,\n LCPPhases: null,\n LCPDiscovery: null,\n CLSCulprits: null,\n RenderBlocking: null,\n NetworkDependencyTree: null,\n ImageDelivery: null,\n DocumentLatency: null,\n FontDisplay: null,\n Viewport: null,\n DOMSize: null,\n ThirdParties: null,\n DuplicatedJavaScript: null,\n SlowCSSSelector: null,\n ForcedReflow: null,\n Cache: null,\n ModernHTTP: null,\n LegacyJavaScript: null,\n };\n\n // Determine the weights for each metric based on field data, utilizing the same scoring curve that Lighthouse uses.\n const weights = Insights.Common.calculateMetricWeightsForSorting(insightSet, metadata);\n\n // Normalize the estimated savings to a single number, weighted by its relative impact\n // to the page experience based on the same scoring curve that Lighthouse uses.\n const observedLcpMicro = Insights.Common.getLCP(this.#insights, insightSet.id)?.value;\n const observedLcp = observedLcpMicro ? Helpers.Timing.microToMilli(observedLcpMicro) : Types.Timing.Milli(0);\n const observedCls = Insights.Common.getCLS(this.#insights, insightSet.id).value;\n\n // INP is special - if users did not interact with the page, we'll have no INP, but we should still\n // be able to prioritize insights based on this metric. When we observe no interaction, instead use\n // a default value for the baseline INP.\n const observedInpMicro = Insights.Common.getINP(this.#insights, insightSet.id)?.value;\n const observedInp = observedInpMicro ? Helpers.Timing.microToMilli(observedInpMicro) : Types.Timing.Milli(200);\n\n const observedLcpScore =\n observedLcp !== undefined ? Insights.Common.evaluateLCPMetricScore(observedLcp) : undefined;\n const observedInpScore = Insights.Common.evaluateINPMetricScore(observedInp);\n const observedClsScore = Insights.Common.evaluateCLSMetricScore(observedCls);\n\n const insightToSortingRank = new Map<string, number>();\n for (const [name, model] of Object.entries(insightSet.model)) {\n const lcp = model.metricSavings?.LCP ?? 0;\n const inp = model.metricSavings?.INP ?? 0;\n const cls = model.metricSavings?.CLS ?? 0;\n\n const lcpPostSavings =\n observedLcp !== undefined ? Math.max(0, observedLcp - lcp) as Types.Timing.Milli : undefined;\n const inpPostSavings = Math.max(0, observedInp - inp) as Types.Timing.Milli;\n const clsPostSavings = Math.max(0, observedCls - cls);\n\n let score = 0;\n if (weights.lcp && lcp && observedLcpScore !== undefined && lcpPostSavings !== undefined) {\n score += weights.lcp * (Insights.Common.evaluateLCPMetricScore(lcpPostSavings) - observedLcpScore);\n }\n if (weights.inp && inp && observedInpScore !== undefined) {\n score += weights.inp * (Insights.Common.evaluateINPMetricScore(inpPostSavings) - observedInpScore);\n }\n if (weights.cls && cls && observedClsScore !== undefined) {\n score += weights.cls * (Insights.Common.evaluateCLSMetricScore(clsPostSavings) - observedClsScore);\n }\n\n insightToSortingRank.set(name, score);\n }\n\n // Now perform the actual sorting.\n const baselineOrderKeys = Object.keys(baselineOrder);\n const orderedKeys = Object.keys(insightSet.model);\n orderedKeys.sort((a, b) => {\n const a1 = baselineOrderKeys.indexOf(a);\n const b1 = baselineOrderKeys.indexOf(b);\n if (a1 >= 0 && b1 >= 0) {\n return a1 - b1;\n }\n if (a1 >= 0) {\n return -1;\n }\n if (b1 >= 0) {\n return 1;\n }\n return 0;\n });\n orderedKeys.sort((a, b) => (insightToSortingRank.get(b) ?? 0) - (insightToSortingRank.get(a) ?? 0));\n\n const newModel = {} as Insights.Types.InsightModels;\n for (const key of orderedKeys as Array<keyof Insights.Types.InsightModels>) {\n const model = insightSet.model[key];\n // @ts-expect-error Maybe someday typescript will be powerful enough to handle this.\n newModel[key] = model;\n }\n insightSet.model = newModel;\n }\n\n #computeInsightSet(\n parsedTrace: Handlers.Types.ParsedTrace, context: Insights.Types.InsightSetContext,\n options: Types.Configuration.ParseOptions): void {\n let id, urlString, navigation;\n if (context.navigation) {\n id = context.navigationId;\n urlString =\n parsedTrace.Meta.finalDisplayUrlByNavigationId.get(context.navigationId) ?? parsedTrace.Meta.mainFrameURL;\n navigation = context.navigation;\n } else {\n id = Types.Events.NO_NAVIGATION;\n urlString = parsedTrace.Meta.finalDisplayUrlByNavigationId.get('') ?? parsedTrace.Meta.mainFrameURL;\n }\n\n const model = {} as Insights.Types.InsightSet['model'];\n\n for (const [name, insight] of Object.entries(TraceProcessor.getInsightRunners())) {\n let insightResult;\n try {\n options.logger?.start(`insights:${name}`);\n insightResult = insight.generateInsight(parsedTrace, context);\n insightResult.frameId = context.frameId;\n const navId = context.navigation?.args.data?.navigationId;\n if (navId) {\n insightResult.navigationId = navId;\n }\n } catch (err) {\n insightResult = err;\n } finally {\n options.logger?.end(`insights:${name}`);\n }\n Object.assign(model, {[name]: insightResult});\n }\n\n let url;\n try {\n url = new URL(urlString);\n } catch {\n // We're pretty sure this only happens for our test fixture: missing-url.json.gz. Shouldn't\n // happen for real traces.\n return;\n }\n\n const insightSet: Insights.Types.InsightSet = {\n id,\n url,\n navigation,\n frameId: context.frameId,\n bounds: context.bounds,\n model,\n };\n if (!this.#insights) {\n this.#insights = new Map();\n }\n this.#insights.set(insightSet.id, insightSet);\n this.sortInsightSet(insightSet, options.metadata ?? null);\n }\n\n /**\n * Run all the insights and set the result to `#insights`.\n */\n #computeInsights(\n parsedTrace: Handlers.Types.ParsedTrace, traceEvents: readonly Types.Events.Event[],\n options: Types.Configuration.ParseOptions): void {\n // This insights map will be populated by the helper methods.\n this.#insights = new Map();\n\n // Filter main frame navigations to those that have the necessary data (frameId and navigationId).\n // TODO(cjamcl): Does this filtering makes the \"use the next nav as the end time\" logic potentially broken? Are navs without nav id or frame even real?\n const navigations = parsedTrace.Meta.mainFrameNavigations.filter(\n navigation => navigation.args.frame && navigation.args.data?.navigationId);\n\n this.#computeInsightsForInitialTracePeriod(parsedTrace, navigations, options);\n\n for (const [index, navigation] of navigations.entries()) {\n const min = navigation.ts;\n // Use trace end for the last navigation, otherwise use the start of the next navigation.\n const max = index + 1 < navigations.length ? navigations[index + 1].ts : parsedTrace.Meta.traceBounds.max;\n const bounds = Helpers.Timing.traceWindowFromMicroSeconds(min, max);\n this.#computeInsightsForNavigation(navigation, bounds, parsedTrace, traceEvents, options);\n }\n }\n\n /**\n * Computes insights for the period before the first navigation, or for the entire trace if no navigations exist.\n */\n #computeInsightsForInitialTracePeriod(\n parsedTrace: Handlers.Types.ParsedTrace, navigations: readonly Types.Events.NavigationStart[],\n options: Types.Configuration.ParseOptions): void {\n // Determine bounds: Use the period before the first navigation if navigations exist, otherwise use the entire trace bounds.\n const bounds = navigations.length > 0 ?\n Helpers.Timing.traceWindowFromMicroSeconds(parsedTrace.Meta.traceBounds.min, navigations[0].ts) :\n parsedTrace.Meta.traceBounds;\n\n // Define threshold for considering the pre-navigation period significant enough to analyze.\n // When using \"Record and reload\" option, it typically takes ~5ms. So use 50ms to be safe.\n const threshold = Helpers.Timing.milliToMicro(50 as Types.Timing.Milli);\n\n // Compute insights if either:\n // 1. There are no navigations (we analyze the whole trace).\n // 2. There are navigations, AND the initial period before the first navigation is longer than the threshold.\n const shouldComputeInsights = navigations.length === 0 || bounds.range > threshold;\n\n // If navigations exist but the initial period is below the threshold, we intentionally do nothing for this portion of the trace.\n if (shouldComputeInsights) {\n const context: Insights.Types.InsightSetContext = {\n bounds,\n frameId: parsedTrace.Meta.mainFrameId,\n // No navigation or lantern context applies to this initial/no-navigation period.\n };\n this.#computeInsightSet(parsedTrace, context, options);\n }\n }\n\n /**\n * Computes insights for a specific navigation event.\n */\n #computeInsightsForNavigation(\n navigation: Types.Events.NavigationStart, bounds: Types.Timing.TraceWindowMicro,\n parsedTrace: Handlers.Types.ParsedTrace, traceEvents: readonly Types.Events.Event[],\n options: Types.Configuration.ParseOptions): void {\n const frameId = navigation.args.frame;\n // Guaranteed by the filter in #computeInsights\n const navigationId = navigation.args.data?.navigationId as string;\n\n // The lantern sub-context is optional on InsightSetContext, so not setting it is OK.\n // This is also a hedge against an error inside Lantern resulting in breaking the entire performance panel.\n // Additionally, many trace fixtures are too old to be processed by Lantern.\n let lantern: Insights.Types.LanternContext|undefined;\n try {\n options.logger?.start('insights:createLanternContext');\n lantern = this.#createLanternContext(parsedTrace, traceEvents, frameId, navigationId, options);\n } catch (e) {\n // Handle Lantern errors gracefully\n // Don't allow an error in constructing the Lantern graphs to break the rest of the trace processor.\n // Log unexpected errors, but suppress anything that occurs from a trace being too old.\n // Otherwise tests using old fixtures become way too noisy.\n const expectedErrors = [\n 'mainDocumentRequest not found',\n 'missing metric scores for main frame',\n 'missing metric: FCP',\n 'missing metric: LCP',\n 'No network requests found in trace',\n 'Trace is too old',\n ];\n if (!(e instanceof Lantern.Core.LanternError)) {\n // If this wasn't a managed LanternError, the stack trace is likely needed for debugging.\n console.error(e);\n } else if (!expectedErrors.some(err => e.message === err)) {\n // To reduce noise from tests, only print errors that are not expected to occur because a trace is\n // too old (for which there is no single check).\n console.error(e);\n }\n } finally {\n options.logger?.end('insights:createLanternContext');\n }\n\n const context: Insights.Types.InsightSetContext = {\n bounds,\n frameId,\n navigation,\n navigationId,\n lantern,\n };\n this.#computeInsightSet(parsedTrace, context, options);\n }\n}\n\n/**\n * Some Handlers need data provided by others. Dependencies of a handler handler are\n * declared in the `deps` field.\n * @returns A map from trace event handler name to trace event handler whose entries\n * iterate in such a way that each handler is visited after its dependencies.\n */\nexport function sortHandlers(traceHandlers: Partial<{[key in Handlers.Types.HandlerName]: Handlers.Types.Handler}>):\n Map<Handlers.Types.HandlerName, Handlers.Types.Handler> {\n const sortedMap = new Map<Handlers.Types.HandlerName, Handlers.Types.Handler>();\n const visited = new Set<Handlers.Types.HandlerName>();\n const visitHandler = (handlerName: Handlers.Types.HandlerName): void => {\n if (sortedMap.has(handlerName)) {\n return;\n }\n if (visited.has(handlerName)) {\n let stackPath = '';\n for (const handler of visited) {\n if (stackPath || handler === handlerName) {\n stackPath += `${handler}->`;\n }\n }\n stackPath += handlerName;\n throw new Error(`Found dependency cycle in trace event handlers: ${stackPath}`);\n }\n visited.add(handlerName);\n const handler = traceHandlers[handlerName];\n if (!handler) {\n return;\n }\n const deps = handler.deps?.();\n if (deps) {\n deps.forEach(visitHandler);\n }\n sortedMap.set(handlerName, handler);\n };\n\n for (const handlerName of Object.keys(traceHandlers)) {\n visitHandler(handlerName as Handlers.Types.HandlerName);\n }\n return sortedMap;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"TracingManager.js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C5B,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,IAAI;QACF,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC5C,CAAC;QACD,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;QACtD,CAAC;QACD,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QACvB,KAAK,IAAI,CAAC,aAAa,CAAC,UAAU,EAAE,CAAC;IACvC,CAAC;CACF;AAUD,MAAM,iBAAiB;IACZ,eAAe,CAAiB;IACzC,YAAY,cAA8B;QACxC,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;IACxC,CAAC;IAED,2FAA2F;IAC3F,WAAW,CAAC,EAAC,KAAK,EAAE,UAAU,EAAE,WAAW,EAAoC;QAC7E,IAAI,CAAC,eAAe,CAAC,WAAW,CAAC,KAAK,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;IACnE,CAAC;IAED,aAAa,CAAC,EAAC,KAAK,EAAsC;QACxD,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IAC9C,CAAC;IAED,eAAe;QACb,IAAI,CAAC,eAAe,CAAC,eAAe,EAAE,CAAC;IACzC,CAAC;CACF;AAED,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,cAAc,EAAE,EAAC,YAAY,yCAA+B,EAAE,SAAS,EAAE,KAAK,EAAC,CAAC,CAAC","sourcesContent":["// Copyright 2014 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 SDK from '../../core/sdk/sdk.js';\nimport type * as ProtocolProxyApi from '../../generated/protocol-proxy-api.js';\nimport * as Protocol from '../../generated/protocol.js';\n\nimport type * as Types from './types/types.js';\n\nexport class TracingManager extends SDK.SDKModel.SDKModel<void> {\n readonly #tracingAgent: ProtocolProxyApi.TracingApi;\n #activeClient: TracingManagerClient|null;\n #eventsRetrieved: number;\n #finishing?: boolean;\n constructor(target: SDK.Target.Target) {\n super(target);\n this.#tracingAgent = target.tracingAgent();\n target.registerTracingDispatcher(new TracingDispatcher(this));\n\n this.#activeClient = null;\n this.#eventsRetrieved = 0;\n }\n\n bufferUsage(usage?: number, eventCount?: number, percentFull?: number): void {\n if (this.#activeClient) {\n this.#activeClient.tracingBufferUsage(usage || percentFull || 0);\n }\n }\n\n eventsCollected(events: Types.Events.Event[]): void {\n if (!this.#activeClient) {\n return;\n }\n this.#activeClient.traceEventsCollected(events);\n this.#eventsRetrieved += events.length;\n\n // CDP no longer provides an approximate_event_count AKA eventCount. It's always 0.\n // To give some idea of progress we'll compare to a large (900k event) trace.\n // And we'll clamp both sides so the user sees some progress, and never maxed at 99%\n const progress = Math.min((this.#eventsRetrieved / 900_000) + 0.15, 0.90);\n this.#activeClient.eventsRetrievalProgress(progress);\n }\n\n tracingComplete(): void {\n this.#eventsRetrieved = 0;\n if (this.#activeClient) {\n this.#activeClient.tracingComplete();\n this.#activeClient = null;\n }\n this.#finishing = false;\n }\n\n async reset(): Promise<void> {\n // If we have an active client, we should try to stop\n // it before resetting it, else we will leave the\n // backend in a broken state where it thinks we are in\n // the middle of tracing, but we think we are not.\n // Then, any subsequent attempts to record will fail\n // because the backend will not let us start a second\n // tracing session.\n if (this.#activeClient) {\n await this.#tracingAgent.invoke_end();\n }\n this.#eventsRetrieved = 0;\n this.#activeClient = null;\n this.#finishing = false;\n }\n\n // TODO(petermarshall): Use the traceConfig argument instead of deprecated\n // categories + options.\n async start(client: TracingManagerClient, categoryFilter: string, options: string):\n Promise<Protocol.ProtocolResponseWithError> {\n if (this.#activeClient) {\n throw new Error('Tracing is already started');\n }\n const bufferUsageReportingIntervalMs = 500;\n this.#activeClient = client;\n const args = {\n bufferUsageReportingInterval: bufferUsageReportingIntervalMs,\n categories: categoryFilter,\n options,\n transferMode: Protocol.Tracing.StartRequestTransferMode.ReportEvents,\n };\n const response = await this.#tracingAgent.invoke_start(args);\n if (response.getError()) {\n this.#activeClient = null;\n }\n return response;\n }\n\n stop(): void {\n if (!this.#activeClient) {\n throw new Error('Tracing is not started');\n }\n if (this.#finishing) {\n throw new Error('Tracing is already being stopped');\n }\n this.#finishing = true;\n void this.#tracingAgent.invoke_end();\n }\n}\n\nexport interface TracingManagerClient {\n traceEventsCollected(events: Types.Events.Event[]): void;\n\n tracingComplete(): void;\n tracingBufferUsage(usage: number): void;\n eventsRetrievalProgress(progress: number): void;\n}\n\nclass TracingDispatcher implements ProtocolProxyApi.TracingDispatcher {\n readonly #tracingManager: TracingManager;\n constructor(tracingManager: TracingManager) {\n this.#tracingManager = tracingManager;\n }\n\n // `eventCount` will always be 0 as perfetto no longer calculates `approximate_event_count`\n bufferUsage({value, eventCount, percentFull}: Protocol.Tracing.BufferUsageEvent): void {\n this.#tracingManager.bufferUsage(value, eventCount, percentFull);\n }\n\n dataCollected({value}: Protocol.Tracing.DataCollectedEvent): void {\n this.#tracingManager.eventsCollected(value);\n }\n\n tracingComplete(): void {\n this.#tracingManager.tracingComplete();\n }\n}\n\nSDK.SDKModel.SDKModel.register(TracingManager, {capabilities: SDK.Target.Capability.TRACING, autostart: false});\n"]}
1
+ {"version":3,"file":"TracingManager.js","sourceRoot":"","sources":["../../../../../../front_end/models/trace/TracingManager.ts"],"names":[],"mappings":"AAAA,4DAA4D;AAC5D,yEAAyE;AACzE,6BAA6B;AAE7B,OAAO,KAAK,GAAG,MAAM,uBAAuB,CAAC;AAM7C,MAAM,OAAO,cAAe,SAAQ,GAAG,CAAC,QAAQ,CAAC,QAAc;IACpD,aAAa,CAA8B;IACpD,aAAa,CAA4B;IACzC,gBAAgB,CAAS;IACzB,UAAU,CAAW;IACrB,YAAY,MAAyB;QACnC,KAAK,CAAC,MAAM,CAAC,CAAC;QACd,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC,YAAY,EAAE,C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,UAAU,EAAE,CAAC;IACvC,CAAC;CACF;AAUD,MAAM,iBAAiB;IACZ,eAAe,CAAiB;IACzC,YAAY,cAA8B;QACxC,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;IACxC,CAAC;IAED,2FAA2F;IAC3F,WAAW,CAAC,EAAC,KAAK,EAAE,WAAW,EAAoC;QACjE,IAAI,CAAC,eAAe,CAAC,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;IACvD,CAAC;IAED,aAAa,CAAC,EAAC,KAAK,EAAsC;QACxD,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IAC9C,CAAC;IAED,eAAe;QACb,IAAI,CAAC,eAAe,CAAC,eAAe,EAAE,CAAC;IACzC,CAAC;CACF;AAED,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,cAAc,EAAE,EAAC,YAAY,yCAA+B,EAAE,SAAS,EAAE,KAAK,EAAC,CAAC,CAAC","sourcesContent":["// Copyright 2014 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 SDK from '../../core/sdk/sdk.js';\nimport type * as ProtocolProxyApi from '../../generated/protocol-proxy-api.js';\nimport * as Protocol from '../../generated/protocol.js';\n\nimport type * as Types from './types/types.js';\n\nexport class TracingManager extends SDK.SDKModel.SDKModel<void> {\n readonly #tracingAgent: ProtocolProxyApi.TracingApi;\n #activeClient: TracingManagerClient|null;\n #eventsRetrieved: number;\n #finishing?: boolean;\n constructor(target: SDK.Target.Target) {\n super(target);\n this.#tracingAgent = target.tracingAgent();\n target.registerTracingDispatcher(new TracingDispatcher(this));\n\n this.#activeClient = null;\n this.#eventsRetrieved = 0;\n }\n\n bufferUsage(usage?: number, percentFull?: number): void {\n if (this.#activeClient) {\n this.#activeClient.tracingBufferUsage(usage || percentFull || 0);\n }\n }\n\n eventsCollected(events: Types.Events.Event[]): void {\n if (!this.#activeClient) {\n return;\n }\n this.#activeClient.traceEventsCollected(events);\n this.#eventsRetrieved += events.length;\n\n // CDP no longer provides an approximate_event_count AKA eventCount. It's always 0.\n // To give some idea of progress we'll compare to a large (900k event) trace.\n // And we'll clamp both sides so the user sees some progress, and never maxed at 99%\n const progress = Math.min((this.#eventsRetrieved / 900_000) + 0.15, 0.90);\n this.#activeClient.eventsRetrievalProgress(progress);\n }\n\n tracingComplete(): void {\n this.#eventsRetrieved = 0;\n if (this.#activeClient) {\n this.#activeClient.tracingComplete();\n this.#activeClient = null;\n }\n this.#finishing = false;\n }\n\n async reset(): Promise<void> {\n // If we have an active client, we should try to stop\n // it before resetting it, else we will leave the\n // backend in a broken state where it thinks we are in\n // the middle of tracing, but we think we are not.\n // Then, any subsequent attempts to record will fail\n // because the backend will not let us start a second\n // tracing session.\n if (this.#activeClient) {\n await this.#tracingAgent.invoke_end();\n }\n this.#eventsRetrieved = 0;\n this.#activeClient = null;\n this.#finishing = false;\n }\n\n async start(client: TracingManagerClient, categoryFilter: string): Promise<Protocol.ProtocolResponseWithError> {\n if (this.#activeClient) {\n throw new Error('Tracing is already started');\n }\n const bufferUsageReportingIntervalMs = 500;\n this.#activeClient = client;\n const args = {\n bufferUsageReportingInterval: bufferUsageReportingIntervalMs,\n transferMode: Protocol.Tracing.StartRequestTransferMode.ReportEvents,\n traceConfig: {\n recordMode: Protocol.Tracing.TraceConfigRecordMode.RecordUntilFull,\n traceBufferSizeInKb: 400 * 1000,\n includedCategories: categoryFilter.split(','),\n },\n };\n const response = await this.#tracingAgent.invoke_start(args);\n if (response.getError()) {\n this.#activeClient = null;\n }\n return response;\n }\n\n stop(): void {\n if (!this.#activeClient) {\n throw new Error('Tracing is not started');\n }\n if (this.#finishing) {\n throw new Error('Tracing is already being stopped');\n }\n this.#finishing = true;\n void this.#tracingAgent.invoke_end();\n }\n}\n\nexport interface TracingManagerClient {\n traceEventsCollected(events: Types.Events.Event[]): void;\n\n tracingComplete(): void;\n tracingBufferUsage(usage: number): void;\n eventsRetrievalProgress(progress: number): void;\n}\n\nclass TracingDispatcher implements ProtocolProxyApi.TracingDispatcher {\n readonly #tracingManager: TracingManager;\n constructor(tracingManager: TracingManager) {\n this.#tracingManager = tracingManager;\n }\n\n // `eventCount` will always be 0 as perfetto no longer calculates `approximate_event_count`\n bufferUsage({value, percentFull}: Protocol.Tracing.BufferUsageEvent): void {\n this.#tracingManager.bufferUsage(value, percentFull);\n }\n\n dataCollected({value}: Protocol.Tracing.DataCollectedEvent): void {\n this.#tracingManager.eventsCollected(value);\n }\n\n tracingComplete(): void {\n this.#tracingManager.tracingComplete();\n }\n}\n\nSDK.SDKModel.SDKModel.register(TracingManager, {capabilities: SDK.Target.Capability.TRACING, autostart: false});\n"]}
@@ -1 +1 @@
1
- {"compilerOptions":{"composite":true,"outDir":".","baseUrl":".","rootDir":"../../../../../../front_end/models/trace"},"files":["../../../../../../front_end/models/trace/trace.ts"],"references":[{"path":"./trace-tsconfig.json"}]}
1
+ {"compilerOptions":{"composite":true,"outDir":".","baseUrl":".","rootDir":"../../../../../../front_end/models/trace"},"files":["../../../../../../front_end/models/trace/trace.ts"],"references":[{"path":"./trace-tsconfig.json"},{"path":"extras/bundle-tsconfig.json"},{"path":"handlers/bundle-tsconfig.json"},{"path":"helpers/bundle-tsconfig.json"},{"path":"insights/bundle-tsconfig.json"},{"path":"lantern/bundle-tsconfig.json"},{"path":"types/bundle-tsconfig.json"}]}
@@ -18,6 +18,7 @@
18
18
  "noImplicitOverride": true,
19
19
  "noImplicitReturns": true,
20
20
  "noUnusedLocals": false,
21
+ "noUnusedParameters": true,
21
22
  "outDir": ".",
22
23
  "rootDir": "../../../../../../front_end/models/trace",
23
24
  "skipLibCheck": true,
@@ -32,12 +33,29 @@
32
33
  "../../../../../../front_end/models/trace/trace.ts",
33
34
  "../../../../../../front_end/legacy/legacy-defs.d.ts",
34
35
  "../../../../../../front_end/global_typings/global_defs.d.ts",
35
- "../../../../../../node_modules/@types/filesystem/index.d.ts",
36
- "../../../../../../node_modules/@types/wicg-task-scheduling/index.d.ts"
36
+ "../../../../../../node_modules/@types/filesystem/index.d.ts"
37
37
  ],
38
38
  "references": [
39
39
  {
40
40
  "path": "./trace-tsconfig.json"
41
+ },
42
+ {
43
+ "path": "extras/bundle-tsconfig.json"
44
+ },
45
+ {
46
+ "path": "handlers/bundle-tsconfig.json"
47
+ },
48
+ {
49
+ "path": "helpers/bundle-tsconfig.json"
50
+ },
51
+ {
52
+ "path": "insights/bundle-tsconfig.json"
53
+ },
54
+ {
55
+ "path": "lantern/bundle-tsconfig.json"
56
+ },
57
+ {
58
+ "path": "types/bundle-tsconfig.json"
41
59
  }
42
60
  ]
43
61
  }
@@ -1,15 +1,4 @@
1
- import type * as Handlers from '../handlers/handlers.js';
2
- type GeneratedFileSizes = {
3
- errorMessage: string;
4
- } | {
5
- files: Record<string, number>;
6
- unmappedBytes: number;
7
- totalBytes: number;
8
- };
9
- /**
10
- * Using a script's contents and source map, attribute every generated byte to an authored source file.
11
- */
12
- export declare function computeGeneratedFileSizes(script: Handlers.ModelHandlers.Scripts.Script): GeneratedFileSizes;
1
+ import * as Handlers from '../handlers/handlers.js';
13
2
  export declare function normalizeSource(source: string): string;
14
3
  /**
15
4
  * The key is a source map `sources` entry (these are URLs/file paths), but normalized
@@ -46,8 +35,15 @@ export type ScriptDuplication = Map<string, {
46
35
  * on sources that are too small, and calculates esimatedDuplicateBytes.
47
36
  */
48
37
  export declare function normalizeDuplication(duplication: ScriptDuplication): void;
38
+ export declare function getNodeModuleName(source: string): string;
49
39
  /**
50
- * Returns a @see ScriptDuplication for the given collection of script contents + source maps.
40
+ * Returns 2 @see ScriptDuplication for the given collection of script contents + source maps:
41
+ *
42
+ * 1. `duplication` keys correspond to authored files
43
+ * 2. `duplication` keys correspond to authored files, except all files within the same
44
+ * node_module package are aggregated under the same entry.
51
45
  */
52
- export declare function computeScriptDuplication(scriptsData: Handlers.ModelHandlers.Scripts.ScriptsData): ScriptDuplication;
53
- export {};
46
+ export declare function computeScriptDuplication(scriptsData: Handlers.ModelHandlers.Scripts.ScriptsData): {
47
+ duplication: ScriptDuplication;
48
+ duplicationGroupedByNodeModules: ScriptDuplication;
49
+ };