@utk09/ui-observability 0.8.0 → 0.9.0

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 (177) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +52 -45
  3. package/dist/bus/bus.d.ts +46 -12
  4. package/dist/bus/links.d.ts +6 -3
  5. package/dist/bus-CtJWf9QN.cjs +2 -0
  6. package/dist/bus-CtJWf9QN.cjs.map +1 -0
  7. package/dist/{bus-DPDrlUBY.js → bus-D8kH58tb.js} +128 -71
  8. package/dist/bus-D8kH58tb.js.map +1 -0
  9. package/dist/capture/interactions.d.ts +7 -6
  10. package/dist/capture/network.d.ts +23 -9
  11. package/dist/capture/types.d.ts +3 -3
  12. package/dist/console-BpHfWstv.cjs +2 -0
  13. package/dist/console-BpHfWstv.cjs.map +1 -0
  14. package/dist/console-DjLbryED.js +82 -0
  15. package/dist/console-DjLbryED.js.map +1 -0
  16. package/dist/constants-Br3b89Wg.cjs +2 -0
  17. package/dist/constants-Br3b89Wg.cjs.map +1 -0
  18. package/dist/constants-DM94FjVX.js +96 -0
  19. package/dist/constants-DM94FjVX.js.map +1 -0
  20. package/dist/constants.d.ts +20 -9
  21. package/dist/core/diagnostics.d.ts +2 -2
  22. package/dist/core/journey.d.ts +16 -4
  23. package/dist/core/logger.d.ts +6 -2
  24. package/dist/core/pipeline.d.ts +18 -9
  25. package/dist/core/record.d.ts +11 -6
  26. package/dist/core/remote-sampling.d.ts +1 -1
  27. package/dist/core/runtime.d.ts +43 -15
  28. package/dist/core/sender.d.ts +15 -10
  29. package/dist/deadline-B5DINjD5.js +111 -0
  30. package/dist/deadline-B5DINjD5.js.map +1 -0
  31. package/dist/deadline-Cbg2cbUw.cjs +2 -0
  32. package/dist/deadline-Cbg2cbUw.cjs.map +1 -0
  33. package/dist/error-like-Ywo5uRHo.js +19 -0
  34. package/dist/error-like-Ywo5uRHo.js.map +1 -0
  35. package/dist/error-like-gGRx2s36.cjs +2 -0
  36. package/dist/error-like-gGRx2s36.cjs.map +1 -0
  37. package/dist/errors-CpGRhhIf.cjs +3 -0
  38. package/dist/errors-CpGRhhIf.cjs.map +1 -0
  39. package/dist/{errors-Dnc-X4Ec.js → errors-DH4QJS0u.js} +39 -20
  40. package/dist/errors-DH4QJS0u.js.map +1 -0
  41. package/dist/global-scope-BN-Io_yv.cjs.map +1 -1
  42. package/dist/global-scope-dp2jADRl.js.map +1 -1
  43. package/dist/index.cjs +1 -1
  44. package/dist/index.cjs.map +1 -1
  45. package/dist/index.d.ts +11 -4
  46. package/dist/index.js +561 -436
  47. package/dist/index.js.map +1 -1
  48. package/dist/indexeddb-storage-DNdf1fmL.cjs +2 -0
  49. package/dist/indexeddb-storage-DNdf1fmL.cjs.map +1 -0
  50. package/dist/{indexeddb-storage-uD4oaRMc.js → indexeddb-storage-n1qkFBGA.js} +17 -17
  51. package/dist/indexeddb-storage-n1qkFBGA.js.map +1 -0
  52. package/dist/interactions-31eHGwEQ.cjs +2 -0
  53. package/dist/interactions-31eHGwEQ.cjs.map +1 -0
  54. package/dist/{interactions-igKTAJvj.js → interactions-OU94MPXs.js} +22 -19
  55. package/dist/interactions-OU94MPXs.js.map +1 -0
  56. package/dist/journey-CE2EcwHW.cjs +2 -0
  57. package/dist/journey-CE2EcwHW.cjs.map +1 -0
  58. package/dist/journey-CeJ1QoT2.js +162 -0
  59. package/dist/journey-CeJ1QoT2.js.map +1 -0
  60. package/dist/{library-request-Br_T09Bn.cjs → library-request-C9uJFlbq.cjs} +2 -2
  61. package/dist/{library-request-Br_T09Bn.cjs.map → library-request-C9uJFlbq.cjs.map} +1 -1
  62. package/dist/{library-request-Dt0fXhcn.js → library-request-DvhuplAB.js} +2 -2
  63. package/dist/{library-request-Dt0fXhcn.js.map → library-request-DvhuplAB.js.map} +1 -1
  64. package/dist/{long-frames-DahhqM6u.cjs → long-frames-B8VdA_ny.cjs} +2 -2
  65. package/dist/{long-frames-DahhqM6u.cjs.map → long-frames-B8VdA_ny.cjs.map} +1 -1
  66. package/dist/{long-frames-6pnjWSSR.js → long-frames-C_7OutLs.js} +3 -3
  67. package/dist/{long-frames-6pnjWSSR.js.map → long-frames-C_7OutLs.js.map} +1 -1
  68. package/dist/models/batch.d.ts +1 -1
  69. package/dist/models/bus.d.ts +7 -4
  70. package/dist/models/config.d.ts +43 -12
  71. package/dist/models/log-record.d.ts +12 -6
  72. package/dist/network-BAV7ipyn.cjs +2 -0
  73. package/dist/network-BAV7ipyn.cjs.map +1 -0
  74. package/dist/network-D_lloS5t.js +174 -0
  75. package/dist/network-D_lloS5t.js.map +1 -0
  76. package/dist/patch-BX8KrPCT.cjs +2 -0
  77. package/dist/patch-BX8KrPCT.cjs.map +1 -0
  78. package/dist/patch-CCWfuEY7.js +9 -0
  79. package/dist/patch-CCWfuEY7.js.map +1 -0
  80. package/dist/{platform-D_XkVIF6.cjs → platform-D4wu1eIF.cjs} +2 -2
  81. package/dist/platform-D4wu1eIF.cjs.map +1 -0
  82. package/dist/platform-IHBZGqUe.js +48 -0
  83. package/dist/platform-IHBZGqUe.js.map +1 -0
  84. package/dist/{remote-rules-5UA23alm.js → remote-rules-Bt1XsdEQ.js} +14 -14
  85. package/dist/remote-rules-Bt1XsdEQ.js.map +1 -0
  86. package/dist/{remote-rules-rJJZKVG8.cjs → remote-rules-kuDf5gbe.cjs} +2 -2
  87. package/dist/remote-rules-kuDf5gbe.cjs.map +1 -0
  88. package/dist/sampling-BI15ds9D.cjs +2 -0
  89. package/dist/sampling-BI15ds9D.cjs.map +1 -0
  90. package/dist/sampling-o0VY1mqQ.js +63 -0
  91. package/dist/sampling-o0VY1mqQ.js.map +1 -0
  92. package/dist/sanitize-B9UheVKc.js +123 -0
  93. package/dist/sanitize-B9UheVKc.js.map +1 -0
  94. package/dist/sanitize-DSIP7amZ.cjs +2 -0
  95. package/dist/sanitize-DSIP7amZ.cjs.map +1 -0
  96. package/dist/{sender-G6v4Uqi4.js → sender-BnNj9bOX.js} +234 -176
  97. package/dist/sender-BnNj9bOX.js.map +1 -0
  98. package/dist/sender-D0OsyB1c.cjs +3 -0
  99. package/dist/sender-D0OsyB1c.cjs.map +1 -0
  100. package/dist/storage/emergency-queue.d.ts +1 -1
  101. package/dist/storage/factory.d.ts +1 -1
  102. package/dist/storage/idb-driver.d.ts +1 -1
  103. package/dist/storage/local-storage.d.ts +3 -3
  104. package/dist/storage/memory-storage.d.ts +3 -3
  105. package/dist/{storm-DJkEZP_8.js → storm-BTw0J6eE.js} +2 -2
  106. package/dist/{storm-DJkEZP_8.js.map → storm-BTw0J6eE.js.map} +1 -1
  107. package/dist/{storm-BtzgLOCX.cjs → storm-Y-yuBhvv.cjs} +2 -2
  108. package/dist/{storm-BtzgLOCX.cjs.map → storm-Y-yuBhvv.cjs.map} +1 -1
  109. package/dist/transport/compression.d.ts +1 -1
  110. package/dist/transport/exit-flush.d.ts +21 -17
  111. package/dist/transport/http-transport.d.ts +61 -7
  112. package/dist/transport/retry-engine.d.ts +5 -5
  113. package/dist/transport/status-transport.d.ts +4 -2
  114. package/dist/utils/console.d.ts +1 -1
  115. package/dist/utils/error-like.d.ts +25 -0
  116. package/dist/utils/global-scope.d.ts +1 -1
  117. package/dist/utils/identity.d.ts +1 -1
  118. package/dist/utils/library-console.d.ts +1 -1
  119. package/dist/utils/library-request.d.ts +1 -1
  120. package/dist/utils/patch.d.ts +9 -0
  121. package/dist/utils/platform.d.ts +3 -3
  122. package/dist/utils/sequence.d.ts +0 -5
  123. package/dist/utils/timer.d.ts +1 -1
  124. package/dist/utils/tracing.d.ts +3 -3
  125. package/dist/utils/unref.d.ts +2 -2
  126. package/dist/{web-vitals-DHZ0yA_H.js → web-vitals-Bflr5jSA.js} +4 -2
  127. package/dist/web-vitals-Bflr5jSA.js.map +1 -0
  128. package/dist/web-vitals-DFuoTQbZ.cjs +2 -0
  129. package/dist/web-vitals-DFuoTQbZ.cjs.map +1 -0
  130. package/package.json +2 -2
  131. package/dist/bus-CUXRY0JR.cjs +0 -2
  132. package/dist/bus-CUXRY0JR.cjs.map +0 -1
  133. package/dist/bus-DPDrlUBY.js.map +0 -1
  134. package/dist/console-CNljJict.js +0 -81
  135. package/dist/console-CNljJict.js.map +0 -1
  136. package/dist/console-PKzc-FmR.cjs +0 -2
  137. package/dist/console-PKzc-FmR.cjs.map +0 -1
  138. package/dist/constants-B28fDv2F.cjs +0 -2
  139. package/dist/constants-B28fDv2F.cjs.map +0 -1
  140. package/dist/constants-Bu49bm39.js +0 -93
  141. package/dist/constants-Bu49bm39.js.map +0 -1
  142. package/dist/errors-C78ZTjet.cjs +0 -3
  143. package/dist/errors-C78ZTjet.cjs.map +0 -1
  144. package/dist/errors-Dnc-X4Ec.js.map +0 -1
  145. package/dist/indexeddb-storage-D0p3iMD0.cjs +0 -2
  146. package/dist/indexeddb-storage-D0p3iMD0.cjs.map +0 -1
  147. package/dist/indexeddb-storage-uD4oaRMc.js.map +0 -1
  148. package/dist/interactions-CsE2y_fQ.cjs +0 -2
  149. package/dist/interactions-CsE2y_fQ.cjs.map +0 -1
  150. package/dist/interactions-igKTAJvj.js.map +0 -1
  151. package/dist/network-CZ0aFUsy.cjs +0 -2
  152. package/dist/network-CZ0aFUsy.cjs.map +0 -1
  153. package/dist/network-aSNbwpue.js +0 -112
  154. package/dist/network-aSNbwpue.js.map +0 -1
  155. package/dist/platform-BwbMRwHm.js +0 -48
  156. package/dist/platform-BwbMRwHm.js.map +0 -1
  157. package/dist/platform-D_XkVIF6.cjs.map +0 -1
  158. package/dist/remote-rules-5UA23alm.js.map +0 -1
  159. package/dist/remote-rules-rJJZKVG8.cjs.map +0 -1
  160. package/dist/sampling-E4x92Nn2.cjs +0 -2
  161. package/dist/sampling-E4x92Nn2.cjs.map +0 -1
  162. package/dist/sampling-J1eahbfT.js +0 -160
  163. package/dist/sampling-J1eahbfT.js.map +0 -1
  164. package/dist/sanitize-BMhh8ghJ.cjs +0 -2
  165. package/dist/sanitize-BMhh8ghJ.cjs.map +0 -1
  166. package/dist/sanitize-UJ-4Lb0n.js +0 -114
  167. package/dist/sanitize-UJ-4Lb0n.js.map +0 -1
  168. package/dist/sender-B6ufz26f.cjs +0 -3
  169. package/dist/sender-B6ufz26f.cjs.map +0 -1
  170. package/dist/sender-G6v4Uqi4.js.map +0 -1
  171. package/dist/unref-16maCyKA.js +0 -8
  172. package/dist/unref-16maCyKA.js.map +0 -1
  173. package/dist/unref-CU9Nyz_9.cjs +0 -2
  174. package/dist/unref-CU9Nyz_9.cjs.map +0 -1
  175. package/dist/web-vitals-B2FYsEAU.cjs +0 -2
  176. package/dist/web-vitals-B2FYsEAU.cjs.map +0 -1
  177. package/dist/web-vitals-DHZ0yA_H.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"journey-CeJ1QoT2.js","names":["BASE64_PADDING_PATTERN","JOURNEY_STORAGE_KEY","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","BASE64URL_UNDERSCORE_PATTERN","BASE64URL_DASH_PATTERN","JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BASE64_PLUS_PATTERN","OPENFIN_OPTIONS_TIMEOUT_MS","BASE64_SLASH_PATTERN","BROWSER_STORES","withDeadline","unrefTimer","newId","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","current","token","decoded","broadcast","ownerContextId","raw","standard","missing","padding","c","remaining","timer","url","me","getOptions"],"sources":["../src/core/journey.ts"],"sourcesContent":["// src/core/journey.ts\n//\n// This module manages the lifecycle of a user journey across windows. It encodes tokens,\n// stores the journey and ends it at expiry. Do not trust a value from storage or a token.\n// Any code on the origin can write to both.\n\nimport {\n BASE64_GROUP_CHARS,\n BASE64_PADDING_PATTERN,\n BASE64_PLUS_PATTERN,\n BASE64_SLASH_PATTERN,\n BASE64URL_DASH_PATTERN,\n BASE64URL_UNDERSCORE_PATTERN,\n JOURNEY_END_ON_OWNER_CLOSE,\n JOURNEY_MAX_AGE_MS,\n JOURNEY_STORAGE_KEY,\n JOURNEY_TOKEN_MAX_CHARS,\n JOURNEY_TOKEN_NAME_MAX_CHARS,\n OPENFIN_JOURNEY_CUSTOM_DATA_KEY,\n JOURNEY_URL_PARAM,\n OPENFIN_OPTIONS_TIMEOUT_MS,\n} from \"../constants\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { BROWSER_STORES, type IdentityStores, newId } from \"../utils/identity\";\nimport { unrefTimer } from \"../utils/unref\";\nimport type { Diagnostics } from \"./diagnostics\";\n\n/** Lifetime rules for a journey. A journey is one user task across several contexts. */\nexport interface JourneyOptions {\n /** Maximum open time of a journey, in milliseconds. After this time, the engine ends it. */\n maxAgeMs: number;\n /** True if the journey ends for all contexts when the owning context closes. */\n endOnOwnerClose: boolean;\n /** Query parameter checked at boot for a seeded journey token. */\n urlParam: string;\n}\n\n/** Journey lifetime policy in force. Tests build an engine with shorter values. */\nexport const JOURNEY_OPTIONS: JourneyOptions = {\n maxAgeMs: JOURNEY_MAX_AGE_MS,\n endOnOwnerClose: JOURNEY_END_ON_OWNER_CLOSE,\n urlParam: JOURNEY_URL_PARAM,\n};\n\n/** User journey workflow context shared across windows and applications. */\nexport interface Journey {\n /** Unique journey correlation identifier. */\n id: string;\n /** Journey workflow name for a person to read. */\n name: string;\n /** Journey start timestamp in epoch milliseconds. */\n startedAt: number;\n /** Optional parent journey ID when the journey branches from an earlier journey. */\n parentId?: string;\n /** Context identifier of the document that started the journey. */\n ownerContextId: string;\n}\n\n/** Structural interface for OpenFin window metadata. */\ninterface FinLike {\n /** Target OpenFin window or view. */\n me?: {\n /** Resolves initial window creation options including customData. */\n getOptions?: () => Promise<{ customData?: Record<string, unknown> }>;\n };\n}\n\n/** Global environment extended with optional OpenFin APIs. */\ntype OpenFinGlobal = typeof globalThis & { fin?: FinLike };\n\n/**\n * Reads a non-empty string property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Non-empty string value or undefined.\n */\nfunction readString(source: object, key: string): string | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n\n/**\n * Reads a finite number property from an unverified object.\n * @param source Object to read from.\n * @param key Property name.\n * @returns Finite number value or undefined.\n */\nfunction readNumber(source: object, key: string): number | undefined {\n const value: unknown = Reflect.get(source, key);\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/**\n * Parses and validates an unknown value into a Journey object. The value comes from\n * sessionStorage or from a bus message of another realm.\n * @param value Unverified parsed JSON value.\n * @returns Validated Journey instance or null.\n */\nexport function parseJourney(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"id\");\n const name = readString(value, \"name\");\n const startedAt = readNumber(value, \"startedAt\");\n if (id === undefined || name === undefined || startedAt === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\n parentId: readString(value, \"parentId\"),\n ownerContextId: readString(value, \"ownerContextId\") ?? \"\",\n };\n}\n\n/**\n * Parses and validates decoded token payload into a Journey object.\n * @param value Unverified parsed token payload.\n * @returns Validated Journey instance or null.\n */\nfunction journeyFromTokenPayload(value: unknown): Journey | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const id = readString(value, \"i\");\n const name = readString(value, \"n\");\n if (id === undefined || name === undefined) {\n return null;\n }\n return {\n id,\n name,\n startedAt: readNumber(value, \"s\") ?? Date.now(),\n parentId: undefined,\n ownerContextId: \"\",\n };\n}\n\n/**\n * Encodes journey metadata into a compact, URL-safe base64 string.\n * @param journey Journey instance to serialize.\n * @returns Unpadded base64url encoded token string.\n */\nfunction encodeToken(journey: Journey): string {\n const json = JSON.stringify({\n i: journey.id,\n n: journey.name.slice(0, JOURNEY_TOKEN_NAME_MAX_CHARS),\n s: journey.startedAt,\n });\n // Convert the UTF-8 bytes to a binary string before btoa. btoa throws above U+00FF.\n // Without this step, a name in a non-Latin script fails.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary)\n .replace(BASE64_PLUS_PATTERN, \"-\")\n .replace(BASE64_SLASH_PATTERN, \"_\")\n .replace(BASE64_PADDING_PATTERN, \"\");\n}\n\n/** Manages journey lifecycle, cross-window adoption, storage synchronization, and expiration. */\nexport class JourneyEngine {\n /** Active journey context, or null if none is in progress. */\n private journey: Journey | null = null;\n\n /** Active expiration timer handle. */\n private expiryTimer: ReturnType<typeof setTimeout> | null = null;\n\n /**\n * @param options Journey configuration thresholds.\n * @param diagnostics Diagnostics reporter.\n * @param contextId Unique context identifier for this document.\n * @param onLocalChange Callback invoked when journey state changes locally.\n * @param stores Identity stores that hold the journey.\n */\n constructor(\n private readonly options: JourneyOptions,\n private readonly diagnostics: Diagnostics,\n private readonly contextId: string,\n private readonly onLocalChange: (journey: Journey | null) => void,\n private readonly stores: IdentityStores = BROWSER_STORES,\n ) {}\n\n /** Returns the active journey instance or null. */\n current(): Journey | null {\n return this.journey;\n }\n\n /**\n * Finds and adopts the initial journey. It checks the URL query, then sessionStorage,\n * then OpenFin customData.\n * @returns Promise that resolves when journey initialization completes.\n */\n async bootstrap(): Promise<void> {\n const fromUrl = this.readUrlToken();\n if (fromUrl && this.adopt(fromUrl, \"url\")) {\n this.removeUrlToken();\n return;\n }\n\n const fromStorage = this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not read the persisted journey.\",\n () => this.stores.session().getItem(JOURNEY_STORAGE_KEY),\n );\n if (fromStorage && this.restore(fromStorage)) {\n return;\n }\n\n const fromOpenFin = await this.readOpenFinToken();\n if (fromOpenFin !== null) {\n this.adopt(fromOpenFin, \"openfin.customData\");\n }\n }\n\n /**\n * Starts a new journey. It replaces the active journey and tells connected peers.\n * @param name Human-readable workflow name.\n * @param opts Optional parent linkage and pre-assigned identifier.\n * @returns Started Journey instance.\n */\n start(name: string, opts: { parent?: boolean; id?: string } = {}): Journey {\n const journey: Journey = {\n id: opts.id ?? newId(this.diagnostics),\n name,\n startedAt: Date.now(),\n parentId: opts.parent ? this.journey?.id : undefined,\n ownerContextId: this.contextId,\n };\n this.setJourney(journey);\n this.onLocalChange(journey);\n return journey;\n }\n\n /** Ends the active journey and broadcasts the change. */\n end(): void {\n if (this.journey === null) {\n return;\n }\n this.setJourney(null);\n this.onLocalChange(null);\n }\n\n /**\n * Applies a journey update from a bus peer. It does not broadcast the update again.\n * An echo makes two windows send the change back and forth without end.\n * It ignores a journey with the same ID as the active journey. Thus an echo cannot\n * restart the timer.\n * @param journey Updated Journey instance or null.\n */\n applyRemote(journey: Journey | null): void {\n const current = this.journey;\n if (journey !== null && current !== null && journey.id === current.id) {\n return;\n }\n this.setJourney(journey);\n }\n\n /**\n * Serializes the active journey into a compact token for URL or intent transfer.\n * @returns Base64url token, or undefined when no journey is active or the token exceeds\n * the size limit.\n */\n getToken(): string | undefined {\n const journey = this.journey;\n if (journey === null) {\n return undefined;\n }\n const token = encodeToken(journey);\n if (token.length > JOURNEY_TOKEN_MAX_CHARS) {\n this.diagnostics.report(\n \"journey.token_too_large\",\n \"The journey token is larger than the size limit. The library does not issue it.\",\n { length: token.length },\n );\n return undefined;\n }\n return token;\n }\n\n /**\n * Validates and adopts a serialized journey token.\n * @param token Base64url journey token.\n * @param source Originating source description for diagnostics.\n * @param broadcast True to send the adoption to the connected bus peers.\n * @returns True if the token was valid, unexpired, and adopted.\n */\n adopt(token: string, source: string, broadcast = false): boolean {\n const decoded = this.decodeToken(token);\n if (decoded === null) {\n return false;\n }\n if (Date.now() - decoded.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a seeded journey older than maxAgeMs.\",\n {\n source,\n name: decoded.name,\n },\n );\n return false;\n }\n\n this.setJourney(decoded);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library adopted the journey \"${decoded.name}\".`,\n {\n source,\n journeyId: decoded.id,\n },\n );\n if (broadcast) {\n this.onLocalChange(decoded);\n }\n return true;\n }\n\n /**\n * Ends the journey when endOnOwnerClose is on and the closed context owns the journey.\n * @param ownerContextId Context identifier of the closed window.\n */\n ownerClosed(ownerContextId: string): void {\n if (!this.options.endOnOwnerClose) {\n return;\n }\n if (this.journey?.ownerContextId === ownerContextId) {\n this.end();\n }\n }\n\n /** Clears pending expiration timers and releases resources on shutdown. */\n destroy(): void {\n this.clearTimer();\n }\n\n /**\n * Resumes a persisted journey from raw sessionStorage data.\n * @param raw Serialized JSON string from storage.\n * @returns True if the engine restored the journey.\n */\n private restore(raw: string): boolean {\n const parsed = this.diagnostics.guard(\n \"storage.degraded\",\n \"The library could not parse the persisted journey.\",\n () => JSON.parse(raw) as unknown,\n );\n const journey = parseJourney(parsed);\n if (journey === null) {\n return false;\n }\n\n if (Date.now() - journey.startedAt > this.options.maxAgeMs) {\n this.diagnostics.report(\n \"journey.expired\",\n \"The library discarded a persisted journey older than maxAgeMs.\",\n { name: journey.name },\n );\n this.clearStored();\n return false;\n }\n\n this.setJourney(journey);\n this.diagnostics.report(\n \"journey.adopted\",\n `The library resumed the journey \"${journey.name}\".`,\n {\n source: \"sessionStorage\",\n journeyId: journey.id,\n },\n );\n return true;\n }\n\n /**\n * Decodes a base64url token into a validated Journey object. Anyone can edit the URL\n * that holds a token. Each step throws on bad input. The guard reports the failure\n * and does not throw it.\n * @param token Encoded token string.\n * @returns Decoded Journey instance or null on decode error.\n */\n private decodeToken(token: string): Journey | null {\n const decoded = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not decode a seeded journey token.\",\n () => {\n const standard = token\n .replace(BASE64URL_DASH_PATTERN, \"+\")\n .replace(BASE64URL_UNDERSCORE_PATTERN, \"/\");\n const missing =\n (BASE64_GROUP_CHARS - (standard.length % BASE64_GROUP_CHARS)) % BASE64_GROUP_CHARS;\n const padding = \"=\".repeat(missing);\n const bytes = Uint8Array.from(atob(standard + padding), (c) => c.charCodeAt(0));\n return journeyFromTokenPayload(JSON.parse(new TextDecoder().decode(bytes)) as unknown);\n },\n );\n return decoded ?? null;\n }\n\n /**\n * Sets the active journey, updates sessionStorage, and schedules expiration.\n * @param journey Target Journey instance or null.\n */\n private setJourney(journey: Journey | null): void {\n this.journey = journey;\n this.clearTimer();\n\n this.diagnostics.guard(\"storage.unavailable\", \"The library could not save the journey.\", () => {\n if (journey !== null) {\n this.stores.session().setItem(JOURNEY_STORAGE_KEY, JSON.stringify(journey));\n } else {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n }\n });\n\n if (journey === null) {\n return;\n }\n\n const remaining = Math.max(this.options.maxAgeMs - (Date.now() - journey.startedAt), 0);\n const timer = setTimeout(() => {\n this.diagnostics.report(\n \"journey.expired\",\n `The journey \"${journey.name}\" reached maxAgeMs. The library ended it.`,\n { journeyId: journey.id },\n );\n this.journey = null;\n this.expiryTimer = null;\n this.clearStored();\n }, remaining);\n this.expiryTimer = timer;\n unrefTimer(timer);\n }\n\n /** Removes journey data from the session store. */\n private clearStored(): void {\n this.diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not clear the persisted journey.\",\n () => {\n this.stores.session().removeItem(JOURNEY_STORAGE_KEY);\n },\n );\n }\n\n /** Cancels any active expiration timer. */\n private clearTimer(): void {\n if (this.expiryTimer !== null) {\n clearTimeout(this.expiryTimer);\n this.expiryTimer = null;\n }\n }\n\n /**\n * Extracts the journey token from the current window location search parameters.\n * @returns Token string or null.\n */\n private readUrlToken(): string | null {\n const token = this.diagnostics.guard(\n \"config.invalid\",\n \"The library could not read the journey token from the URL.\",\n () => {\n if (typeof location === \"undefined\") {\n return null;\n }\n return new URL(location.href).searchParams.get(this.options.urlParam);\n },\n );\n return token ?? null;\n }\n\n /**\n * Removes the journey token from the address bar after the engine adopts it.\n * If not, a copy or a bookmark of the link starts the same journey in another session.\n */\n private removeUrlToken(): void {\n this.diagnostics.guard(\n \"platform.api_blocked\",\n \"The library could not remove the journey token from the URL.\",\n () => {\n const url = new URL(location.href);\n url.searchParams.delete(this.options.urlParam);\n // Keep history.state. A router stores its own state there.\n history.replaceState(history.state, \"\", url.href);\n },\n );\n }\n\n /**\n * Reads the journey token from the customData of the OpenFin window options.\n * OPENFIN_OPTIONS_TIMEOUT_MS limits the wait. At the deadline, it reports\n * openfin.unavailable and returns no token. A window without a token gives the same result.\n * @returns Promise that resolves to token string or null.\n */\n private async readOpenFinToken(): Promise<string | null> {\n const me = (globalThis as OpenFinGlobal).fin?.me;\n const getOptions = me?.getOptions;\n if (getOptions === undefined) {\n return null;\n }\n\n // Use call to keep the receiver of the native OpenFin method. A detached copy\n // throws when called.\n const options = await this.diagnostics.guardAsync(\n \"openfin.unavailable\",\n \"The library could not read fin.me.getOptions().\",\n () => withDeadline(getOptions.call(me), OPENFIN_OPTIONS_TIMEOUT_MS),\n );\n const token = options?.customData?.[OPENFIN_JOURNEY_CUSTOM_DATA_KEY];\n return typeof token === \"string\" ? token : null;\n }\n}\n"],"mappings":";;;AAsCA,IAAac,IAAkC;CAC7C,UAAUT;CACV,iBAAA;CACA,UAAUC;AACZ;AAkCA,SAASS,EAAW,GAAgB,GAAiC;CACnE,IAAMC,IAAiB,QAAQ,IAAIC,GAAQC,CAAG;CAC9C,OAAO,OAAOF,KAAU,YAAYA,MAAU,KAAKA,IAAQ,KAAA;AAC7D;AAQA,SAASG,EAAW,GAAgB,GAAiC;CACnE,IAAMH,IAAiB,QAAQ,IAAIC,GAAQC,CAAG;CAC9C,OAAO,OAAOF,KAAU,YAAY,OAAO,SAASA,CAAK,IAAIA,IAAQ,KAAA;AACvE;AAQA,SAAgBI,EAAa,GAAgC;CAC3D,IAAI,OAAOJ,KAAU,aAAYA,GAC/B,OAAO;CAET,IAAMK,IAAKN,EAAWC,GAAO,IAAI,GAC3BM,IAAOP,EAAWC,GAAO,MAAM,GAC/BO,IAAYJ,EAAWH,GAAO,WAAW;CAI/C,OAHIK,MAAO,KAAA,KAAaC,MAAS,KAAA,KAAaC,MAAc,KAAA,IACnD,OAEF;EACL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,EAAa4C,EAAW,KAAKD,CAAE,GAAG9C,CAA0B,CACpE,EAAA,EACuB,aAAaN;EACpC,OAAO,OAAOwC,KAAU,WAAWA,IAAQ;CAC7C;AACF"}
@@ -1,2 +1,2 @@
1
- const e=require("./constants-B28fDv2F.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.ct);function n(e){return t.run(e)}function r(){return t.open()}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return r}});
2
- //# sourceMappingURL=library-request-Br_T09Bn.cjs.map
1
+ const e=require("./constants-Br3b89Wg.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.dt);function n(e){return t.run(e)}function r(){return t.open()}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return r}});
2
+ //# sourceMappingURL=library-request-C9uJFlbq.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"library-request-Br_T09Bn.cjs","names":["globalScope","LIBRARY_REQUEST_KEY","require_constants","scope","runAsLibraryRequest","fn","isLibraryRequest"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests whether a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n"],"mappings":"4CAUA,IAAMG,uCAAQH,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAQ7C,SAAgBG,EAAuB,EAAgB,CACrD,OAAOD,EAAM,IAAIE,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAOH,EAAM,KAAK,CACpB"}
1
+ {"version":3,"file":"library-request-C9uJFlbq.cjs","names":["globalScope","LIBRARY_REQUEST_KEY","require_constants","scope","runAsLibraryRequest","fn","isLibraryRequest"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n"],"mappings":"4CAUA,IAAMG,uCAAQH,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAQ7C,SAAgBG,EAAuB,EAAgB,CACrD,OAAOD,EAAM,IAAIE,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAOH,EAAM,KAAK,CACpB"}
@@ -1,4 +1,4 @@
1
- import { ct as e } from "./constants-Bu49bm39.js";
1
+ import { dt as e } from "./constants-DM94FjVX.js";
2
2
  import { t } from "./global-scope-dp2jADRl.js";
3
3
  //#region src/utils/library-request.ts
4
4
  var n = t(e);
@@ -11,4 +11,4 @@ function i() {
11
11
  //#endregion
12
12
  export { r as n, i as t };
13
13
 
14
- //# sourceMappingURL=library-request-Dt0fXhcn.js.map
14
+ //# sourceMappingURL=library-request-DvhuplAB.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"library-request-Dt0fXhcn.js","names":["LIBRARY_REQUEST_KEY","scope","globalScope","runAsLibraryRequest","fn","isLibraryRequest"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests whether a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n"],"mappings":";;;AAUA,IAAMC,IAAQC,EAAYF,CAAmB;AAQ7C,SAAgBG,EAAuB,GAAgB;CACrD,OAAOF,EAAM,IAAIG,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAOJ,EAAM,KAAK;AACpB"}
1
+ {"version":3,"file":"library-request-DvhuplAB.js","names":["LIBRARY_REQUEST_KEY","scope","globalScope","runAsLibraryRequest","fn","isLibraryRequest"],"sources":["../src/utils/library-request.ts"],"sourcesContent":["// src/utils/library-request.ts\n//\n// Marks the requests that the library starts itself. Network capture skips a request that starts\n// inside this scope. A captured library request logs a record. The library then sends that record\n// with another request. The loop does not stop.\n\nimport { LIBRARY_REQUEST_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/**\n * Runs a function inside the library request scope. The scope covers only the synchronous part\n * of the function. A request that starts after an await is outside the scope.\n * @param fn Function that starts the request.\n * @returns The return value of the function.\n */\nexport function runAsLibraryRequest<T>(fn: () => T): T {\n return scope.run(fn);\n}\n\n/**\n * Tests if a library request scope is open.\n * @returns True while the library starts a request.\n */\nexport function isLibraryRequest(): boolean {\n return scope.open();\n}\n"],"mappings":";;;AAUA,IAAMC,IAAQC,EAAYF,CAAmB;AAQ7C,SAAgBG,EAAuB,GAAgB;CACrD,OAAOF,EAAM,IAAIG,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAOJ,EAAM,KAAK;AACpB"}
@@ -1,2 +1,2 @@
1
- const e=require("./platform-D_XkVIF6.cjs"),t=require("./storm-BtzgLOCX.cjs");var n=[`long-animation-frame`,`longtask`];function r(e){let t;for(let n of e??[])(!t||n.duration>t.duration)&&(t=n);return t}var i=class{ctx;name=`long-frames`;observer;window={start:0,count:0};threshold=100;constructor(e){this.ctx=e}install(){if(this.observer)return;let{once:e}=this.ctx,t=!e.longFrames;e.longFrames=!0;let r=typeof PerformanceObserver>`u`?void 0:PerformanceObserver.supportedEntryTypes,i=n.find(e=>r?.includes(e));if(i===void 0){if(!t)return;this.ctx.diagnostics.report(`capture.install_failed`,`The browser does not report long frames. The long frame capture is off.`)}else this.threshold=this.readThreshold(),this.observer=new PerformanceObserver(e=>{for(let t of e.getEntries())this.record(t)}),this.observer.observe({type:i,buffered:t})}uninstall(){this.observer?.disconnect(),this.observer=void 0}readThreshold(){let e=this.ctx.config.capture.longFrameThresholdMs;return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:(this.ctx.diagnostics.report(`config.invalid`,`capture.longFrameThresholdMs must be a number of 0 or more. The library uses 100.`),100)}record(n){if(n.duration<this.threshold)return;let{diagnostics:i}=this.ctx;if(!t.t(this.window,20,i,`long frames`))return;let a=Math.round(n.duration),o={"frame.type":n.entryType};n.blockingDuration!==void 0&&(o[`frame.blocking_ms`]=Math.round(n.blockingDuration));let s=r(n.scripts),c=t=>this.ctx.config.capture.fullUrls?t:e.r(t);if(s?.invoker){let{invoker:e}=s;o[`frame.script.invoker`]=e.includes(`://`)?c(e):e}s?.sourceURL&&(o[`frame.script.source`]=c(s.sourceURL)),this.ctx.breadcrumbs.push({t:Date.now(),category:`frame`,message:`long frame ${String(a)} ms`}),this.ctx.logger.logMetric(`ui.long_frame.duration`,a,`ms`,`histogram`,o)}};exports.LongFrameCapture=i;
2
- //# sourceMappingURL=long-frames-DahhqM6u.cjs.map
1
+ const e=require("./platform-D4wu1eIF.cjs"),t=require("./storm-Y-yuBhvv.cjs");var n=[`long-animation-frame`,`longtask`];function r(e){let t;for(let n of e??[])(!t||n.duration>t.duration)&&(t=n);return t}var i=class{ctx;name=`long-frames`;observer;window={start:0,count:0};threshold=100;constructor(e){this.ctx=e}install(){if(this.observer)return;let{once:e}=this.ctx,t=!e.longFrames;e.longFrames=!0;let r=typeof PerformanceObserver>`u`?void 0:PerformanceObserver.supportedEntryTypes,i=n.find(e=>r?.includes(e));if(i===void 0){if(!t)return;this.ctx.diagnostics.report(`capture.install_failed`,`The browser does not report long frames. The long frame capture is off.`)}else this.threshold=this.readThreshold(),this.observer=new PerformanceObserver(e=>{for(let t of e.getEntries())this.record(t)}),this.observer.observe({type:i,buffered:t})}uninstall(){this.observer?.disconnect(),this.observer=void 0}readThreshold(){let e=this.ctx.config.capture.longFrameThresholdMs;return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:(this.ctx.diagnostics.report(`config.invalid`,`capture.longFrameThresholdMs must be a number of 0 or more. The library uses 100.`),100)}record(n){if(n.duration<this.threshold)return;let{diagnostics:i}=this.ctx;if(!t.t(this.window,20,i,`long frames`))return;let a=Math.round(n.duration),o={"frame.type":n.entryType};n.blockingDuration!==void 0&&(o[`frame.blocking_ms`]=Math.round(n.blockingDuration));let s=r(n.scripts),c=t=>this.ctx.config.capture.fullUrls?t:e.r(t);if(s?.invoker){let{invoker:e}=s;o[`frame.script.invoker`]=e.includes(`://`)?c(e):e}s?.sourceURL&&(o[`frame.script.source`]=c(s.sourceURL)),this.ctx.breadcrumbs.push({t:Date.now(),category:`frame`,message:`long frame ${String(a)} ms`}),this.ctx.logger.logMetric(`ui.long_frame.duration`,a,`ms`,`histogram`,o)}};exports.LongFrameCapture=i;
2
+ //# sourceMappingURL=long-frames-B8VdA_ny.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"long-frames-DahhqM6u.cjs","names":["allowInWindow","stripUrlQuery","require_platform","require_storm","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if fullUrls is set.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":"6EAWA,IAAMI,EAAc,CAAC,uBAAwB,UAAU,EAyBvD,SAASC,EAAc,EAA6D,CAClF,IAAIC,EAEJ,IAAK,IAAMC,KAAUC,GAAW,CAAC,GAC3B,CAACF,GAAWC,EAAO,SAAWD,EAAQ,YACxC,EAAUC,GAId,OAAOD,CACT,CAGA,IAAaG,EAAb,KAAiD,CAgBlB,IAd7B,KAAgB,cAGhB,SAGA,OAAuC,CAAE,MAAO,EAAG,MAAO,CAAE,EAG5D,UAAA,IAKA,YAAY,EAAsC,CAArB,KAAA,IAAAC,CAAsB,CAGnD,SAAgB,CACd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X,GAAQ,QAAS,CAGnB,GAAM,CAAE,WAAYA,EACpB,EAAM,wBAA0BgB,EAAQ,SAAS,KAAK,EAAID,EAAIC,CAAO,EAAIA,CAC3E,CAEIhB,GAAQ,YACV,EAAM,uBAAyBe,EAAIf,EAAO,SAAS,GAGrD,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,QACV,QAAS,cAAc,OAAOa,CAAQ,EAAE,IAC1C,CAAC,EACD,KAAK,IAAI,OAAO,UAAU,yBAA0BA,EAAU,KAAM,YAAaC,CAAK,CACxF,CACF"}
1
+ {"version":3,"file":"long-frames-B8VdA_ny.cjs","names":["allowInWindow","stripUrlQuery","require_platform","require_storm","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":"6EAWA,IAAMI,EAAc,CAAC,uBAAwB,UAAU,EAyBvD,SAASC,EAAc,EAA6D,CAClF,IAAIC,EAEJ,IAAK,IAAMC,KAAUC,GAAW,CAAC,GAC3B,CAACF,GAAWC,EAAO,SAAWD,EAAQ,YACxC,EAA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mBAAqB,IAAA,KAC7B,EAAM,qBAAuB,KAAK,MAAMA,EAAM,gBAAgB,GAGhE,IAAMT,EAASF,EAAcW,EAAM,OAAO,EAGpCM,EAAO,GACX,KAAK,IAAI,OAAO,QAAQ,SAAWJ,EAAQjB,EAAAA,EAAciB,CAAK,EAEhE,GAAIX,GAAQ,QAAS,CAGnB,GAAM,CAAE,WAAYA,EACpB,EAAM,wBAA0BgB,EAAQ,SAAS,KAAK,EAAID,EAAIC,CAAO,EAAIA,CAC3E,CAEIhB,GAAQ,YACV,EAAM,uBAAyBe,EAAIf,EAAO,SAAS,GAGrD,KAAK,IAAI,YAAY,KAAK,CACxB,EAAG,KAAK,IAAI,EACZ,SAAU,QACV,QAAS,cAAc,OAAOa,CAAQ,EAAE,IAC1C,CAAC,EACD,KAAK,IAAI,OAAO,UAAU,yBAA0BA,EAAU,KAAM,YAAaC,CAAK,CACxF,CACF"}
@@ -1,5 +1,5 @@
1
- import { r as e } from "./platform-BwbMRwHm.js";
2
- import { t } from "./storm-DJkEZP_8.js";
1
+ import { r as e } from "./platform-IHBZGqUe.js";
2
+ import { t } from "./storm-BTw0J6eE.js";
3
3
  //#region src/capture/long-frames.ts
4
4
  var n = ["long-animation-frame", "longtask"];
5
5
  function r(e) {
@@ -62,4 +62,4 @@ var i = class {
62
62
  //#endregion
63
63
  export { i as LongFrameCapture };
64
64
 
65
- //# sourceMappingURL=long-frames-6pnjWSSR.js.map
65
+ //# sourceMappingURL=long-frames-C_7OutLs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"long-frames-6pnjWSSR.js","names":["stripUrlQuery","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","allowInWindow","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if fullUrls is set.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":";;;AAWA,IAAMC,IAAc,CAAC,wBAAwB,UAAU;AAyBvD,SAASC,EAAc,GAA6D;CAClF,IAAIC;CAEJ,KAAK,IAAMC,KAAUC,KAAW,CAAC,GAC/B,CAAI,CAACF,KAAWC,EAAO,WAAWD,EAAQ,cACxC,IAAUC;CAId,OAAOD;AACT;AAGA,IAAaG,IAAb,MAAiD;CAgBlB;CAd7B,OAAgB;CAGhB;CAGA,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAG5D,YAAA;CAKA,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,IAAI,KAAK,UACP;EAKF,IAAM,EAAE,YAAS,KAAK,KAChBC,IAAQ,CAACC,EAAK;EACpB,EAAK,aAAa;EAGlB,IAAMC,IACJ,OAAO,sBAAwB,MAC3B,KAAA,IACA,oBAAoB,qBACpBC,IAAOV,EAAY,MAAM,MAASS,GAAW,SAASE,CAAI,CAAC;EAEjE,IAAID,MAAS,KAAA,GAAW;GACtB,IAAI,CAACH,GACH;GAGF,KAAK,IAAI,YAAY,OACnB,0BACA,yEACF;EAEF,OAUA,AARA,KAAK,YAAY,KAAK,cAAc,GACpC,KAAK,WAAW,IAAI,qBAAqB,MAAS;GAChD,KAAK,IAAMK,KAASC,EAAK,WAAW,GAClC,KAAK,OAAOD,CAAK;EAErB,CAAC,GAGD,KAAK,SAAS,QAAQ;GAAE;GAAM,UAAUL;EAAM,CAAC;CACjD;CAGA,YAAkB;EAEhB,AADA,KAAK,UAAU,WAAW,GAC1B,KAAK,WAAW,KAAA;CAClB;CAMA,gBAAgC;EAC9B,IAAMO,IAAiB,KAAK,IAAI,OAAO,QAAQ;EAU/C,OARI,OAAOA,KAAU,YAAY,OAAO,SAASA,CAAK,KAAKA,KAAS,IAC3DA,KAGT,KAAK,IAAI,YAAY,OACnB,kBACA,mFACF,GACA;CACF;CAMA,OAAe,GAAyB;EACtC,IAAIF,EAAM,WAAW,KAAK,WACxB;EAGF,IAAM,EAAE,mBAAgB,KAAK;EAE7B,IAAI,CAACG,EAAc,KAAK,QAAA,IAAmCC,GAAa,aAAa,GACnF;EAGF,IAAMC,IAAW,KAAK,MAAML,EAAM,QAAQ,GACpCM,IAAiC,EAAE,cAAcN,EAAM,UAAU;EAEvE,AAAIA,EAAM,qBAAqB,KAAA,MAC7B,EAAM,uBAAuB,KAAK,MAAMA,EAAM,gBAAgB;EAGhE,IAAMT,IAASF,EAAcW,EAAM,OAAO,GAGpCO,KAAO,MACX,KAAK,IAAI,OAAO,QAAQ,WAAWL,IAAQf,EAAce,CAAK;EAEhE,IAAIX,GAAQ,SAAS;GAGnB,IAAM,EAAE,eAAYA;GACpB,EAAM,0BAA0BiB,EAAQ,SAAS,KAAK,IAAID,EAAIC,CAAO,IAAIA;EAC3E;EAWA,AATIjB,GAAQ,cACV,EAAM,yBAAyBgB,EAAIhB,EAAO,SAAS,IAGrD,KAAK,IAAI,YAAY,KAAK;GACxB,GAAG,KAAK,IAAI;GACZ,UAAU;GACV,SAAS,cAAc,OAAOc,CAAQ,EAAE;EAC1C,CAAC,GACD,KAAK,IAAI,OAAO,UAAU,0BAA0BA,GAAU,MAAM,aAAaC,CAAK;CACxF;AACF"}
1
+ {"version":3,"file":"long-frames-C_7OutLs.js","names":["stripUrlQuery","FRAME_TYPES","longestScript","longest","script","scripts","LongFrameCapture","ctx","first","once","supported","type","name","entry","list","value","allowInWindow","diagnostics","duration","attrs","url","invoker"],"sources":["../src/capture/long-frames.ts"],"sourcesContent":["// src/capture/long-frames.ts\n//\n// Reports long animation frames. A long frame freezes the page with no user input.\n// INP does not show it, for example a grid that re-renders 5,000 rows.\n\nimport { LONG_FRAME_MAX_PER_WINDOW, LONG_FRAME_THRESHOLD_MS } from \"../constants\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport type { Capture, CaptureContext } from \"./types\";\n\n/** Entry types that the capture observes, in order of preference. */\nconst FRAME_TYPES = [\"long-animation-frame\", \"longtask\"];\n\n/** One script of a long animation frame. Some DOM type versions do not declare it. */\ninterface FrameScript {\n /** Run time of the script, in milliseconds. */\n duration: number;\n /** Caller of the script, for example an event listener or a timer. */\n invoker?: string;\n /** URL of the script source. */\n sourceURL?: string;\n}\n\n/** Long animation frame or long task. A long task has no blocking time and no scripts. */\ninterface FrameEntry extends PerformanceEntry {\n /** Time that the frame blocked input, in milliseconds. */\n blockingDuration?: number;\n /** Scripts that ran in the frame. */\n scripts?: FrameScript[];\n}\n\n/**\n * Finds the script that ran longest in a frame.\n * @param scripts Scripts of the frame.\n * @returns The longest script, or undefined if the frame has none.\n */\nfunction longestScript(scripts: FrameScript[] | undefined): FrameScript | undefined {\n let longest: FrameScript | undefined;\n\n for (const script of scripts ?? []) {\n if (!longest || script.duration > longest.duration) {\n longest = script;\n }\n }\n\n return longest;\n}\n\n/** Records each long animation frame as a histogram metric and a breadcrumb. */\nexport class LongFrameCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"long-frames\";\n\n /** Active observer. Undefined when the capture is not installed. */\n private observer: PerformanceObserver | undefined;\n\n /** Rate limit of this capture. A frozen tab must not flood the pipeline. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** Minimum frame duration to record, in milliseconds. */\n private threshold = LONG_FRAME_THRESHOLD_MS;\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, and breadcrumbs.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Observes the best entry type that the browser supports. */\n install(): void {\n if (this.observer) {\n return;\n }\n\n // Only the first install in a document reads buffered frames, or reports missing support.\n // A reinstall after configure() then does not repeat them.\n const { once } = this.ctx;\n const first = !once.longFrames;\n once.longFrames = true;\n\n // Older browsers have no supportedEntryTypes. The capture is then off.\n const supported: readonly string[] | undefined =\n typeof PerformanceObserver === \"undefined\"\n ? undefined\n : PerformanceObserver.supportedEntryTypes;\n const type = FRAME_TYPES.find((name) => supported?.includes(name));\n\n if (type === undefined) {\n if (!first) {\n return;\n }\n\n this.ctx.diagnostics.report(\n \"capture.install_failed\",\n \"The browser does not report long frames. The long frame capture is off.\",\n );\n return;\n }\n\n this.threshold = this.readThreshold();\n this.observer = new PerformanceObserver((list) => {\n for (const entry of list.getEntries()) {\n this.record(entry);\n }\n });\n\n // Buffered frames include the first render, which runs before this chunk loads.\n this.observer.observe({ type, buffered: first });\n }\n\n /** Disconnects the observer. */\n uninstall(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n }\n\n /**\n * Reads the threshold from the configuration. It reports a value that is not usable.\n * @returns Minimum frame duration to record, in milliseconds.\n */\n private readThreshold(): number {\n const value: unknown = this.ctx.config.capture.longFrameThresholdMs;\n\n if (typeof value === \"number\" && Number.isFinite(value) && value >= 0) {\n return value;\n }\n\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `capture.longFrameThresholdMs must be a number of 0 or more. The library uses ${String(LONG_FRAME_THRESHOLD_MS)}.`,\n );\n return LONG_FRAME_THRESHOLD_MS;\n }\n\n /**\n * Records one frame at or above the threshold.\n * @param entry Long animation frame or long task entry.\n */\n private record(entry: FrameEntry): void {\n if (entry.duration < this.threshold) {\n return;\n }\n\n const { diagnostics } = this.ctx;\n\n if (!allowInWindow(this.window, LONG_FRAME_MAX_PER_WINDOW, diagnostics, \"long frames\")) {\n return;\n }\n\n const duration = Math.round(entry.duration);\n const attrs: Record<string, unknown> = { \"frame.type\": entry.entryType };\n\n if (entry.blockingDuration !== undefined) {\n attrs[\"frame.blocking_ms\"] = Math.round(entry.blockingDuration);\n }\n\n const script = longestScript(entry.scripts);\n\n // A signed URL is a credential. Keep the query only if you set fullUrls.\n const url = (value: string): string =>\n this.ctx.config.capture.fullUrls ? value : stripUrlQuery(value);\n\n if (script?.invoker) {\n // The invoker of a script entry is the script URL. Other invokers, for example\n // \"IMG#hero.onload\", contain a \"#\" that is not a fragment.\n const { invoker } = script;\n attrs[\"frame.script.invoker\"] = invoker.includes(\"://\") ? url(invoker) : invoker;\n }\n\n if (script?.sourceURL) {\n attrs[\"frame.script.source\"] = url(script.sourceURL);\n }\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"frame\",\n message: `long frame ${String(duration)} ms`,\n });\n this.ctx.logger.logMetric(\"ui.long_frame.duration\", duration, \"ms\", \"histogram\", attrs);\n }\n}\n"],"mappings":";;;AAWA,IAAMC,IAAc,CAAC,wBAAwB,UAAU;AAyBvD,SAASC,EAAc,GAA6D;CAClF,IAAIC;CAEJ,KAAK,IAAMC,KAAUC,KAAW,CAAC,GAC/B,CAAI,CAACF,KAAWC,EAAO,WAAWD,EAAQ,cACxC,IAAUC;CAId,OAAOD;AACT;AAGA,IAAaG,IAAb,MAAiD;CAgBlB;CAd7B,OAAgB;CAGhB;CAGA,SAAuC;EAAE,OAAO;EAAG,OAAO;CAAE;CAG5D,YAAA;CAKA,YAAY,GAAsC;EAArB,KAAA,MAAAC;CAAsB;CAGnD,UAAgB;EACd,IAAI,KAAK,UACP;EAKF,IAAM,EAAE,YAAS,KAAK,KAChBC,IAAQ,CAACC,EAAK;EACpB,EAAK,aAAa;EAGlB,IAAMC,IACJ,OAAO,sBAAwB,MAC3B,KAAA,IACA,oBAAoB,qBACpBC,IAAOV,EAAY,MAAM,MAASS,GAAW,SAASE,CAAI,CAAC;EAEjE,IAAID,MAAS,KAAA,GAAW;GACtB,IAAI,CAACH,GACH;GAGF,KAAK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AE;EAC1C,CAAC,GACD,KAAK,IAAI,OAAO,UAAU,0BAA0BA,GAAU,MAAM,aAAaC,CAAK;CACxF;AACF"}
@@ -15,7 +15,7 @@ export interface LogBatch {
15
15
  attempts: number;
16
16
  }
17
17
  /**
18
- * Tells whether a value from storage has all fields of a batch. `keyOf` cannot match
18
+ * Tells if a value from storage has all fields of a batch. `keyOf` cannot match
19
19
  * an entry without `id` after delivery. The library then retries that entry with no
20
20
  * end, and the entry blocks each batch behind it. An entry without `attempts` counts
21
21
  * as NaN. That count never reaches `maxAttempts`. Thus the library never drops the
@@ -1,7 +1,6 @@
1
1
  import { BUS_PROTOCOL } from "../constants";
2
- import type { Journey } from "../core/journey";
3
2
  import type { LogRecord } from "./log-record";
4
- /** Delivery role indicating whether this context sends records directly or forwards upstream. */
3
+ /** Delivery role. It tells if this context sends its records or forwards them upstream. */
5
4
  export type BusRole = "sender" | "forwarder";
6
5
  /**
7
6
  * Kind of transport channel. The bus uses it to route incoming and outgoing messages.
@@ -55,11 +54,15 @@ export type BusMessage =
55
54
  from: string;
56
55
  records: LogRecord[];
57
56
  }
58
- /** Broadcast update announcing a new or ended journey state. */
57
+ /**
58
+ * Journey update, or the answer to a journey question. An answer holds the address of the
59
+ * context that asked in `to`. The payload comes from another realm. The receiver parses it.
60
+ */
59
61
  | {
60
62
  t: "journey";
61
63
  from: string;
62
- journey: Journey | null;
64
+ to?: string;
65
+ journey: unknown;
63
66
  }
64
67
  /** Query requesting active journey state from connected peers. */
65
68
  | {
@@ -25,7 +25,7 @@ export interface WebVitalsMetric {
25
25
  }
26
26
  /**
27
27
  * Callback `web-vitals` invokes with a measurement.
28
- * @param metric The measurement being reported.
28
+ * @param metric The measurement that `web-vitals` reports.
29
29
  */
30
30
  export type WebVitalsReporter = (metric: WebVitalsMetric) => void;
31
31
  /** The five `web-vitals` entry points this library subscribes to. */
@@ -106,7 +106,7 @@ export interface OtelApi {
106
106
  }
107
107
  /**
108
108
  * Supplies the `@opentelemetry/api` module without a hard dependency on it.
109
- * @returns A promise resolving to the module.
109
+ * @returns A promise that resolves to the module.
110
110
  */
111
111
  export type OtelLoader = () => Promise<OtelApi>;
112
112
  /** Sampling policy. It controls which records the library keeps. */
@@ -148,6 +148,7 @@ export interface BusOptions {
148
148
  /**
149
149
  * Origins that can send postMessage records to this document.
150
150
  * A document that gets records from a cross-origin iframe must list the iframe origin.
151
+ * The library does not accept "null". A sandboxed frame must set `mode: "sender"`.
151
152
  * @default []
152
153
  */
153
154
  trustedOrigins: string[];
@@ -159,6 +160,24 @@ export interface BusOptions {
159
160
  */
160
161
  openFinRole: "auto" | "provider" | "client";
161
162
  }
163
+ /**
164
+ * Where a journey id applies.
165
+ * - "context": each document, frame or worker keeps its own journey.
166
+ * - "tab": a frame or a worker adopts the journey of the context that owns it. A journey
167
+ * does not go to another tab.
168
+ * - "origin": each context of the origin adopts each journey. The broadcast link also reaches
169
+ * other tabs.
170
+ * - "auto": "origin" in OpenFin and "tab" in a browser.
171
+ */
172
+ export type JourneyScope = "auto" | "context" | "tab" | "origin";
173
+ /** Journey settings. */
174
+ export interface JourneyOptions {
175
+ /**
176
+ * Which contexts adopt a journey that one context starts.
177
+ * @default "auto"
178
+ */
179
+ scope: JourneyScope;
180
+ }
162
181
  /** Console method that the console capture can wrap. */
163
182
  export type CapturedConsoleMethod = "error" | "warn" | "info" | "log";
164
183
  /**
@@ -236,14 +255,15 @@ export interface CaptureOptions {
236
255
  */
237
256
  ignoreUrls: (string | RegExp)[];
238
257
  /**
239
- * Targets that receive a `traceparent` header. A pattern that matches all URLs breaks
240
- * CORS on third-party endpoints.
258
+ * Targets that receive a `traceparent` header. A string is an origin and matches a request
259
+ * to that origin only. A RegExp tests the full URL. Start each RegExp with `^`. A pattern that
260
+ * matches all URLs breaks CORS on third-party endpoints.
241
261
  * @default []
242
262
  */
243
263
  propagateTraceHeaderTo: (string | RegExp)[];
244
264
  /**
245
265
  * Supplies the `web-vitals` module without a hard dependency on the package.
246
- * @returns A promise resolving to the `web-vitals` module.
266
+ * @returns A promise that resolves to the `web-vitals` module.
247
267
  */
248
268
  webVitalsLoader?: () => Promise<WebVitalsModule>;
249
269
  }
@@ -312,7 +332,7 @@ export interface TransportResponse {
312
332
  * Sends one batch through a channel of the app, such as an API client, a WebSocket or IPC.
313
333
  * A rejected promise counts as a network error. The library then sends the batch again.
314
334
  * @param request Batch to send.
315
- * @returns Promise resolving to the answer of the server.
335
+ * @returns Promise that resolves to the answer of the server.
316
336
  */
317
337
  export type Transport = (request: TransportRequest) => Promise<TransportResponse>;
318
338
  /**
@@ -346,7 +366,7 @@ export interface ObservabilityConfig {
346
366
  */
347
367
  environment?: string;
348
368
  /**
349
- * Master switch. False makes every log call a no-op.
369
+ * Master switch. With false, each log call does nothing.
350
370
  * @default true
351
371
  */
352
372
  enabled?: boolean;
@@ -356,7 +376,7 @@ export interface ObservabilityConfig {
356
376
  */
357
377
  minLevel?: LogLevel;
358
378
  /**
359
- * Whether to gzip a payload that is larger than the compression threshold.
379
+ * Set "gzip" to compress a payload that is larger than the compression threshold.
360
380
  * Set "none" for an ingest endpoint that rejects gzip.
361
381
  * @default "gzip"
362
382
  */
@@ -372,7 +392,7 @@ export interface ObservabilityConfig {
372
392
  * @default "omit"
373
393
  */
374
394
  credentials?: RequestCredentials;
375
- /** Extra request headers, or a function returning them. */
395
+ /** Extra request headers, or a function returning them. `undefined` removes the headers. */
376
396
  headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
377
397
  /**
378
398
  * Backing store for undelivered records.
@@ -397,6 +417,11 @@ export interface ObservabilityConfig {
397
417
  * @see {@link BusOptions}
398
418
  */
399
419
  bus?: Partial<BusOptions>;
420
+ /**
421
+ * Journey settings.
422
+ * @see {@link JourneyOptions}
423
+ */
424
+ journey?: Partial<JourneyOptions>;
400
425
  /**
401
426
  * Automatic instrumentation.
402
427
  * @see {@link CaptureOptions}
@@ -426,7 +451,8 @@ export interface ObservabilityConfig {
426
451
  */
427
452
  otelLoader?: OtelLoader;
428
453
  /**
429
- * Rewrites or drops a record before the library sends it.
454
+ * Rewrites or drops a record before the library sends it. If the hook throws or returns a
455
+ * value that is not a record, the library drops the record.
430
456
  * @param record The record that the library is about to send.
431
457
  * @returns The record to send, or `null` to drop it.
432
458
  */
@@ -447,11 +473,11 @@ export interface ResolvedConfig {
447
473
  serviceVersion: string;
448
474
  /** The library reports this value as `deployment.environment`. */
449
475
  environment: string;
450
- /** Master switch. False makes every log call a no-op. */
476
+ /** Master switch. With false, each log call does nothing. */
451
477
  enabled: boolean;
452
478
  /** Minimum level that the library logs. */
453
479
  minLevel: LogLevel;
454
- /** Whether to gzip a payload that is larger than the compression threshold. */
480
+ /** "gzip" compresses a payload that is larger than the compression threshold. */
455
481
  compression: "gzip" | "none";
456
482
  /** The library passes this value to `fetch`. */
457
483
  credentials: RequestCredentials;
@@ -469,6 +495,11 @@ export interface ResolvedConfig {
469
495
  * @see {@link BusOptions}
470
496
  */
471
497
  bus: BusOptions;
498
+ /**
499
+ * Journey settings.
500
+ * @see {@link JourneyOptions}
501
+ */
502
+ journey: JourneyOptions;
472
503
  /**
473
504
  * Automatic instrumentation.
474
505
  * @see {@link CaptureOptions}
@@ -1,11 +1,11 @@
1
1
  /** OpenTelemetry severity levels, in ascending order. */
2
2
  export type LogLevel = "TRACE" | "DEBUG" | "INFO" | "WARN" | "ERROR" | "FATAL";
3
3
  /**
4
- * Kind of thing a record describes: `action` (something a person did),
5
- * `event` (something the application did), `metric` (a measurement), or
6
- * `system` (this library's own diagnostic output).
4
+ * Kind of thing that a record tells about. `action` is something that a person did.
5
+ * `event` is something that the application did. `metric` is a measurement.
6
+ * `log` is a log call of the application. `system` is the output of this library.
7
7
  */
8
- export type LogType = "action" | "event" | "metric" | "system";
8
+ export type LogType = "action" | "event" | "metric" | "log" | "system";
9
9
  /** Metric value type: level, running total, or distribution. */
10
10
  export type MetricType = "gauge" | "counter" | "histogram";
11
11
  /** Internal record shape. A serializer converts it to the payload format. */
@@ -46,11 +46,17 @@ export interface LogRecord {
46
46
  */
47
47
  export declare function nowUnixNano(): string;
48
48
  /**
49
- * Checks whether a value has the shape `LogRecord` requires.
49
+ * Checks if a value is a known log level. An own-key check rejects "toString".
50
+ * @param value The value to check.
51
+ * @returns True if `value` is a key of the severity table.
52
+ */
53
+ export declare function isLogLevel(value: unknown): value is LogLevel;
54
+ /**
55
+ * Checks if a value has the shape `LogRecord` requires.
50
56
  * Use it to validate records from another realm. A malformed record throws
51
57
  * during serialization. The check accepts any string as `severityText`, not only
52
58
  * a known level. Thus an unknown level from a newer version passes.
53
59
  * @param value The value to check.
54
- * @returns Whether `value` has the shape `LogRecord` requires.
60
+ * @returns True if `value` has the shape `LogRecord` requires.
55
61
  */
56
62
  export declare function isLogRecord(value: unknown): value is LogRecord;
@@ -0,0 +1,2 @@
1
+ const e=require("./platform-D4wu1eIF.cjs"),t=require("./patch-BX8KrPCT.cjs"),n=require("./library-request-C9uJFlbq.cjs");function r(e,t){return typeof e==`string`&&t.some(t=>typeof t==`string`?e.includes(t):t.test(e))}function i(){return XMLHttpRequest.prototype}function a(e){if(typeof e==`string`)return e;if(e instanceof URL)return e.href;if(typeof e==`object`&&e){let{url:t}=e;if(typeof t==`string`)return t}return String(e)}function o(e,t){let n=t?.method;return n===void 0&&typeof e==`object`&&e&&(n=e.method),c(n??`GET`)}function s(e){return typeof e==`object`&&!(e instanceof URL)&&!(e instanceof Request)}function c(e){return typeof e==`string`?e.toUpperCase():String(e)}var l=class{ctx;name=`network`;installed=!1;restores=[];constructor(e){this.ctx=e}install(){this.installed||(this.installed=!0,this.ctx.config.capture.fetch&&this.installFetch(),this.ctx.config.capture.xhr&&this.installXhr())}uninstall(){if(this.installed){this.installed=!1;for(let e of this.restores.splice(0))e()}}ignored(e){return n.t()||r(e,this.ctx.config.capture.ignoreUrls)}propagates(e){let t=this.ctx.config.capture.propagateTraceHeaderTo;if(t.length===0)return!1;let n=this.ctx.diagnostics.guard(`capture.header_failed`,`The library could not read the origin of a request URL. Only a RegExp target can match it.`,()=>new URL(e,location.href).origin);return t.some(t=>typeof t==`string`?t===n:t.test(e))}installFetch(){if(typeof globalThis.fetch!=`function`)return;let e=!0,n=(e,t)=>this.prepareFetch(e,t),r=(e,t,n,r,i)=>{this.record(e,t,n,r,i)},i=t.t(globalThis,`fetch`,t=>{let i=t.bind(globalThis);return async function(t,a){let o=e?n(t,a):void 0;if(!o)return i(t,a);let s=performance.now();try{let e=await i(o.input,o.init);return r(o.method,o.url,e.status,performance.now()-s,void 0),e}catch(e){throw r(o.method,o.url,0,performance.now()-s,e),e}}});this.restores.push(()=>{e=!1,i()})}prepareFetch(e,t){let n=this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not read a fetch request. It sends the request unchanged.`,()=>{let n=a(e);if(!this.ignored(n))return{method:o(e,t),url:n,propagate:this.propagates(n)}});if(!n)return;let{method:r,url:i}=n,c={method:r,url:i,input:e,init:t};if(!n.propagate||s(e))return c;try{let n=Object.entries(this.ctx.tracing.headers());if(e instanceof Request){let t=new Headers(e.headers);for(let[e,r]of n)t.set(e,r);c.input=new Request(e,{headers:t})}else{let e=new Headers(t?.headers);for(let[t,r]of n)e.set(t,r);c.init={...t,headers:e}}}catch(n){c.input=e,c.init=t,this.ctx.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:i},n)}return c}installXhr(){if(typeof XMLHttpRequest>`u`)return;let e=!0,n=this.ctx,r=e=>this.ignored(e),o=e=>this.propagates(e),s=(e,t,n,r)=>{this.record(e,t,n,r,void 0)},l=i(),d=t.t(l,`open`,t=>function(r,i,...o){e&&n.diagnostics.guard(`capture.record_failed`,`The library could not read an XMLHttpRequest. It does not record the request.`,()=>{this.__uiobs={method:c(r),url:a(i),startedAt:0}}),t.apply(this,[r,i,...o])}),f=t.t(l,`send`,t=>function(...i){let a=e?this.__uiobs:void 0;a&&n.diagnostics.guard(`capture.record_failed`,`The library could not record ${a.method} ${a.url}.`,()=>{r(a.url)||(a.startedAt=performance.now(),this.addEventListener(`loadend`,()=>{s(a.method,a.url,this.status,performance.now()-a.startedAt)}),o(a.url)&&u(this,a.url,n))}),t.apply(this,i)});this.restores.push(()=>{e=!1,d(),f()})}record(t,n,r,i,a){let o=this.ctx.config.capture.fullUrls?n:e.r(n);this.ctx.diagnostics.guard(`capture.record_failed`,`The library could not record ${t} ${o}.`,()=>{let e=Math.round(i);this.ctx.breadcrumbs.push({t:Date.now(),category:`http`,message:`${t} ${o} ${r===0?`failed`:String(r)}`,data:{durationMs:e}});let n={"http.request.method":t,"url.full":o,"http.response.status_code":r,"http.duration_ms":e};r===0?this.ctx.logger.error(`${t} ${o} failed`,a,n):r>=400?this.ctx.logger.warn(`${t} ${o} returned ${String(r)}`,n):this.ctx.logger.debug(`${t} ${o}`,n)})}};function u(e,t,n){try{for(let[t,r]of Object.entries(n.tracing.headers()))e.setRequestHeader(t,r)}catch(e){n.diagnostics.report(`capture.header_failed`,`The library could not add the traceparent header. It sends the request unchanged.`,{url:t},e)}}exports.NetworkCapture=l;
2
+ //# sourceMappingURL=network-BAV7ipyn.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"network-BAV7ipyn.cjs","names":["isLibraryRequest","patch","stripUrlQuery","require_platform","require_patch","require_library_request","matchesAny","url","patterns","pattern","xhrMethods","readUrl","input","readFetchMethod","requested","init","toMethod","isForeignInput","method","NetworkCapture","ctx","restore","targets","origin","target","active","prepare","record","status","durationMs","error","call","original","plan","startedAt","response","read","injected","headers","key","value","ignored","propagates","proto","restoreOpen","rest","originalOpen","restoreSend","args","meta","addTraceHeaders","originalSend","rounded","attributes","xhr"],"sources":["../src/capture/types.ts","../src/capture/network.ts"],"sourcesContent":["// src/capture/types.ts\n//\n// Shared interfaces, logger abstractions, and utility helpers for auto-capture modules.\n\nimport type { BreadcrumbBuffer } from \"../core/breadcrumbs\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { MetricType } from \"../models/log-record\";\nimport type { TraceEngine } from \"../utils/tracing\";\n\n/**\n * Logging interface that auto-capture modules use. A reference to the runtime class\n * here causes an import cycle. The runtime installs the capture modules.\n */\nexport interface CaptureLogger {\n /**\n * Logs an error event with an associated error instance or reason.\n * @param message Error description.\n * @param error Caught error instance or reason.\n * @param payload Optional attributes.\n */\n error(message: string, error?: unknown, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a warning event.\n * @param message Warning description.\n * @param payload Optional attributes.\n */\n warn(message: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a discrete lifecycle or user event.\n * @param name Event identifier.\n * @param payload Optional attributes.\n */\n logEvent(name: string, payload?: Record<string, unknown>): void;\n\n /**\n * Logs a numerical metric measurement.\n * @param name Metric name.\n * @param value Numerical measurement.\n * @param unit Unit of measurement.\n * @param type Metric type classification.\n * @param attrs Optional metric attributes.\n */\n logMetric(\n name: string,\n value: number,\n unit?: string,\n type?: MetricType,\n attrs?: Record<string, unknown>,\n ): void;\n\n /**\n * Logs a diagnostic debug message.\n * @param message Debug message.\n * @param payload Optional attributes.\n */\n debug(message: string, payload?: Record<string, unknown>): void;\n}\n\n/**\n * Capture work that runs one time for each document, not one time for each\n * install. A reconfigure builds new capture instances. Thus instance state\n * cannot hold these flags. web-vitals has no unsubscribe. A second subscription\n * reports each metric two times.\n */\nexport interface CaptureOnce {\n /** True after the library subscribes the web-vitals reporters. */\n webVitals: boolean;\n /** True after the library reports navigation timing. */\n navigationTiming: boolean;\n /** True after the first long frame install. Only that install reads buffered frames. */\n longFrames: boolean;\n}\n\n/** Shared runtime dependencies provided to auto-capture instances. */\nexport interface CaptureContext {\n /** Active runtime configuration. */\n config: ResolvedConfig;\n /** Diagnostics reporter for capture faults. */\n diagnostics: Diagnostics;\n /** Logger instance for recorded telemetry. */\n logger: CaptureLogger;\n /** Buffer for recording contextual breadcrumbs. */\n breadcrumbs: BreadcrumbBuffer;\n /** Active trace context provider. */\n tracing: TraceEngine;\n /** Guards for the capture work that a reinstall must not repeat. */\n once: CaptureOnce;\n}\n\n/** Lifecycle interface for browser instrumentation modules. */\nexport interface Capture {\n /** Module identifier used in diagnostics. */\n readonly name: string;\n /**\n * Attaches instrumentation listeners and patches target APIs. A second patch on a\n * patched function adds a second wrapper and doubles each record. A second call\n * must do nothing.\n */\n install(): void;\n /** Restores native APIs and removes registered listeners. */\n uninstall(): void;\n}\n\n/**\n * Tests if a URL matches any string substring or regular expression pattern.\n * @param url Target URL to test. A value that is not a string matches nothing.\n * @param patterns Substrings and regular expressions to test against.\n * @returns True if any pattern matches the URL.\n */\nexport function matchesAny(url: unknown, patterns: (string | RegExp)[]): boolean {\n // Guard against a URL that is not a string. includes() on it throws in the call of the host.\n if (typeof url !== \"string\") {\n return false;\n }\n\n return patterns.some((pattern) =>\n typeof pattern === \"string\" ? url.includes(pattern) : pattern.test(url),\n );\n}\n","// src/capture/network.ts\n//\n// Instruments fetch and XMLHttpRequest to record network request outcomes and timing.\n\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { patch } from \"../utils/patch\";\nimport { stripUrlQuery } from \"../utils/platform\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Signature of the global fetch function. */\ntype FetchFn = typeof fetch;\n\n/** Request data that the XHR wrapper keeps from open to send. */\ninterface XhrMeta {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Performance timestamp at send. */\n startedAt: number;\n}\n\n/** XMLHttpRequest extended with internal telemetry tracking metadata. */\ntype Tracked = XMLHttpRequest & {\n __uiobs?: XhrMeta;\n};\n\n/** Unbound prototype methods intercepted on XMLHttpRequest. */\ninterface XhrMethods {\n open: (this: XMLHttpRequest, ...args: never[]) => void;\n send: (this: XMLHttpRequest, ...args: never[]) => void;\n}\n\n/** Returns the XMLHttpRequest prototype. */\nfunction xhrMethods(): XhrMethods {\n return XMLHttpRequest.prototype;\n}\n\n/** The fetch call to make, and the method and URL to record. */\ninterface FetchPlan {\n /** Uppercase HTTP method. */\n method: string;\n /** Request target URL. */\n url: string;\n /** Input to pass to the original fetch. */\n input: RequestInfo | URL;\n /** Init to pass to the original fetch. */\n init: RequestInit | undefined;\n}\n\n/**\n * Reads the URL of a fetch input or an XHR URL argument.\n * A Request from another realm fails `instanceof Request`. Its `url` property still works.\n * @param input String, URL, Request, or an object with a text form.\n * @returns The URL.\n * @throws TypeError when the input has no text form. Call it inside a diagnostics guard.\n */\nfunction readUrl(input: unknown): string {\n if (typeof input === \"string\") {\n return input;\n }\n\n if (input instanceof URL) {\n return input.href;\n }\n\n if (typeof input === \"object\" && input !== null) {\n const { url } = input as { url?: unknown };\n if (typeof url === \"string\") {\n return url;\n }\n }\n\n // fetch accepts each value with a text form.\n return String(input);\n}\n\n/**\n * Reads the method of a fetch call. The init method wins over the Request method.\n * @param input Fetch input.\n * @param init Fetch init.\n * @returns Uppercase method. The default is GET.\n */\nfunction readFetchMethod(input: unknown, init: RequestInit | undefined): string {\n let requested: unknown = init?.method;\n\n if (requested === undefined && typeof input === \"object\" && input !== null) {\n requested = (input as { method?: unknown }).method;\n }\n\n return toMethod(requested ?? \"GET\");\n}\n\n/**\n * Tests if a fetch input is an object that is not a Request or a URL of this realm.\n * An example is a Request from an iframe.\n * @param input Fetch input.\n * @returns True for a foreign object.\n */\nfunction isForeignInput(input: unknown): boolean {\n return typeof input === \"object\" && !(input instanceof URL) && !(input instanceof Request);\n}\n\n/**\n * Converts a method argument to text. A method that is not a string does not throw.\n * @param method Method argument of the caller.\n * @returns Uppercase method for a string, or the text form of another value.\n */\nfunction toMethod(method: unknown): string {\n return typeof method === \"string\" ? method.toUpperCase() : String(method);\n}\n\n/** Instruments global fetch and XMLHttpRequest to capture request durations and outcomes. */\nexport class NetworkCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"network\";\n\n /** Prevents a second wrap on a wrapped function. */\n private installed = false;\n\n /** Restore functions of the installed wrappers. */\n private readonly restores: (() => void)[] = [];\n\n /**\n * @param ctx Capture context containing configuration, diagnostics, logger, breadcrumbs, and tracing.\n */\n constructor(private readonly ctx: CaptureContext) {}\n\n /** Instruments configured network transport APIs. */\n install(): void {\n if (this.installed) {\n return;\n }\n this.installed = true;\n\n if (this.ctx.config.capture.fetch) {\n this.installFetch();\n }\n if (this.ctx.config.capture.xhr) {\n this.installXhr();\n }\n }\n\n /**\n * Restores each host function that still holds the wrapper of this capture.\n * A wrapper that another script wrapped again stays in place and records nothing.\n */\n uninstall(): void {\n if (!this.installed) {\n return;\n }\n this.installed = false;\n\n for (const restore of this.restores.splice(0)) {\n restore();\n }\n }\n\n /**\n * Tests if a URL matches ignore patterns.\n * @param url Request target URL.\n * @returns True if telemetry must exclude the URL.\n */\n private ignored(url: string): boolean {\n // resolveConfig always adds the endpoint to ignoreUrls. Without it, a failed POST\n // makes a log record. That record causes a new POST, and the loop does not stop.\n // A custom transport has no known URL. Its request starts inside the library scope.\n return isLibraryRequest() || matchesAny(url, this.ctx.config.capture.ignoreUrls);\n }\n\n /**\n * Tests if a request gets the trace headers.\n * @param url Request target URL.\n * @returns True if the URL is in propagateTraceHeaderTo.\n */\n private propagates(url: string): boolean {\n // Add headers only to allowlisted URLs. A traceparent on a third-party request causes\n // a CORS preflight. The third party does not answer it, and its API stops working.\n const targets = this.ctx.config.capture.propagateTraceHeaderTo;\n if (targets.length === 0) {\n return false;\n }\n\n // A string target is an origin. A relative URL resolves against the page.\n const origin = this.ctx.diagnostics.guard(\n \"capture.header_failed\",\n \"The library could not read the origin of a request URL. Only a RegExp target can match it.\",\n () => new URL(url, location.href).origin,\n );\n\n return targets.some((target) =>\n typeof target === \"string\" ? target === origin : target.test(url),\n );\n }\n\n /** Instruments globalThis.fetch with tracing injection and outcome logging. */\n private installFetch(): void {\n if (typeof globalThis.fetch !== \"function\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const prepare = (input: RequestInfo | URL, init: RequestInit | undefined) =>\n this.prepareFetch(input, init);\n const record = (\n method: string,\n url: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void => {\n this.record(method, url, status, durationMs, error);\n };\n\n const restore = patch(globalThis, \"fetch\", (original: FetchFn) => {\n const call = original.bind(globalThis);\n\n return async function instrumentedFetch(input, init) {\n const plan = active ? prepare(input, init) : undefined;\n if (!plan) {\n return call(input, init);\n }\n\n const startedAt = performance.now();\n try {\n const response = await call(plan.input, plan.init);\n record(plan.method, plan.url, response.status, performance.now() - startedAt, undefined);\n return response;\n } catch (error) {\n record(plan.method, plan.url, 0, performance.now() - startedAt, error);\n throw error;\n }\n };\n });\n\n this.restores.push(() => {\n active = false;\n restore();\n });\n }\n\n /**\n * Reads a fetch call and adds the trace headers to an allowlisted request.\n * @param input Fetch input of the caller.\n * @param init Fetch init of the caller.\n * @returns The plan, or undefined to send the request unchanged and record nothing.\n */\n private prepareFetch(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n ): FetchPlan | undefined {\n // A read here runs inside the fetch call of the caller. A throw must not fail the request.\n const read = this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read a fetch request. It sends the request unchanged.\",\n (): { method: string; url: string; propagate: boolean } | undefined => {\n const url = readUrl(input);\n if (this.ignored(url)) {\n return undefined;\n }\n\n return { method: readFetchMethod(input, init), url, propagate: this.propagates(url) };\n },\n );\n\n if (!read) {\n return undefined;\n }\n\n const { method, url } = read;\n const plan: FetchPlan = { method, url, input, init };\n // An init with headers replaces all headers of a foreign Request, for example\n // Authorization. Send a foreign input without the trace headers.\n if (!read.propagate || isForeignInput(input)) {\n return plan;\n }\n\n try {\n const injected = Object.entries(this.ctx.tracing.headers());\n\n if (input instanceof Request) {\n // Do not spread a non-empty init with a Request input. That runs the Request\n // constructor on `input` again and reads its body. A second read of a body\n // causes a TypeError.\n const headers = new Headers(input.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.input = new Request(input, { headers });\n } else {\n const headers = new Headers(init?.headers);\n for (const [key, value] of injected) {\n headers.set(key, value);\n }\n plan.init = { ...init, headers };\n }\n } catch (error) {\n // Send the request that the caller gave, without changes. A missing header is\n // better than a failed request.\n plan.input = input;\n plan.init = init;\n this.ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n\n return plan;\n }\n\n /** Instruments XMLHttpRequest open and send prototype methods. */\n private installXhr(): void {\n if (typeof XMLHttpRequest === \"undefined\") {\n return;\n }\n\n // Uninstall clears the flag. A wrapper that stays in place then only calls the original.\n let active = true;\n const ctx = this.ctx;\n const ignored = (url: string): boolean => this.ignored(url);\n const propagates = (url: string): boolean => this.propagates(url);\n const record = (method: string, url: string, status: number, durationMs: number): void => {\n this.record(method, url, status, durationMs, undefined);\n };\n\n const proto = xhrMethods();\n\n const restoreOpen = patch(\n proto,\n \"open\",\n (originalOpen) =>\n function (this: Tracked, method: unknown, url: unknown, ...rest: never[]) {\n if (active) {\n // A read here runs inside the open call of the caller. A throw must not fail it.\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The library could not read an XMLHttpRequest. It does not record the request.\",\n () => {\n this.__uiobs = { method: toMethod(method), url: readUrl(url), startedAt: 0 };\n },\n );\n }\n originalOpen.apply(this, [method, url, ...rest] as never[]);\n },\n );\n\n const restoreSend = patch(\n proto,\n \"send\",\n (originalSend) =>\n function (this: Tracked, ...args: never[]) {\n const meta = active ? this.__uiobs : undefined;\n if (meta) {\n ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${meta.method} ${meta.url}.`,\n () => {\n if (ignored(meta.url)) {\n return;\n }\n\n meta.startedAt = performance.now();\n this.addEventListener(\"loadend\", () => {\n record(meta.method, meta.url, this.status, performance.now() - meta.startedAt);\n });\n\n // setRequestHeader works only between open and send.\n if (propagates(meta.url)) {\n addTraceHeaders(this, meta.url, ctx);\n }\n },\n );\n }\n originalSend.apply(this, args);\n },\n );\n\n this.restores.push(() => {\n active = false;\n restoreOpen();\n restoreSend();\n });\n }\n\n /**\n * Records request outcome attributes and breadcrumb entry.\n * @param method Uppercase HTTP method.\n * @param target Request target URL. The method removes the query unless you set fullUrls.\n * @param status HTTP response status code, or 0 on failure.\n * @param durationMs Request duration in milliseconds.\n * @param error Caught error instance on failed requests.\n */\n private record(\n method: string,\n target: string,\n status: number,\n durationMs: number,\n error: unknown,\n ): void {\n // Remove the query here, not at the call sites. ignoreUrls and propagateTraceHeaderTo\n // match on the full URL. Only the recorded URL loses the query string.\n const url = this.ctx.config.capture.fullUrls ? target : stripUrlQuery(target);\n\n // This code runs inside the fetch call of the caller. An error here must not cause\n // the request of the caller to fail.\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n `The library could not record ${method} ${url}.`,\n () => {\n const rounded = Math.round(durationMs);\n\n this.ctx.breadcrumbs.push({\n t: Date.now(),\n category: \"http\",\n message: `${method} ${url} ${status === 0 ? \"failed\" : String(status)}`,\n data: { durationMs: rounded },\n });\n\n const attributes = {\n \"http.request.method\": method,\n \"url.full\": url,\n \"http.response.status_code\": status,\n \"http.duration_ms\": rounded,\n };\n\n if (status === 0) {\n this.ctx.logger.error(`${method} ${url} failed`, error, attributes);\n return;\n }\n if (status >= 400) {\n this.ctx.logger.warn(`${method} ${url} returned ${String(status)}`, attributes);\n return;\n }\n\n // Log a success at DEBUG. The default minLevel of INFO drops it.\n // Only failures use bandwidth.\n this.ctx.logger.debug(`${method} ${url}`, attributes);\n },\n );\n }\n}\n\n/**\n * Adds the trace headers to an open XHR. A failure sends the request without them.\n * @param xhr Request between open and send.\n * @param url Request target URL, for the diagnostic.\n * @param ctx Capture context with tracing and diagnostics.\n */\nfunction addTraceHeaders(xhr: XMLHttpRequest, url: string, ctx: CaptureContext): void {\n try {\n for (const [key, value] of Object.entries(ctx.tracing.headers())) {\n xhr.setRequestHeader(key, value);\n }\n } catch (error) {\n ctx.diagnostics.report(\n \"capture.header_failed\",\n \"The library could not add the traceparent header. It sends the request unchanged.\",\n { url },\n error,\n );\n }\n}\n"],"mappings":"yHAgHA,SAAgBM,E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