lighthouse 13.6.0-dev.20261112 → 13.6.0-dev.20261117

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 (152) hide show
  1. package/.agents/skills/update-ard-port/SKILL.md +1 -1
  2. package/cli/bin.js +8 -3
  3. package/cli/open-file.js +1 -1
  4. package/cli/printer.js +1 -1
  5. package/cli/run.d.ts +7 -0
  6. package/cli/run.js +42 -5
  7. package/cli/sentry-prompt.js +2 -1
  8. package/cli/test/smokehouse/frontends/smokehouse-bin.js +1 -1
  9. package/cli/test/smokehouse/lighthouse-runners/cli.js +1 -2
  10. package/cli/test/smokehouse/report-assert.js +1 -2
  11. package/cli/test/smokehouse/smokehouse.js +1 -2
  12. package/core/audits/autocomplete.js +1 -2
  13. package/core/audits/baseline.d.ts +3 -0
  14. package/core/audits/bootup-time.js +1 -2
  15. package/core/audits/errors-in-console.js +1 -2
  16. package/core/audits/mainthread-work-breakdown.js +1 -2
  17. package/core/audits/metrics.d.ts +2 -2
  18. package/core/audits/metrics.js +1 -1
  19. package/core/computed/computed-artifact.js +1 -2
  20. package/core/computed/entity-classification.d.ts +3 -3
  21. package/core/computed/entity-classification.js +5 -3
  22. package/core/computed/js-bundles.js +1 -2
  23. package/core/computed/lcp-network-record.js +1 -1
  24. package/core/computed/load-simulator.d.ts +5 -3
  25. package/core/computed/load-simulator.js +9 -2
  26. package/core/computed/metrics/lcp-breakdown.d.ts +19 -0
  27. package/core/computed/metrics/lcp-breakdown.js +71 -8
  28. package/core/computed/metrics/responsiveness.d.ts +5 -3
  29. package/core/computed/metrics/responsiveness.js +1 -1
  30. package/core/computed/metrics/time-to-first-byte.js +3 -1
  31. package/core/computed/metrics/timing-summary.d.ts +7 -5
  32. package/core/computed/metrics/timing-summary.js +3 -4
  33. package/core/computed/navigation-insights.d.ts +5 -3
  34. package/core/computed/navigation-insights.js +1 -1
  35. package/core/computed/network-analysis.js +1 -2
  36. package/core/computed/page-dependency-graph.d.ts +5 -3
  37. package/core/computed/page-dependency-graph.js +5 -2
  38. package/core/computed/trace-engine-result.d.ts +7 -5
  39. package/core/computed/trace-engine-result.js +9 -14
  40. package/core/computed/unused-css.d.ts +2 -2
  41. package/core/computed/unused-css.js +1 -1
  42. package/core/config/config.js +1 -2
  43. package/core/gather/base-artifacts.js +1 -2
  44. package/core/gather/driver/environment.js +1 -2
  45. package/core/gather/driver/navigation.js +1 -2
  46. package/core/gather/driver/network-monitor.js +1 -2
  47. package/core/gather/driver/prepare.js +1 -2
  48. package/core/gather/driver/storage.js +1 -2
  49. package/core/gather/driver/target-manager.js +1 -2
  50. package/core/gather/driver/wait-for-condition.js +1 -2
  51. package/core/gather/driver.js +1 -2
  52. package/core/gather/gatherers/agentic/ard.js +1 -1
  53. package/core/gather/gatherers/agentic/llms-txt.js +1 -2
  54. package/core/gather/gatherers/image-elements.js +1 -2
  55. package/core/gather/gatherers/seo/robots-txt.js +1 -2
  56. package/core/gather/gatherers/stacks.js +1 -2
  57. package/core/gather/gatherers/stylesheets.js +1 -2
  58. package/core/gather/navigation-runner.js +1 -1
  59. package/core/gather/runner-helpers.js +1 -2
  60. package/core/gather/session.js +1 -2
  61. package/core/gather/snapshot-runner.js +1 -2
  62. package/core/gather/timespan-runner.js +1 -2
  63. package/core/lib/asset-saver.js +1 -2
  64. package/core/lib/baseline/web-features-data.json +12 -3
  65. package/core/lib/baseline/web-features-metadata.json +1 -1
  66. package/core/lib/csp-evaluator.js +1 -1
  67. package/core/lib/deprecations-strings.d.ts +0 -2
  68. package/core/lib/deprecations-strings.js +1 -18
  69. package/core/lib/i18n/i18n.js +1 -2
  70. package/core/lib/lighthouse-logger.d.ts +127 -0
  71. package/core/lib/lighthouse-logger.js +319 -0
  72. package/core/lib/median-run.d.ts +16 -6
  73. package/core/lib/median-run.js +13 -6
  74. package/core/lib/network-recorder.js +1 -2
  75. package/core/lib/network-request.d.ts +2 -2
  76. package/core/lib/network-request.js +1 -1
  77. package/core/lib/page-functions.js +2 -2
  78. package/core/lib/script-helpers.d.ts +23 -8
  79. package/core/lib/script-helpers.js +7 -6
  80. package/core/lib/sentry-reporter.d.ts +59 -0
  81. package/core/lib/sentry-reporter.js +281 -0
  82. package/core/lib/sentry.d.ts +7 -7
  83. package/core/lib/sentry.js +23 -40
  84. package/core/lib/stack-packs.js +1 -1
  85. package/core/lib/timing-trace-saver.d.ts +2 -2
  86. package/core/lib/timing-trace-saver.js +1 -1
  87. package/core/lib/tracehouse/task-summary.d.ts +16 -4
  88. package/core/lib/tracehouse/task-summary.js +6 -5
  89. package/core/lib/tracehouse/trace-processor.d.ts +6 -6
  90. package/core/lib/tracehouse/trace-processor.js +1 -1
  91. package/core/lib/traces/metric-trace-events.js +1 -2
  92. package/core/lib/url-utils.d.ts +4 -4
  93. package/core/lib/url-utils.js +1 -1
  94. package/core/runner.js +1 -2
  95. package/dist/report/bundle.esm.js +10 -10
  96. package/dist/report/flow.js +12 -12
  97. package/dist/report/standalone.js +11 -11
  98. package/package.json +19 -21
  99. package/report/renderer/text-encoding.d.ts +3 -5
  100. package/report/renderer/text-encoding.js +19 -33
  101. package/report/types/augment-dom.d.ts +0 -4
  102. package/shared/localization/locales/ar-XB.json +3 -0
  103. package/shared/localization/locales/ar.json +3 -0
  104. package/shared/localization/locales/bg.json +3 -0
  105. package/shared/localization/locales/ca.json +75 -72
  106. package/shared/localization/locales/cs.json +3 -0
  107. package/shared/localization/locales/da.json +3 -0
  108. package/shared/localization/locales/de.json +3 -0
  109. package/shared/localization/locales/el.json +3 -0
  110. package/shared/localization/locales/en-GB.json +3 -0
  111. package/shared/localization/locales/es-419.json +3 -0
  112. package/shared/localization/locales/es.json +3 -0
  113. package/shared/localization/locales/fi.json +3 -0
  114. package/shared/localization/locales/fil.json +3 -0
  115. package/shared/localization/locales/fr.json +3 -0
  116. package/shared/localization/locales/he.json +3 -0
  117. package/shared/localization/locales/hi.json +11 -8
  118. package/shared/localization/locales/hr.json +3 -0
  119. package/shared/localization/locales/hu.json +3 -0
  120. package/shared/localization/locales/id.json +3 -0
  121. package/shared/localization/locales/it.json +3 -0
  122. package/shared/localization/locales/ja.json +3 -0
  123. package/shared/localization/locales/ko.json +3 -0
  124. package/shared/localization/locales/lt.json +3 -0
  125. package/shared/localization/locales/lv.json +5 -2
  126. package/shared/localization/locales/nl.json +3 -0
  127. package/shared/localization/locales/no.json +3 -0
  128. package/shared/localization/locales/pl.json +3 -0
  129. package/shared/localization/locales/pt-PT.json +3 -0
  130. package/shared/localization/locales/pt.json +32 -29
  131. package/shared/localization/locales/ro.json +3 -0
  132. package/shared/localization/locales/ru.json +3 -0
  133. package/shared/localization/locales/sk.json +3 -0
  134. package/shared/localization/locales/sl.json +3 -0
  135. package/shared/localization/locales/sr-Latn.json +3 -0
  136. package/shared/localization/locales/sr.json +3 -0
  137. package/shared/localization/locales/sv.json +3 -0
  138. package/shared/localization/locales/ta.json +3 -0
  139. package/shared/localization/locales/te.json +3 -0
  140. package/shared/localization/locales/th.json +3 -0
  141. package/shared/localization/locales/tr.json +3 -0
  142. package/shared/localization/locales/uk.json +3 -0
  143. package/shared/localization/locales/vi.json +3 -0
  144. package/shared/localization/locales/zh-HK.json +3 -0
  145. package/shared/localization/locales/zh-TW.json +3 -0
  146. package/shared/localization/locales/zh.json +3 -0
  147. package/third-party/ard/README.md +1 -1
  148. package/third-party/ard/ard.js +1 -1
  149. package/tsconfig.json +2 -42
  150. package/types/artifacts.d.ts +7 -1
  151. package/types/internal/test.d.ts +5 -0
  152. package/report/types/buffer.d.ts +0 -19
@@ -5,7 +5,11 @@
5
5
  */
6
6
 
7
7
 
8
- /** @param {LH.Result} lhr @param {string} auditName */
8
+ /**
9
+ * @template {{audits: Record<string, {numericValue?: number}>}} T
10
+ * @param {T} lhr
11
+ * @param {string} auditName
12
+ */
9
13
  const getNumericValue = (lhr, auditName) => lhr.audits[auditName]?.numericValue || NaN;
10
14
 
11
15
  /**
@@ -21,7 +25,8 @@ function getMedianValue(numbers) {
21
25
  }
22
26
 
23
27
  /**
24
- * @param {LH.Result} lhr
28
+ * @template {{audits: Record<string, {numericValue?: number}>}} T
29
+ * @param {T} lhr
25
30
  * @param {number} medianFcp
26
31
  * @param {number} medianInteractive
27
32
  */
@@ -41,8 +46,9 @@ function getMedianSortValue(lhr, medianFcp, medianInteractive) {
41
46
  * We avoid the median of single measures like the performance score because they can still exhibit
42
47
  * outlier behavior at the beginning or end of load.
43
48
  *
44
- * @param {Array<LH.Result>} runs
45
- * @return {LH.Result}
49
+ * @template {{audits: Record<string, {numericValue?: number}>}} T
50
+ * @param {Array<T>} runs
51
+ * @return {T}
46
52
  */
47
53
  function computeMedianRun(runs) {
48
54
  const missingFcp = runs.some(run =>
@@ -78,8 +84,9 @@ function computeMedianRun(runs) {
78
84
  }
79
85
 
80
86
  /**
81
- * @param {Array<LH.Result>} runs
82
- * @return {Array<LH.Result>}
87
+ * @template {{audits: Record<string, {numericValue?: number}>}} T
88
+ * @param {Array<T>} runs
89
+ * @return {Array<T>}
83
90
  */
84
91
  function filterToValidRuns(runs) {
85
92
  return runs
@@ -6,8 +6,7 @@
6
6
 
7
7
  import {EventEmitter} from 'events';
8
8
 
9
- import log from 'lighthouse-logger';
10
-
9
+ import log from './lighthouse-logger.js';
11
10
  import * as LH from '../../types/lh.js';
12
11
  import * as Lantern from './lantern/lantern.js';
13
12
  import {NetworkRequest} from './network-request.js';
@@ -73,10 +73,10 @@ export class NetworkRequest {
73
73
  static isHstsRequest(record: NetworkRequest): boolean;
74
74
  /**
75
75
  * Returns whether the network request was sent encoded.
76
- * @param {NetworkRequest} record
76
+ * @param {Pick<LH.Artifacts.NetworkRequest, 'responseHeaders'>} record
77
77
  * @return {boolean}
78
78
  */
79
- static isContentEncoded(record: NetworkRequest): boolean;
79
+ static isContentEncoded(record: Pick<LH.Artifacts.NetworkRequest, "responseHeaders">): boolean;
80
80
  /**
81
81
  * Resource size is almost always the right one to be using because of the below:
82
82
  * `transferSize = resourceSize + headers.length`.
@@ -663,7 +663,7 @@ class NetworkRequest {
663
663
 
664
664
  /**
665
665
  * Returns whether the network request was sent encoded.
666
- * @param {NetworkRequest} record
666
+ * @param {Pick<LH.Artifacts.NetworkRequest, 'responseHeaders'>} record
667
667
  * @return {boolean}
668
668
  */
669
669
  static isContentEncoded(record) {
@@ -525,9 +525,9 @@ function isBundledEnvironment() {
525
525
  const require = createRequire(import.meta.url);
526
526
 
527
527
  try {
528
- // Not foolproof, but `lighthouse-logger` is a dependency of lighthouse that should always be resolvable.
528
+ // Not foolproof, but `debug` is a dependency of lighthouse that should always be resolvable.
529
529
  // `require.resolve` will only throw in atypical/bundled environments.
530
- require.resolve('lighthouse-logger');
530
+ require.resolve('debug');
531
531
  return false;
532
532
  } catch (err) {
533
533
  return true;
@@ -1,9 +1,14 @@
1
1
  /**
2
- * @param {LH.Artifacts.NetworkRequest[]} networkRecords
3
- * @param {LH.Artifacts.Script} script
4
- * @return {LH.Artifacts.NetworkRequest|undefined}
2
+ * @template {{url: string, frameId?: string, redirectDestination?: T}} T
3
+ * @param {T[]} networkRecords
4
+ * @param {Pick<LH.Artifacts.Script, 'url'|'executionContextAuxData'>} script
5
+ * @return {T|undefined}
5
6
  */
6
- export function getRequestForScript(networkRecords: LH.Artifacts.NetworkRequest[], script: LH.Artifacts.Script): LH.Artifacts.NetworkRequest | undefined;
7
+ export function getRequestForScript<T extends {
8
+ url: string;
9
+ frameId?: string;
10
+ redirectDestination?: T;
11
+ }>(networkRecords: T[], script: Pick<LH.Artifacts.Script, "url" | "executionContextAuxData">): T | undefined;
7
12
  /**
8
13
  * @param {LH.Artifacts.Script} script
9
14
  * @return {boolean}
@@ -16,22 +21,32 @@ export function isInline(script: LH.Artifacts.Script): boolean;
16
21
  *
17
22
  * This differs from `estimateTransferSize` only in that is subtracts the response headers from the estimate.
18
23
  *
19
- * @param {LH.Artifacts.NetworkRequest|undefined} networkRecord
24
+ * @param {{resourceType?: LH.Crdp.Network.ResourceType, transferSize?: number, resourceSize?: number, responseHeaders: LH.Artifacts.NetworkRequest['responseHeaders'], responseHeadersTransferSize?: number}|undefined} networkRecord
20
25
  * @param {number} totalBytes Uncompressed size of the resource
21
26
  * @param {LH.Crdp.Network.ResourceType=} resourceType
22
27
  * @return {number}
23
28
  */
24
- export function estimateCompressedContentSize(networkRecord: LH.Artifacts.NetworkRequest | undefined, totalBytes: number, resourceType?: LH.Crdp.Network.ResourceType | undefined): number;
29
+ export function estimateCompressedContentSize(networkRecord: {
30
+ resourceType?: LH.Crdp.Network.ResourceType;
31
+ transferSize?: number;
32
+ resourceSize?: number;
33
+ responseHeaders: LH.Artifacts.NetworkRequest["responseHeaders"];
34
+ responseHeadersTransferSize?: number;
35
+ } | undefined, totalBytes: number, resourceType?: LH.Crdp.Network.ResourceType | undefined): number;
25
36
  /**
26
37
  * Estimates the number of bytes this network record would have consumed on the network based on the
27
38
  * uncompressed size (totalBytes). Uses the actual transfer size from the network record if applicable.
28
39
  *
29
- * @param {LH.Artifacts.NetworkRequest|undefined} networkRecord
40
+ * @param {{resourceType?: LH.Crdp.Network.ResourceType, transferSize?: number, resourceSize?: number}|undefined} networkRecord
30
41
  * @param {number} totalBytes Uncompressed size of the resource
31
42
  * @param {LH.Crdp.Network.ResourceType=} resourceType
32
43
  * @return {number}
33
44
  */
34
- export function estimateTransferSize(networkRecord: LH.Artifacts.NetworkRequest | undefined, totalBytes: number, resourceType?: LH.Crdp.Network.ResourceType | undefined): number;
45
+ export function estimateTransferSize(networkRecord: {
46
+ resourceType?: LH.Crdp.Network.ResourceType;
47
+ transferSize?: number;
48
+ resourceSize?: number;
49
+ } | undefined, totalBytes: number, resourceType?: LH.Crdp.Network.ResourceType | undefined): number;
35
50
  /**
36
51
  * Utility function to estimate the ratio of the compression on the resource.
37
52
  * This excludes the size of the response headers.
@@ -15,9 +15,10 @@ function isInline(script) {
15
15
  }
16
16
 
17
17
  /**
18
- * @param {LH.Artifacts.NetworkRequest[]} networkRecords
19
- * @param {LH.Artifacts.Script} script
20
- * @return {LH.Artifacts.NetworkRequest|undefined}
18
+ * @template {{url: string, frameId?: string, redirectDestination?: T}} T
19
+ * @param {T[]} networkRecords
20
+ * @param {Pick<LH.Artifacts.Script, 'url'|'executionContextAuxData'>} script
21
+ * @return {T|undefined}
21
22
  */
22
23
  function getRequestForScript(networkRecords, script) {
23
24
  const frameId = script.executionContextAuxData?.frameId;
@@ -43,7 +44,7 @@ function getRequestForScript(networkRecords, script) {
43
44
  * Estimates the number of bytes this network record would have consumed on the network based on the
44
45
  * uncompressed size (totalBytes). Uses the actual transfer size from the network record if applicable.
45
46
  *
46
- * @param {LH.Artifacts.NetworkRequest|undefined} networkRecord
47
+ * @param {{resourceType?: LH.Crdp.Network.ResourceType, transferSize?: number, resourceSize?: number}|undefined} networkRecord
47
48
  * @param {number} totalBytes Uncompressed size of the resource
48
49
  * @param {LH.Crdp.Network.ResourceType=} resourceType
49
50
  * @return {number}
@@ -88,7 +89,7 @@ function estimateTransferSize(networkRecord, totalBytes, resourceType) {
88
89
  *
89
90
  * This differs from `estimateTransferSize` only in that is subtracts the response headers from the estimate.
90
91
  *
91
- * @param {LH.Artifacts.NetworkRequest|undefined} networkRecord
92
+ * @param {{resourceType?: LH.Crdp.Network.ResourceType, transferSize?: number, resourceSize?: number, responseHeaders: LH.Artifacts.NetworkRequest['responseHeaders'], responseHeadersTransferSize?: number}|undefined} networkRecord
92
93
  * @param {number} totalBytes Uncompressed size of the resource
93
94
  * @param {LH.Crdp.Network.ResourceType=} resourceType
94
95
  * @return {number}
@@ -119,7 +120,7 @@ function estimateCompressedContentSize(networkRecord, totalBytes, resourceType)
119
120
  // This is not encoded, so we can use resourceSize directly.
120
121
  // This would be equivalent to transfer size minus headers transfer size, but transfer size
121
122
  // may also include bytes for SSL connection etc.
122
- contentTransferSize = networkRecord.resourceSize;
123
+ contentTransferSize = networkRecord.resourceSize || 0;
123
124
  } else if (networkRecord.responseHeadersTransferSize) {
124
125
  // Subtract the size of the encoded headers.
125
126
  contentTransferSize =
@@ -0,0 +1,59 @@
1
+ export type SeverityLevel = "fatal" | "error" | "warning" | "log" | "info" | "debug";
2
+ export type Breadcrumb = {
3
+ message?: string;
4
+ category?: string;
5
+ level?: SeverityLevel;
6
+ data?: Record<string, any>;
7
+ timestamp?: number;
8
+ };
9
+ export type EnvironmentData = {
10
+ release?: string;
11
+ environment?: string;
12
+ serverName?: string;
13
+ };
14
+ export type CaptureOptions = {
15
+ level?: SeverityLevel;
16
+ tags?: Record<string, any>;
17
+ extra?: Record<string, any>;
18
+ fingerprint?: string[];
19
+ };
20
+ /**
21
+ * @param {string} dsn
22
+ * @param {EnvironmentData=} environmentData
23
+ */
24
+ export function createSentryReporter(dsn: string, environmentData?: EnvironmentData | undefined): {
25
+ /** @param {Record<string, any>} newTags */
26
+ setTags(newTags: Record<string, any>): void;
27
+ /** @param {Record<string, any>} newExtras */
28
+ setExtras(newExtras: Record<string, any>): void;
29
+ /**
30
+ * @param {string} name
31
+ * @param {Record<string, any>|null} context
32
+ */
33
+ setContext(name: string, context: Record<string, any> | null): void;
34
+ /** @param {Breadcrumb} breadcrumb */
35
+ addBreadcrumb(breadcrumb: Breadcrumb): void;
36
+ /**
37
+ * @param {string} message
38
+ * @param {SeverityLevel|CaptureOptions=} levelOrOpts
39
+ */
40
+ captureMessage(message: string, levelOrOpts?: (SeverityLevel | CaptureOptions) | undefined): Promise<void>;
41
+ /**
42
+ * @param {unknown} err
43
+ * @param {CaptureOptions=} opts
44
+ */
45
+ captureException(err: unknown, opts?: CaptureOptions | undefined): Promise<void>;
46
+ };
47
+ /**
48
+ * Parses a V8 stack into Sentry frames, oldest call first.
49
+ * @param {unknown} stack
50
+ */
51
+ export function parseStack(stack: unknown): {
52
+ filename: string;
53
+ module: string;
54
+ function: string;
55
+ lineno: number | undefined;
56
+ colno: number | undefined;
57
+ in_app: boolean;
58
+ }[];
59
+ //# sourceMappingURL=sentry-reporter.d.ts.map
@@ -0,0 +1,281 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /**
8
+ * A minimal Sentry client that sends events with `fetch` using Sentry's envelope protocol.
9
+ * See https://develop.sentry.dev/sdk/data-model/envelopes/
10
+ */
11
+
12
+ import os from 'os';
13
+ import path from 'path';
14
+ import {types} from 'util';
15
+
16
+ import log from './lighthouse-logger.js';
17
+
18
+ /** @typedef {'fatal'|'error'|'warning'|'log'|'info'|'debug'} SeverityLevel */
19
+ /** @typedef {{message?: string, category?: string, level?: SeverityLevel, data?: Record<string, any>, timestamp?: number}} Breadcrumb */
20
+ /** @typedef {{release?: string, environment?: string, serverName?: string}} EnvironmentData */
21
+ /** @typedef {{level?: SeverityLevel, tags?: Record<string, any>, extra?: Record<string, any>, fingerprint?: string[]}} CaptureOptions */
22
+
23
+ const MAX_BREADCRUMBS = 100;
24
+ const MAX_FRAMES = 50;
25
+ const MAX_LINKED_ERRORS = 5;
26
+ const SEND_TIMEOUT_MS = 5000;
27
+ const DEFAULT_RETRY_AFTER_S = 60;
28
+
29
+ // Same as @sentry/node's stack line parser so frames (and issue grouping) stay similar.
30
+ const FRAME_RE = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
31
+
32
+ /**
33
+ * Same as @sentry/core: drop any Windows drive letter and use forward slashes.
34
+ * @param {string} p
35
+ */
36
+ function normalizePath(p) {
37
+ return p.replace(/^[A-Za-z]:/, '').replace(/\\/g, '/');
38
+ }
39
+
40
+ const BASE_PATH = normalizePath(process.argv[1] ? path.dirname(process.argv[1]) : process.cwd());
41
+
42
+ /**
43
+ * Same as @sentry/node's module naming, e.g. `core.lib:sentry` or `puppeteer-core.lib:foo`.
44
+ * @param {string} filename
45
+ */
46
+ function getModule(filename) {
47
+ const {dir, name} = path.posix.parse(normalizePath(filename));
48
+ const nodeModulesIndex = dir.lastIndexOf('/node_modules');
49
+ if (nodeModulesIndex > -1) {
50
+ return `${dir.slice(nodeModulesIndex + 14).replace(/\//g, '.')}:${name}`;
51
+ }
52
+ if (dir === BASE_PATH || dir.startsWith(`${BASE_PATH}/`)) {
53
+ const moduleName = dir.slice(BASE_PATH.length + 1).replace(/\//g, '.');
54
+ return moduleName ? `${moduleName}:${name}` : name;
55
+ }
56
+ return name;
57
+ }
58
+
59
+ /**
60
+ * Parses a V8 stack into Sentry frames, oldest call first.
61
+ * @param {unknown} stack
62
+ */
63
+ function parseStack(stack) {
64
+ if (typeof stack !== 'string') return [];
65
+
66
+ const frames = [];
67
+ const lines = stack.split('\n').filter(line => /^\s+at /.test(line)).slice(0, MAX_FRAMES);
68
+ for (const line of lines) {
69
+ const match = FRAME_RE.exec(line);
70
+ if (!match) continue;
71
+
72
+ let filename = match[2] || match[5];
73
+ if (filename.startsWith('file://')) {
74
+ filename = filename.slice(7);
75
+ // `file:///C:/foo.js` -> `C:/foo.js`
76
+ if (/^\/[A-Za-z]:/.test(filename)) filename = filename.slice(1);
77
+ try {
78
+ filename = decodeURI(filename);
79
+ } catch {}
80
+ }
81
+ const slashFilename = filename.replace(/\\/g, '/');
82
+ const isAbsolute = slashFilename.startsWith('/') || /^[A-Za-z]:\//.test(slashFilename);
83
+ const inApp = isAbsolute && !slashFilename.includes('/node_modules/');
84
+
85
+ frames.push({
86
+ filename,
87
+ module: getModule(filename),
88
+ function: match[1] || '<anonymous>',
89
+ lineno: match[3] ? Number(match[3]) : undefined,
90
+ colno: match[4] ? Number(match[4]) : undefined,
91
+ in_app: inApp,
92
+ });
93
+ }
94
+ return frames.reverse();
95
+ }
96
+
97
+ /**
98
+ * @param {unknown} value
99
+ * @return {value is Error}
100
+ */
101
+ function isError(value) {
102
+ // `isNativeError` also handles errors from other realms (e.g. `vm` contexts).
103
+ return value instanceof Error || types.isNativeError(value);
104
+ }
105
+
106
+ /**
107
+ * @param {unknown} err
108
+ */
109
+ function exceptionValues(err) {
110
+ const values = [];
111
+ /** @type {unknown} */
112
+ let current = err;
113
+ while (isError(current) && values.length < MAX_LINKED_ERRORS) {
114
+ values.push({
115
+ type: current.name,
116
+ value: current.message,
117
+ mechanism: {type: 'generic', handled: true},
118
+ stacktrace: {frames: parseStack(current.stack)},
119
+ });
120
+ current = current.cause;
121
+ }
122
+ // Non-Error throwables (strings, plain objects, ...).
123
+ if (!values.length) {
124
+ const message = err && typeof err === 'object' && 'message' in err ? err.message : err;
125
+ values.push({
126
+ type: 'Error',
127
+ value: String(message),
128
+ mechanism: {type: 'generic', handled: true},
129
+ });
130
+ }
131
+ // Sentry expects the root cause first, and the captured error last.
132
+ return values.reverse();
133
+ }
134
+
135
+ /**
136
+ * A JSON.stringify replacer that handles values that would otherwise throw or be lost.
137
+ * Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value
138
+ */
139
+ function safeJsonReplacer() {
140
+ /** @type {unknown[]} */
141
+ const ancestors = [];
142
+ /**
143
+ * @this {unknown}
144
+ * @param {string} key
145
+ * @param {unknown} value
146
+ */
147
+ return function(key, value) {
148
+ if (typeof value === 'bigint') return String(value);
149
+ if (value instanceof Error) {
150
+ value = {name: value.name, message: value.message, stack: value.stack};
151
+ }
152
+ if (typeof value !== 'object' || value === null) return value;
153
+
154
+ while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) ancestors.pop();
155
+ if (ancestors.includes(value)) return '[Circular]';
156
+ ancestors.push(value);
157
+ return value;
158
+ };
159
+ }
160
+
161
+ /**
162
+ * @param {string} dsn
163
+ * @param {EnvironmentData=} environmentData
164
+ */
165
+ function createSentryReporter(dsn, environmentData = {}) {
166
+ const sdkVersion = environmentData.release || 'unknown';
167
+ const {protocol, username: publicKey, host, pathname} = new URL(dsn);
168
+ const endpoint = `${protocol}//${host}/api/${pathname.slice(1)}/envelope/`;
169
+ const auth = `Sentry sentry_version=7, sentry_key=${publicKey}, ` +
170
+ `sentry_client=lighthouse/${sdkVersion}`;
171
+
172
+ /** @type {Record<string, any>} */
173
+ const tags = {};
174
+ /** @type {Record<string, any>} */
175
+ const extra = {};
176
+ /** @type {Record<string, any>} */
177
+ const contexts = {
178
+ os: {name: os.type(), version: os.release()},
179
+ runtime: {name: 'node', version: process.version},
180
+ };
181
+ /** @type {Breadcrumb[]} */
182
+ const breadcrumbs = [];
183
+ // Set when Sentry rate limits us (HTTP 429); nothing is sent until then.
184
+ let disabledUntil = 0;
185
+
186
+ /**
187
+ * Never throws: a failure to report an error must not affect Lighthouse.
188
+ * @param {() => Record<string, any>} getEvent
189
+ * @param {CaptureOptions} opts
190
+ * @return {Promise<void>}
191
+ */
192
+ async function send(getEvent, opts) {
193
+ if (Date.now() < disabledUntil) return;
194
+
195
+ try {
196
+ const eventId = crypto.randomUUID().replace(/-/g, '');
197
+ const fullEvent = {
198
+ event_id: eventId,
199
+ timestamp: Date.now() / 1000,
200
+ platform: 'node',
201
+ level: opts.level,
202
+ release: environmentData.release,
203
+ environment: environmentData.environment,
204
+ server_name: environmentData.serverName,
205
+ tags: {...tags, ...opts.tags},
206
+ extra: {...extra, ...opts.extra},
207
+ contexts,
208
+ breadcrumbs,
209
+ fingerprint: opts.fingerprint,
210
+ sdk: {name: 'lighthouse', version: sdkVersion},
211
+ ...getEvent(),
212
+ };
213
+ const envelope = [
214
+ JSON.stringify({event_id: eventId, sent_at: new Date().toISOString()}),
215
+ JSON.stringify({type: 'event'}),
216
+ JSON.stringify(fullEvent, safeJsonReplacer()),
217
+ ].join('\n');
218
+
219
+ const response = await fetch(endpoint, {
220
+ method: 'POST',
221
+ headers: {'Content-Type': 'application/x-sentry-envelope', 'X-Sentry-Auth': auth},
222
+ body: envelope,
223
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
224
+ });
225
+ await response.body?.cancel();
226
+ if (!response.ok) log.verbose('sentry', `Failed to send event: HTTP ${response.status}`);
227
+ if (response.status === 429) {
228
+ const retryAfter = Number(response.headers.get('Retry-After'));
229
+ const seconds = retryAfter > 0 ? retryAfter : DEFAULT_RETRY_AFTER_S;
230
+ disabledUntil = Date.now() + seconds * 1000;
231
+ }
232
+ } catch (err) {
233
+ log.verbose('sentry', `Failed to send event: ${err}`);
234
+ }
235
+ }
236
+
237
+ return {
238
+ /** @param {Record<string, any>} newTags */
239
+ setTags(newTags) {
240
+ Object.assign(tags, newTags);
241
+ },
242
+ /** @param {Record<string, any>} newExtras */
243
+ setExtras(newExtras) {
244
+ Object.assign(extra, newExtras);
245
+ },
246
+ /**
247
+ * @param {string} name
248
+ * @param {Record<string, any>|null} context
249
+ */
250
+ setContext(name, context) {
251
+ if (context) contexts[name] = context;
252
+ else delete contexts[name];
253
+ },
254
+ /** @param {Breadcrumb} breadcrumb */
255
+ addBreadcrumb(breadcrumb) {
256
+ breadcrumbs.push({timestamp: Date.now() / 1000, ...breadcrumb});
257
+ if (breadcrumbs.length > MAX_BREADCRUMBS) breadcrumbs.shift();
258
+ },
259
+ /**
260
+ * @param {string} message
261
+ * @param {SeverityLevel|CaptureOptions=} levelOrOpts
262
+ */
263
+ captureMessage(message, levelOrOpts) {
264
+ const opts = typeof levelOrOpts === 'string' ? {level: levelOrOpts} : levelOrOpts;
265
+ return send(() => ({message}), {...opts, level: opts?.level || 'info'});
266
+ },
267
+ /**
268
+ * @param {unknown} err
269
+ * @param {CaptureOptions=} opts
270
+ */
271
+ captureException(err, opts) {
272
+ const getEvent = () => ({exception: {values: exceptionValues(err)}});
273
+ return send(getEvent, {...opts, level: opts?.level || 'error'});
274
+ },
275
+ };
276
+ }
277
+
278
+ export {
279
+ createSentryReporter,
280
+ parseStack,
281
+ };
@@ -1,6 +1,6 @@
1
1
  export namespace Sentry {
2
2
  export { init };
3
- export { noop as captureMessage };
3
+ export let captureMessage: (message: string, levelOrOpts?: SeverityLevel | CaptureOptions) => Promise<void>;
4
4
  export { noop as captureBreadcrumb };
5
5
  export { noop as getContext };
6
6
  export { noop as setContext };
@@ -15,19 +15,19 @@ export namespace Sentry {
15
15
  }) => Promise<void>;
16
16
  export function _shouldSample(): boolean;
17
17
  }
18
- export type Breadcrumb = import("@sentry/node").Breadcrumb;
19
- export type NodeClient = import("@sentry/node").NodeClient;
20
- export type NodeOptions = import("@sentry/node").NodeOptions;
21
- export type SeverityLevel = import("@sentry/node").SeverityLevel;
18
+ export type Breadcrumb = import("./sentry-reporter.js").Breadcrumb;
19
+ export type EnvironmentData = import("./sentry-reporter.js").EnvironmentData;
20
+ export type SeverityLevel = import("./sentry-reporter.js").SeverityLevel;
21
+ export type CaptureOptions = import("./sentry-reporter.js").CaptureOptions;
22
22
  /**
23
23
  * When called, replaces noops with actual Sentry implementation.
24
- * @param {{url: string, flags: LH.CliFlags, config?: LH.Config, environmentData: NodeOptions}} opts
24
+ * @param {{url: string, flags: LH.CliFlags, config?: LH.Config, environmentData: EnvironmentData}} opts
25
25
  */
26
26
  declare function init(opts: {
27
27
  url: string;
28
28
  flags: LH.CliFlags;
29
29
  config?: LH.Config;
30
- environmentData: NodeOptions;
30
+ environmentData: EnvironmentData;
31
31
  }): Promise<void>;
32
32
  declare function noop(): void;
33
33
  export {};