@utk09/ui-observability 0.9.4 → 0.9.5

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 (208) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +122 -94
  3. package/dist/batch-BQFtb3i5.cjs +2 -0
  4. package/dist/batch-BQFtb3i5.cjs.map +1 -0
  5. package/dist/{batch-D-4xl7op.js → batch-BUJh-1jZ.js} +7 -5
  6. package/dist/batch-BUJh-1jZ.js.map +1 -0
  7. package/dist/bus/bus.d.ts +76 -2
  8. package/dist/bus/links.d.ts +9 -2
  9. package/dist/bus/validation.d.ts +7 -0
  10. package/dist/bus-BW6N-pY8.cjs +2 -0
  11. package/dist/bus-BW6N-pY8.cjs.map +1 -0
  12. package/dist/bus-DeOPHWaD.js +647 -0
  13. package/dist/bus-DeOPHWaD.js.map +1 -0
  14. package/dist/capture/storm.d.ts +2 -1
  15. package/dist/capture/types.d.ts +2 -0
  16. package/dist/{console-Boqa7new.cjs → console-Ce6heqZZ.cjs} +2 -2
  17. package/dist/console-Ce6heqZZ.cjs.map +1 -0
  18. package/dist/{console-BT7mcgU6.js → console-DbAZYJuy.js} +4 -4
  19. package/dist/console-DbAZYJuy.js.map +1 -0
  20. package/dist/constants-CN7GE1Lt.js +246 -0
  21. package/dist/constants-CN7GE1Lt.js.map +1 -0
  22. package/dist/constants-CW-MlHdY.cjs +2 -0
  23. package/dist/constants-CW-MlHdY.cjs.map +1 -0
  24. package/dist/constants.d.ts +29 -9
  25. package/dist/context-storage-BjzeBSxH.cjs +2 -0
  26. package/dist/context-storage-BjzeBSxH.cjs.map +1 -0
  27. package/dist/context-storage-DxZf4Gfh.js +52 -0
  28. package/dist/context-storage-DxZf4Gfh.js.map +1 -0
  29. package/dist/core/breadcrumbs.d.ts +7 -2
  30. package/dist/core/context.d.ts +2 -0
  31. package/dist/core/diagnostics.d.ts +11 -3
  32. package/dist/core/meter.d.ts +6 -1
  33. package/dist/core/pipeline.d.ts +29 -2
  34. package/dist/core/record.d.ts +2 -1
  35. package/dist/core/runtime.d.ts +91 -3
  36. package/dist/core/sampling.d.ts +3 -1
  37. package/dist/core/sender.d.ts +35 -1
  38. package/dist/deadline-5_PecIl5.js +26 -0
  39. package/dist/deadline-5_PecIl5.js.map +1 -0
  40. package/dist/deadline-XSnm95pg.cjs +2 -0
  41. package/dist/deadline-XSnm95pg.cjs.map +1 -0
  42. package/dist/emergency-queue-BYUyDHGD.js +69 -0
  43. package/dist/emergency-queue-BYUyDHGD.js.map +1 -0
  44. package/dist/emergency-queue-Cs1hrjsC.cjs +2 -0
  45. package/dist/emergency-queue-Cs1hrjsC.cjs.map +1 -0
  46. package/dist/{errors-BDI96zKc.js → errors-BhC7HTSt.js} +8 -9
  47. package/dist/errors-BhC7HTSt.js.map +1 -0
  48. package/dist/errors-CgY633cG.cjs +3 -0
  49. package/dist/errors-CgY633cG.cjs.map +1 -0
  50. package/dist/factory-C5TujXlU.js +280 -0
  51. package/dist/factory-C5TujXlU.js.map +1 -0
  52. package/dist/factory-CNj4DH3n.cjs +2 -0
  53. package/dist/factory-CNj4DH3n.cjs.map +1 -0
  54. package/dist/fixed-window-CtaFHanJ.js +12 -0
  55. package/dist/fixed-window-CtaFHanJ.js.map +1 -0
  56. package/dist/fixed-window-CvESpFYV.cjs +2 -0
  57. package/dist/fixed-window-CvESpFYV.cjs.map +1 -0
  58. package/dist/identity-8vKkyAWm.js +103 -0
  59. package/dist/identity-8vKkyAWm.js.map +1 -0
  60. package/dist/identity-Da9TkuKd.cjs +2 -0
  61. package/dist/identity-Da9TkuKd.cjs.map +1 -0
  62. package/dist/index.cjs +1 -1
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.ts +45 -7
  65. package/dist/index.js +908 -529
  66. package/dist/index.js.map +1 -1
  67. package/dist/indexeddb-storage-BTfIFRHF.cjs +2 -0
  68. package/dist/indexeddb-storage-BTfIFRHF.cjs.map +1 -0
  69. package/dist/{indexeddb-storage-HgkQUTyS.js → indexeddb-storage-CCA1LvtO.js} +33 -18
  70. package/dist/indexeddb-storage-CCA1LvtO.js.map +1 -0
  71. package/dist/{interactions-Ck01cEij.js → interactions-BUDLxbv1.js} +16 -12
  72. package/dist/interactions-BUDLxbv1.js.map +1 -0
  73. package/dist/interactions-NHbLKrqe.cjs +2 -0
  74. package/dist/interactions-NHbLKrqe.cjs.map +1 -0
  75. package/dist/{journey-DRK0A8u_.js → journey-BUJ4WJxP.js} +12 -12
  76. package/dist/{journey-DRK0A8u_.js.map → journey-BUJ4WJxP.js.map} +1 -1
  77. package/dist/{journey-Co9OlzrW.cjs → journey-B_tTnvac.cjs} +2 -2
  78. package/dist/{journey-Co9OlzrW.cjs.map → journey-B_tTnvac.cjs.map} +1 -1
  79. package/dist/keys-BHhw_0Wh.cjs +2 -0
  80. package/dist/keys-BHhw_0Wh.cjs.map +1 -0
  81. package/dist/keys-D5r_GH9q.js +17 -0
  82. package/dist/keys-D5r_GH9q.js.map +1 -0
  83. package/dist/{library-request-ChCar5F8.js → library-request-BKOcaKtQ.js} +2 -2
  84. package/dist/{library-request-ChCar5F8.js.map → library-request-BKOcaKtQ.js.map} +1 -1
  85. package/dist/{library-request-gMFOCNcn.cjs → library-request-BaZOi4eg.cjs} +2 -2
  86. package/dist/{library-request-gMFOCNcn.cjs.map → library-request-BaZOi4eg.cjs.map} +1 -1
  87. package/dist/{long-frames-Bky6nZDF.cjs → long-frames-CF3qiSAX.cjs} +2 -2
  88. package/dist/long-frames-CF3qiSAX.cjs.map +1 -0
  89. package/dist/{long-frames-DDumopji.js → long-frames-DI5ypfAF.js} +5 -5
  90. package/dist/long-frames-DI5ypfAF.js.map +1 -0
  91. package/dist/models/batch.d.ts +4 -0
  92. package/dist/models/bus.d.ts +32 -9
  93. package/dist/models/config.d.ts +347 -9
  94. package/dist/models/drop.d.ts +1 -1
  95. package/dist/models/health.d.ts +27 -0
  96. package/dist/models/storage.d.ts +13 -0
  97. package/dist/network-CF8UO5PK.cjs +2 -0
  98. package/dist/network-CF8UO5PK.cjs.map +1 -0
  99. package/dist/{network-BsBZ6_-Q.js → network-DdzXDI3J.js} +18 -16
  100. package/dist/network-DdzXDI3J.js.map +1 -0
  101. package/dist/openfin-BwEN0uj4.js.map +1 -1
  102. package/dist/openfin-DtH2f7zX.cjs.map +1 -1
  103. package/dist/{platform-4yYjMD-B.js → platform-Bw1btWCT.js} +16 -10
  104. package/dist/platform-Bw1btWCT.js.map +1 -0
  105. package/dist/platform-DBSKTvFn.cjs +2 -0
  106. package/dist/platform-DBSKTvFn.cjs.map +1 -0
  107. package/dist/{remote-rules-1KqfVBIu.js → remote-rules-DIcC5vVC.js} +3 -3
  108. package/dist/{remote-rules-1KqfVBIu.js.map → remote-rules-DIcC5vVC.js.map} +1 -1
  109. package/dist/{remote-rules-BHgEGlYi.cjs → remote-rules-DpFmOef2.cjs} +2 -2
  110. package/dist/{remote-rules-BHgEGlYi.cjs.map → remote-rules-DpFmOef2.cjs.map} +1 -1
  111. package/dist/sampling-BVjspJWu.cjs +2 -0
  112. package/dist/sampling-BVjspJWu.cjs.map +1 -0
  113. package/dist/{sampling-nYIWP_vP.js → sampling-Cm3WhI0a.js} +26 -36
  114. package/dist/sampling-Cm3WhI0a.js.map +1 -0
  115. package/dist/{sanitize-BiUKCUG6.js → sanitize-C-ahCFsG.js} +2 -2
  116. package/dist/{sanitize-BiUKCUG6.js.map → sanitize-C-ahCFsG.js.map} +1 -1
  117. package/dist/{sanitize-BxuPSXOk.cjs → sanitize-DHucKGdi.cjs} +2 -2
  118. package/dist/{sanitize-BxuPSXOk.cjs.map → sanitize-DHucKGdi.cjs.map} +1 -1
  119. package/dist/sender-D3fRCR8d.cjs +3 -0
  120. package/dist/sender-D3fRCR8d.cjs.map +1 -0
  121. package/dist/sender-DUUmSglb.js +1163 -0
  122. package/dist/sender-DUUmSglb.js.map +1 -0
  123. package/dist/storage/context-storage.d.ts +89 -0
  124. package/dist/storage/emergency-queue.d.ts +9 -1
  125. package/dist/storage/factory.d.ts +7 -1
  126. package/dist/storage/idb-driver.d.ts +13 -0
  127. package/dist/storage/indexeddb-storage.d.ts +13 -0
  128. package/dist/storage/local-storage.d.ts +21 -1
  129. package/dist/storage/memory-storage.d.ts +13 -0
  130. package/dist/storage-BA9RqRO-.cjs +2 -0
  131. package/dist/storage-BA9RqRO-.cjs.map +1 -0
  132. package/dist/storage-w7Tslvlq.js +17 -0
  133. package/dist/storage-w7Tslvlq.js.map +1 -0
  134. package/dist/storm-CNZjsw4T.cjs +2 -0
  135. package/dist/storm-CNZjsw4T.cjs.map +1 -0
  136. package/dist/storm-Daq2jGHU.js +10 -0
  137. package/dist/storm-Daq2jGHU.js.map +1 -0
  138. package/dist/transport/retry-engine.d.ts +7 -2
  139. package/dist/transport/status-transport.d.ts +17 -0
  140. package/dist/types-BR9t_w28.js.map +1 -1
  141. package/dist/types-C7WNpnG1.cjs.map +1 -1
  142. package/dist/utils/fixed-window.d.ts +9 -0
  143. package/dist/utils/identity.d.ts +9 -2
  144. package/dist/utils/lock.d.ts +8 -0
  145. package/dist/utils/openfin.d.ts +1 -1
  146. package/dist/utils/platform.d.ts +3 -1
  147. package/dist/web-socket-BacvKOvD.cjs +2 -0
  148. package/dist/web-socket-BacvKOvD.cjs.map +1 -0
  149. package/dist/web-socket-CpsD8WAa.js +105 -0
  150. package/dist/web-socket-CpsD8WAa.js.map +1 -0
  151. package/package.json +1 -1
  152. package/dist/batch-C4oF6XZT.cjs +0 -2
  153. package/dist/batch-C4oF6XZT.cjs.map +0 -1
  154. package/dist/batch-D-4xl7op.js.map +0 -1
  155. package/dist/bus-Cyvq-Ngx.js +0 -478
  156. package/dist/bus-Cyvq-Ngx.js.map +0 -1
  157. package/dist/bus-rOhVuRee.cjs +0 -2
  158. package/dist/bus-rOhVuRee.cjs.map +0 -1
  159. package/dist/console-BT7mcgU6.js.map +0 -1
  160. package/dist/console-Boqa7new.cjs.map +0 -1
  161. package/dist/constants-BgRS6MB0.cjs +0 -2
  162. package/dist/constants-BgRS6MB0.cjs.map +0 -1
  163. package/dist/constants-L_d5YvvQ.js +0 -160
  164. package/dist/constants-L_d5YvvQ.js.map +0 -1
  165. package/dist/errors-BDI96zKc.js.map +0 -1
  166. package/dist/errors-_xEsCVXn.cjs +0 -3
  167. package/dist/errors-_xEsCVXn.cjs.map +0 -1
  168. package/dist/fixed-window-BR0bu32Y.cjs +0 -2
  169. package/dist/fixed-window-BR0bu32Y.cjs.map +0 -1
  170. package/dist/fixed-window-Re7jIRJH.js +0 -9
  171. package/dist/fixed-window-Re7jIRJH.js.map +0 -1
  172. package/dist/identity-Bwku7zzN.cjs +0 -2
  173. package/dist/identity-Bwku7zzN.cjs.map +0 -1
  174. package/dist/identity-Dtv917nz.js +0 -98
  175. package/dist/identity-Dtv917nz.js.map +0 -1
  176. package/dist/indexeddb-storage-Cvavrf-y.cjs +0 -2
  177. package/dist/indexeddb-storage-Cvavrf-y.cjs.map +0 -1
  178. package/dist/indexeddb-storage-HgkQUTyS.js.map +0 -1
  179. package/dist/interactions-Bhe1ft8P.cjs +0 -2
  180. package/dist/interactions-Bhe1ft8P.cjs.map +0 -1
  181. package/dist/interactions-Ck01cEij.js.map +0 -1
  182. package/dist/log-record-cwFiLyPY.js +0 -17
  183. package/dist/log-record-cwFiLyPY.js.map +0 -1
  184. package/dist/log-record-jX9eWUP8.cjs +0 -2
  185. package/dist/log-record-jX9eWUP8.cjs.map +0 -1
  186. package/dist/long-frames-Bky6nZDF.cjs.map +0 -1
  187. package/dist/long-frames-DDumopji.js.map +0 -1
  188. package/dist/network-BsBZ6_-Q.js.map +0 -1
  189. package/dist/network-_4csBGBM.cjs +0 -2
  190. package/dist/network-_4csBGBM.cjs.map +0 -1
  191. package/dist/platform-4yYjMD-B.js.map +0 -1
  192. package/dist/platform-o7r1ocOu.cjs +0 -2
  193. package/dist/platform-o7r1ocOu.cjs.map +0 -1
  194. package/dist/sampling-C4my-ma0.cjs +0 -2
  195. package/dist/sampling-C4my-ma0.cjs.map +0 -1
  196. package/dist/sampling-nYIWP_vP.js.map +0 -1
  197. package/dist/sender-6vrT9fFL.cjs +0 -3
  198. package/dist/sender-6vrT9fFL.cjs.map +0 -1
  199. package/dist/sender-DFQMF39P.js +0 -1351
  200. package/dist/sender-DFQMF39P.js.map +0 -1
  201. package/dist/storm-6YYbXzT_.cjs +0 -2
  202. package/dist/storm-6YYbXzT_.cjs.map +0 -1
  203. package/dist/storm-CfO0Sam2.js +0 -10
  204. package/dist/storm-CfO0Sam2.js.map +0 -1
  205. package/dist/web-socket-Ar4cZxmd.js +0 -102
  206. package/dist/web-socket-Ar4cZxmd.js.map +0 -1
  207. package/dist/web-socket-BwJdwSHl.cjs +0 -2
  208. package/dist/web-socket-BwJdwSHl.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"journey-Co9OlzrW.cjs","names":["JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BASE64_PLUS_PATTERN","BASE64_SLASH_PATTERN","BASE64_PADDING_PATTERN","BROWSER_STORES","JOURNEY_STORAGE_KEY","newId","JOURNEY_ID_PATTERN","BASE64URL_DASH_PATTERN","BASE64URL_UNDERSCORE_PATTERN","getFin","withDeadline","OPENFIN_OPTIONS_TIMEOUT_MS","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","require_constants","require_sampling","require_identity","require_openfin","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","future","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","requested","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_CLOCK_SKEW_MS,\n JOURNEY_ID_MAX_CHARS,\n JOURNEY_ID_PATTERN,\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 { getFin } from \"../utils/openfin\";\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/**\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 const startedAt = readNumber(value, \"s\");\n // The library always writes a start time. A token without one, or from the future, never expires.\n const future = startedAt !== undefined && startedAt > Date.now() + JOURNEY_CLOCK_SKEW_MS;\n if (id === undefined || name === undefined || startedAt === undefined || future) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\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: this.journeyId(opts.id),\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 /**\n * Gives the id of a new journey. A longer id, or an id with multibyte characters, makes the\n * journey token too long for adoptJourney().\n * @param requested Id from the app, or undefined.\n * @returns The requested id when it matches JOURNEY_ID_PATTERN, else a new id.\n */\n private journeyId(requested: unknown): string {\n if (requested === undefined) {\n return newId(this.diagnostics);\n }\n\n if (typeof requested === \"string\" && JOURNEY_ID_PATTERN.test(requested)) {\n return requested;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `startJourney() needs an id of 1 to ${String(JOURNEY_ID_MAX_CHARS)} letters, digits, \"_\", \".\", \":\" or \"-\". The library uses a new id.`,\n );\n return newId(this.diagnostics);\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 = getFin()?.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":"0JA0CA,IAAamB,EAAkC,CAC7C,SAAUnB,EAAAA,GACV,gBAAA,GACA,SAAUC,EAAAA,EACZ,EAsBA,SAASmB,EAAW,EAAgB,EAAiC,CACnE,IAAMC,EAAiB,QAAQ,IAAIC,EAAQC,CAAG,EAC9C,OA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,EAAA,EAAW2C,CAAK,CAClB,CAGA,aAA4B,CAC1B,KAAK,YAAY,MACf,sBACA,yDACM,CACJ,KAAK,OAAO,QAAQ,CAAC,CAAC,WAAWrD,EAAAA,EAAmB,CACtD,CACF,CACF,CAGA,YAA2B,CACrB,KAAK,cAAgB,OACvB,aAAa,KAAK,WAAW,EAC7B,KAAK,YAAc,KAEvB,CAMA,cAAsC,CAWpC,OAVc,KAAK,YAAY,MAC7B,iBACA,iEAEM,OAAO,SAAa,IACf,KAEF,IAAI,IAAI,SAAS,IAAI,CAAC,CAAC,aAAa,IAAI,KAAK,QAAQ,QAAQ,CAGjE,GAAS,IAClB,CAMA,gBAA+B,CAC7B,KAAK,YAAY,MACf,uBACA,mEACM,CACJ,IAAMsD,EAAM,IAAI,IAAI,SAAS,IAAI,EACjCA,EAAI,aAAa,OAAO,KAAK,QAAQ,QAAQ,EAE7C,QAAQ,aAAa,QAAQ,MAAO,GAAIA,EAAI,IAAI,CAClD,CACF,CACF,CAQA,MAAc,kBAA2C,CACvD,IAAMC,EAAKlD,EAAAA,EAAO,CAAC,EAAE,GACfmD,EAAaD,GAAI,WACvB,GAAIC,IAAe,IAAA,GACjB,OAAO,KAUT,IAAMb,GAAQ,MALQ,KAAK,YAAY,WACrC,sBACA,sDACMrC,EAAAA,EAAakD,EAAW,KAAKD,CAAE,EAAGhD,EAAAA,EAA0B,CACpE,EAAA,EACuB,aAAaC,EAAAA,IACpC,OAAO,OAAOmC,GAAU,SAAWA,EAAQ,IAC7C,CACF"}
1
+ {"version":3,"file":"journey-B_tTnvac.cjs","names":["JOURNEY_MAX_AGE_MS","JOURNEY_URL_PARAM","BASE64_PLUS_PATTERN","BASE64_SLASH_PATTERN","BASE64_PADDING_PATTERN","BROWSER_STORES","JOURNEY_STORAGE_KEY","newId","JOURNEY_ID_PATTERN","BASE64URL_DASH_PATTERN","BASE64URL_UNDERSCORE_PATTERN","getFin","withDeadline","OPENFIN_OPTIONS_TIMEOUT_MS","OPENFIN_JOURNEY_CUSTOM_DATA_KEY","require_constants","require_deadline","require_identity","require_openfin","JOURNEY_OPTIONS","readString","value","source","key","readNumber","parseJourney","id","name","startedAt","journeyFromTokenPayload","future","encodeToken","json","journey","bytes","binary","byte","JourneyEngine","options","diagnostics","contextId","onLocalChange","stores","fromUrl","fromStorage","fromOpenFin","opts","requested","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_CLOCK_SKEW_MS,\n JOURNEY_ID_MAX_CHARS,\n JOURNEY_ID_PATTERN,\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 { getFin } from \"../utils/openfin\";\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/**\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 const startedAt = readNumber(value, \"s\");\n // The library always writes a start time. A token without one, or from the future, never expires.\n const future = startedAt !== undefined && startedAt > Date.now() + JOURNEY_CLOCK_SKEW_MS;\n if (id === undefined || name === undefined || startedAt === undefined || future) {\n return null;\n }\n return {\n id,\n name,\n startedAt,\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: this.journeyId(opts.id),\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 /**\n * Gives the id of a new journey. A longer id, or an id with multibyte characters, makes the\n * journey token too long for adoptJourney().\n * @param requested Id from the app, or undefined.\n * @returns The requested id when it matches JOURNEY_ID_PATTERN, else a new id.\n */\n private journeyId(requested: unknown): string {\n if (requested === undefined) {\n return newId(this.diagnostics);\n }\n\n if (typeof requested === \"string\" && JOURNEY_ID_PATTERN.test(requested)) {\n return requested;\n }\n\n this.diagnostics.report(\n \"config.invalid\",\n `startJourney() needs an id of 1 to ${String(JOURNEY_ID_MAX_CHARS)} letters, digits, \"_\", \".\", \":\" or \"-\". The library uses a new id.`,\n );\n return newId(this.diagnostics);\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 = getFin()?.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":"0JA0CA,IAAamB,EAAkC,CAC7C,SAAUnB,EAAAA,GACV,gBAAA,GACA,SAAUC,EAAAA,EACZ,EAsBA,SAASmB,EAAW,EAAgB,EAAiC,CACnE,IAAMC,EAAiB,QAAQ,IAAIC,EAAQC,CAAG,EAC9C,OAAO,OAAOF,GAAU,UAAYA,IAAU,GAAKA,EAAQ,IAAA,EAC7D,CAQA,SAASG,EAAW,EAAgB,EAAiC,CACnE,IAAMH,EAAiB,QAAQ,IAAIC,EAAQC,CAAG,EAC9C,OAAO,OAAOF,GAAU,UAAY,OAAO,SAASA,CAAK,EAAIA,EAAQ,IAAA,EACvE,CAQA,SAAgBI,EAAa,EAAgC,CAC3D,GAAI,OAAOJ,GAAU,WAAYA,EAC/B,OAAO,KAET,IAAMK,EAAKN,EAAWC,EAAO,IAAI,EAC3BM,EAAOP,EAAWC,EAAO,MAAM,EAC/BO,EAAYJ,EAAWH,EAAO,WAAW,EAI/C,OAHIK,IAAO,IAAA,IAAaC,IAAS,IAAA,IAAaC,IAAc,IAAA,GACnD,KAEF,CACL,KACA,OACA,YACA,SAAUR,EAAWC,EAAO,UAAU,EACtC,eAAgBD,EAAWC,EAAO,gBAAgB,GAAK,EACzD,CACF,CAOA,SAASQ,EAAwB,EAAgC,CAC/D,GAAI,OAAOR,GAAU,WAAYA,EAC/B,OAAO,KAET,IAAMK,EAAKN,EAAWC,EAAO,GAAG,EAC1BM,EAAOP,EAAWC,EAAO,GAAG,EAC5BO,EAAYJ,EAAWH,EAAO,GAAG,EAEjCS,EAASF,IAAc,IAAA,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ACA,sDACMrC,EAAAA,EAAakD,EAAW,KAAKD,CAAE,EAAGhD,EAAAA,EAA0B,CACpE,EAAA,EACuB,aAAaC,EAAAA,IACpC,OAAO,OAAOmC,GAAU,SAAWA,EAAQ,IAC7C,CACF"}
@@ -0,0 +1,2 @@
1
+ function e(e,t){return`${e}${String(t.createdAt).padStart(14,`0`)}.${t.id}`}function t(e,t){let n=[];return t.guard(`storage.unavailable`,`The library could not list the localStorage keys.`,()=>{for(let t=0;t<localStorage.length;t++){let r=String(localStorage.key(t));r.startsWith(e)&&n.push(r)}}),n.sort()}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return e}});
2
+ //# sourceMappingURL=keys-BHhw_0Wh.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys-BHhw_0Wh.cjs","names":["batchKey","prefix","batch","keysWithPrefix","out","diagnostics","i","key"],"sources":["../src/storage/keys.ts"],"sourcesContent":["// src/storage/keys.ts\n//\n// This module builds the localStorage key of a batch. It also returns the sorted keys that start\n// with a prefix. A sandboxed frame and private mode throw on first access. They do not return null.\n\nimport { BATCH_KEY_TIME_WIDTH } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Formats a storage key with a zero-padded creation time. The keys sort in FIFO order. Always use\n * batch.createdAt, never Date.now(). A key from Date.now() does not match the written key.\n * @param prefix Storage key prefix.\n * @param batch Target log batch.\n * @returns Prefixed, timestamp-ordered storage key.\n */\nexport function batchKey(prefix: string, batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${prefix}${at}.${batch.id}`;\n}\n\n/**\n * Returns all localStorage keys that start with the prefix, in sorted order.\n * @param prefix Storage key prefix to filter by.\n * @param diagnostics Diagnostics reporter.\n * @returns Sorted array of matching storage keys.\n */\nexport function keysWithPrefix(prefix: string, diagnostics: Diagnostics): string[] {\n const out: string[] = [];\n\n diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not list the localStorage keys.\",\n () => {\n for (let i = 0; i < localStorage.length; i++) {\n // localStorage.key(i) has the type string | null. It cannot be null below length. A\n // null check here adds a branch that no test can reach.\n const key = String(localStorage.key(i));\n if (key.startsWith(prefix)) {\n out.push(key);\n }\n }\n },\n );\n\n return out.sort();\n}\n"],"mappings":"AAgBA,SAAgBA,EAAS,EAAgB,EAAyB,CAEhE,MAAO,GAAGC,IADC,OAAOC,EAAM,SAAS,CAAC,CAAC,SAAA,GAA+B,GAC/C,EAAG,GAAGA,EAAM,IACjC,CAQA,SAAgBC,EAAe,EAAgB,EAAoC,CACjF,IAAMC,EAAgB,CAAC,EAiBvB,OAfAC,EAAY,MACV,sBACA,wDACM,CACJ,IAAK,IAAIC,EAAI,EAAGA,EAAI,aAAa,OAAQ,IAAK,CAG5C,IAAMC,EAAM,OAAO,aAAa,IAAID,CAAC,CAAC,EAClCC,EAAI,WAAWN,CAAM,GACvBG,EAAI,KAAKG,CAAG,CAEhB,CACF,CACF,EAEOH,EAAI,KAAK,CAClB"}
@@ -0,0 +1,17 @@
1
+ //#region src/storage/keys.ts
2
+ function e(e, t) {
3
+ return `${e}${String(t.createdAt).padStart(14, "0")}.${t.id}`;
4
+ }
5
+ function t(e, t) {
6
+ let n = [];
7
+ return t.guard("storage.unavailable", "The library could not list the localStorage keys.", () => {
8
+ for (let t = 0; t < localStorage.length; t++) {
9
+ let r = String(localStorage.key(t));
10
+ r.startsWith(e) && n.push(r);
11
+ }
12
+ }), n.sort();
13
+ }
14
+ //#endregion
15
+ export { t as n, e as t };
16
+
17
+ //# sourceMappingURL=keys-D5r_GH9q.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keys-D5r_GH9q.js","names":["batchKey","prefix","batch","keysWithPrefix","out","diagnostics","i","key"],"sources":["../src/storage/keys.ts"],"sourcesContent":["// src/storage/keys.ts\n//\n// This module builds the localStorage key of a batch. It also returns the sorted keys that start\n// with a prefix. A sandboxed frame and private mode throw on first access. They do not return null.\n\nimport { BATCH_KEY_TIME_WIDTH } from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { LogBatch } from \"../models/batch\";\n\n/**\n * Formats a storage key with a zero-padded creation time. The keys sort in FIFO order. Always use\n * batch.createdAt, never Date.now(). A key from Date.now() does not match the written key.\n * @param prefix Storage key prefix.\n * @param batch Target log batch.\n * @returns Prefixed, timestamp-ordered storage key.\n */\nexport function batchKey(prefix: string, batch: LogBatch): string {\n const at = String(batch.createdAt).padStart(BATCH_KEY_TIME_WIDTH, \"0\");\n return `${prefix}${at}.${batch.id}`;\n}\n\n/**\n * Returns all localStorage keys that start with the prefix, in sorted order.\n * @param prefix Storage key prefix to filter by.\n * @param diagnostics Diagnostics reporter.\n * @returns Sorted array of matching storage keys.\n */\nexport function keysWithPrefix(prefix: string, diagnostics: Diagnostics): string[] {\n const out: string[] = [];\n\n diagnostics.guard(\n \"storage.unavailable\",\n \"The library could not list the localStorage keys.\",\n () => {\n for (let i = 0; i < localStorage.length; i++) {\n // localStorage.key(i) has the type string | null. It cannot be null below length. A\n // null check here adds a branch that no test can reach.\n const key = String(localStorage.key(i));\n if (key.startsWith(prefix)) {\n out.push(key);\n }\n }\n },\n );\n\n return out.sort();\n}\n"],"mappings":";AAgBA,SAAgBA,EAAS,GAAgB,GAAyB;CAEhE,OAAO,GAAGC,IADC,OAAOC,EAAM,SAAS,CAAC,CAAC,SAAA,IAA+B,GAC/C,EAAG,GAAGA,EAAM;AACjC;AAQA,SAAgBC,EAAe,GAAgB,GAAoC;CACjF,IAAMC,IAAgB,CAAC;CAiBvB,OAfAC,EAAY,MACV,uBACA,2DACM;EACJ,KAAK,IAAIC,IAAI,GAAGA,IAAI,aAAa,QAAQ,KAAK;GAG5C,IAAMC,IAAM,OAAO,aAAa,IAAID,CAAC,CAAC;GACtC,AAAIC,EAAI,WAAWN,CAAM,KACvBG,EAAI,KAAKG,CAAG;EAEhB;CACF,CACF,GAEOH,EAAI,KAAK;AAClB"}
@@ -1,4 +1,4 @@
1
- import { Tn as e, gt as t } from "./constants-L_d5YvvQ.js";
1
+ import { Sn as e, _t as t } from "./constants-CN7GE1Lt.js";
2
2
  import { t as n } from "./global-scope-dp2jADRl.js";
3
3
  //#region src/utils/library-request.ts
4
4
  var r = n(t), i = Symbol.for(e), a = globalThis, o = () => a[i] ?? 0;
@@ -22,4 +22,4 @@ function u() {
22
22
  //#endregion
23
23
  export { l as i, u as n, s as r, c as t };
24
24
 
25
- //# sourceMappingURL=library-request-ChCar5F8.js.map
25
+ //# sourceMappingURL=library-request-BKOcaKtQ.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"library-request-ChCar5F8.js","names":["TRANSPORT_CALL_KEY","LIBRARY_REQUEST_KEY","globalScope","scope","calls","store","pending","runAsLibraryRequest","fn","isLibraryRequest","trackTransportCall","isTransportPending"],"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, TRANSPORT_CALL_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/** Global count of the custom transport calls that wait for an answer. */\nconst calls = Symbol.for(TRANSPORT_CALL_KEY);\nconst store = globalThis as unknown as Record<symbol, number | undefined>;\nconst pending = (): number => store[calls] ?? 0;\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\n/**\n * Runs a custom transport call and counts it until it settles. The count includes the time after\n * each await, which the library request scope does not cover.\n * @param fn Function that calls the custom transport.\n * @returns Promise that settles with the result of the call.\n */\nexport async function trackTransportCall<T>(fn: () => T | PromiseLike<T>): Promise<T> {\n store[calls] = pending() + 1;\n\n try {\n return await fn();\n } finally {\n store[calls] = pending() - 1;\n }\n}\n\n/**\n * Tests if a custom transport call waits for an answer.\n * @returns True while a call has not settled.\n */\nexport function isTransportPending(): boolean {\n return pending() > 0;\n}\n"],"mappings":";;;AAUA,IAAMG,IAAQD,EAAYD,CAAmB,GAGvCG,IAAQ,OAAO,IAAIJ,CAAkB,GACrCK,IAAQ,YACRC,UAAwBD,EAAMD,MAAU;AAQ9C,SAAgBG,EAAuB,GAAgB;CACrD,OAAOJ,EAAM,IAAIK,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAON,EAAM,KAAK;AACpB;AAQA,eAAsBO,EAAsB,GAA0C;CACpF,EAAMN,KAASE,EAAQ,IAAI;CAE3B,IAAI;EACF,OAAO,MAAME,EAAG;CAClB,UAAU;EACR,EAAMJ,KAASE,EAAQ,IAAI;CAC7B;AACF;AAMA,SAAgBK,IAA8B;CAC5C,OAAOL,EAAQ,IAAI;AACrB"}
1
+ {"version":3,"file":"library-request-BKOcaKtQ.js","names":["TRANSPORT_CALL_KEY","LIBRARY_REQUEST_KEY","globalScope","scope","calls","store","pending","runAsLibraryRequest","fn","isLibraryRequest","trackTransportCall","isTransportPending"],"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, TRANSPORT_CALL_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/** Global count of the custom transport calls that wait for an answer. */\nconst calls = Symbol.for(TRANSPORT_CALL_KEY);\nconst store = globalThis as unknown as Record<symbol, number | undefined>;\nconst pending = (): number => store[calls] ?? 0;\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\n/**\n * Runs a custom transport call and counts it until it settles. The count includes the time after\n * each await, which the library request scope does not cover.\n * @param fn Function that calls the custom transport.\n * @returns Promise that settles with the result of the call.\n */\nexport async function trackTransportCall<T>(fn: () => T | PromiseLike<T>): Promise<T> {\n store[calls] = pending() + 1;\n\n try {\n return await fn();\n } finally {\n store[calls] = pending() - 1;\n }\n}\n\n/**\n * Tests if a custom transport call waits for an answer.\n * @returns True while a call has not settled.\n */\nexport function isTransportPending(): boolean {\n return pending() > 0;\n}\n"],"mappings":";;;AAUA,IAAMG,IAAQD,EAAYD,CAAmB,GAGvCG,IAAQ,OAAO,IAAIJ,CAAkB,GACrCK,IAAQ,YACRC,UAAwBD,EAAMD,MAAU;AAQ9C,SAAgBG,EAAuB,GAAgB;CACrD,OAAOJ,EAAM,IAAIK,CAAE;AACrB;AAMA,SAAgBC,IAA4B;CAC1C,OAAON,EAAM,KAAK;AACpB;AAQA,eAAsBO,EAAsB,GAA0C;CACpF,EAAMN,KAASE,EAAQ,IAAI;CAE3B,IAAI;EACF,OAAO,MAAME,EAAG;CAClB,UAAU;EACR,EAAMJ,KAASE,EAAQ,IAAI;CAC7B;AACF;AAMA,SAAgBK,IAA8B;CAC5C,OAAOL,EAAQ,IAAI;AACrB"}
@@ -1,2 +1,2 @@
1
- const e=require("./constants-BgRS6MB0.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e.gt),n=Symbol.for(e.Tn),r=globalThis,i=()=>r[n]??0;function a(e){return t.run(e)}function o(){return t.open()}async function s(e){r[n]=i()+1;try{return await e()}finally{r[n]=i()-1}}function c(){return i()>0}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
2
- //# sourceMappingURL=library-request-gMFOCNcn.cjs.map
1
+ const e=require("./constants-CW-MlHdY.cjs");var t=require("./global-scope-BN-Io_yv.cjs").t(e._t),n=Symbol.for(e.Sn),r=globalThis,i=()=>r[n]??0;function a(e){return t.run(e)}function o(){return t.open()}async function s(e){r[n]=i()+1;try{return await e()}finally{r[n]=i()-1}}function c(){return i()>0}Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
2
+ //# sourceMappingURL=library-request-BaZOi4eg.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"library-request-gMFOCNcn.cjs","names":["globalScope","LIBRARY_REQUEST_KEY","TRANSPORT_CALL_KEY","require_constants","scope","calls","store","pending","runAsLibraryRequest","fn","isLibraryRequest","trackTransportCall","isTransportPending"],"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, TRANSPORT_CALL_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/** Global count of the custom transport calls that wait for an answer. */\nconst calls = Symbol.for(TRANSPORT_CALL_KEY);\nconst store = globalThis as unknown as Record<symbol, number | undefined>;\nconst pending = (): number => store[calls] ?? 0;\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\n/**\n * Runs a custom transport call and counts it until it settles. The count includes the time after\n * each await, which the library request scope does not cover.\n * @param fn Function that calls the custom transport.\n * @returns Promise that settles with the result of the call.\n */\nexport async function trackTransportCall<T>(fn: () => T | PromiseLike<T>): Promise<T> {\n store[calls] = pending() + 1;\n\n try {\n return await fn();\n } finally {\n store[calls] = pending() - 1;\n }\n}\n\n/**\n * Tests if a custom transport call waits for an answer.\n * @returns True while a call has not settled.\n */\nexport function isTransportPending(): boolean {\n return pending() > 0;\n}\n"],"mappings":"4CAUA,IAAMI,uCAAQJ,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAGvCI,EAAQ,OAAO,IAAIH,EAAAA,EAAkB,EACrCI,EAAQ,WACRC,MAAwBD,EAAMD,IAAU,EAQ9C,SAAgBG,EAAuB,EAAgB,CACrD,OAAOJ,EAAM,IAAIK,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAON,EAAM,KAAK,CACpB,CAQA,eAAsBO,EAAsB,EAA0C,CACpF,EAAMN,GAASE,EAAQ,EAAI,EAE3B,GAAI,CACF,OAAO,MAAME,EAAG,CAClB,QAAU,CACR,EAAMJ,GAASE,EAAQ,EAAI,CAC7B,CACF,CAMA,SAAgBK,GAA8B,CAC5C,OAAOL,EAAQ,EAAI,CACrB"}
1
+ {"version":3,"file":"library-request-BaZOi4eg.cjs","names":["globalScope","LIBRARY_REQUEST_KEY","TRANSPORT_CALL_KEY","require_constants","scope","calls","store","pending","runAsLibraryRequest","fn","isLibraryRequest","trackTransportCall","isTransportPending"],"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, TRANSPORT_CALL_KEY } from \"../constants\";\nimport { globalScope } from \"./global-scope\";\n\n/** Scope of the library requests. */\nconst scope = globalScope(LIBRARY_REQUEST_KEY);\n\n/** Global count of the custom transport calls that wait for an answer. */\nconst calls = Symbol.for(TRANSPORT_CALL_KEY);\nconst store = globalThis as unknown as Record<symbol, number | undefined>;\nconst pending = (): number => store[calls] ?? 0;\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\n/**\n * Runs a custom transport call and counts it until it settles. The count includes the time after\n * each await, which the library request scope does not cover.\n * @param fn Function that calls the custom transport.\n * @returns Promise that settles with the result of the call.\n */\nexport async function trackTransportCall<T>(fn: () => T | PromiseLike<T>): Promise<T> {\n store[calls] = pending() + 1;\n\n try {\n return await fn();\n } finally {\n store[calls] = pending() - 1;\n }\n}\n\n/**\n * Tests if a custom transport call waits for an answer.\n * @returns True while a call has not settled.\n */\nexport function isTransportPending(): boolean {\n return pending() > 0;\n}\n"],"mappings":"4CAUA,IAAMI,uCAAQJ,CAAAA,CAAAA,EAAYC,EAAAA,EAAmB,EAGvCI,EAAQ,OAAO,IAAIH,EAAAA,EAAkB,EACrCI,EAAQ,WACRC,MAAwBD,EAAMD,IAAU,EAQ9C,SAAgBG,EAAuB,EAAgB,CACrD,OAAOJ,EAAM,IAAIK,CAAE,CACrB,CAMA,SAAgBC,GAA4B,CAC1C,OAAON,EAAM,KAAK,CACpB,CAQA,eAAsBO,EAAsB,EAA0C,CACpF,EAAMN,GAASE,EAAQ,EAAI,EAE3B,GAAI,CACF,OAAO,MAAME,EAAG,CAClB,QAAU,CACR,EAAMJ,GAASE,EAAQ,EAAI,CAC7B,CACF,CAMA,SAAgBK,GAA8B,CAC5C,OAAOL,EAAQ,EAAI,CACrB"}
@@ -1,2 +1,2 @@
1
- const e=require("./platform-o7r1ocOu.cjs"),t=require("./storm-6YYbXzT_.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=>e.i(t,this.ctx.config.capture.fullUrls);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-Bky6nZDF.cjs.map
1
+ const e=require("./platform-DBSKTvFn.cjs"),t=require("./storm-CNZjsw4T.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,this.ctx.config.capturePolicy.longFramesPerWindow,i,`long frames`,this.ctx.config.capturePolicy.windowMs))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=>e.i(t,this.ctx.config.capture.fullUrls,this.ctx.config.capture.urlTransform,i);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-CF3qiSAX.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"long-frames-CF3qiSAX.cjs","names":["allowInWindow","recordedUrl","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_THRESHOLD_MS } from \"../constants\";\nimport { recordedUrl } 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 (\n !allowInWindow(\n this.window,\n this.ctx.config.capturePolicy.longFramesPerWindow,\n diagnostics,\n \"long frames\",\n this.ctx.config.capturePolicy.windowMs,\n )\n ) {\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 recordedUrl(\n value,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n diagnostics,\n );\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,GAAI,KAAK,SACP,OAKF,G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B,KAAK,IAAI,OAAO,QAAQ,aACxBC,CACF,EAEF,GAAIZ,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 { i as e } from "./platform-4yYjMD-B.js";
2
- import { t } from "./storm-CfO0Sam2.js";
1
+ import { i as e } from "./platform-Bw1btWCT.js";
2
+ import { t } from "./storm-Daq2jGHU.js";
3
3
  //#region src/capture/long-frames.ts
4
4
  var n = ["long-animation-frame", "longtask"];
5
5
  function r(e) {
@@ -44,10 +44,10 @@ var i = class {
44
44
  record(n) {
45
45
  if (n.duration < this.threshold) return;
46
46
  let { diagnostics: i } = this.ctx;
47
- if (!t(this.window, 20, i, "long frames")) return;
47
+ if (!t(this.window, this.ctx.config.capturePolicy.longFramesPerWindow, i, "long frames", this.ctx.config.capturePolicy.windowMs)) return;
48
48
  let a = Math.round(n.duration), o = { "frame.type": n.entryType };
49
49
  n.blockingDuration !== void 0 && (o["frame.blocking_ms"] = Math.round(n.blockingDuration));
50
- let s = r(n.scripts), c = (t) => e(t, this.ctx.config.capture.fullUrls);
50
+ let s = r(n.scripts), c = (t) => e(t, this.ctx.config.capture.fullUrls, this.ctx.config.capture.urlTransform, i);
51
51
  if (s?.invoker) {
52
52
  let { invoker: e } = s;
53
53
  o["frame.script.invoker"] = e.includes("://") ? c(e) : e;
@@ -62,4 +62,4 @@ var i = class {
62
62
  //#endregion
63
63
  export { i as LongFrameCapture };
64
64
 
65
- //# sourceMappingURL=long-frames-DDumopji.js.map
65
+ //# sourceMappingURL=long-frames-DI5ypfAF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"long-frames-DI5ypfAF.js","names":["recordedUrl","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_THRESHOLD_MS } from \"../constants\";\nimport { recordedUrl } 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 (\n !allowInWindow(\n this.window,\n this.ctx.config.capturePolicy.longFramesPerWindow,\n diagnostics,\n \"long frames\",\n this.ctx.config.capturePolicy.windowMs,\n )\n ) {\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 recordedUrl(\n value,\n this.ctx.config.capture.fullUrls,\n this.ctx.config.capture.urlTransform,\n diagnostics,\n );\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,KA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AAQ,cACxBE,CACF;EAEF,IAAIb,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"}
@@ -5,6 +5,10 @@ import type { LogRecord } from "./log-record";
5
5
  * @see {@link splitBatch}
6
6
  */
7
7
  export interface LogBatch {
8
+ /** Application namespace that owns this stored batch. */
9
+ readonly persistenceNamespace?: string;
10
+ /** Delivery context id. It does not change. With isolation, a batch without this id stays stored. */
11
+ readonly routingContextId?: string;
8
12
  /** Deduplication key. It stays the same across retries and reloads. */
9
13
  id: string;
10
14
  /** Records to deliver, in log order. */
@@ -1,5 +1,16 @@
1
- import { BUS_PROTOCOL } from "../constants";
1
+ import { BUS_PROTOCOL, type BUS_TYPE } from "../constants";
2
2
  import type { LogRecord } from "./log-record";
3
+ /** Permissions of one child window or worker. The handshake needs no separate permission. */
4
+ export type BusPermission = "records" | "journey:read" | "journey:write" | "sampling:read";
5
+ export interface SourceOptions {
6
+ /** Permissions of this source. Without this list, the source can send records only. */
7
+ permissions?: BusPermission[];
8
+ }
9
+ /** Origin and permissions for one child frame registration. */
10
+ export interface FrameOptions extends SourceOptions {
11
+ /** Expected window origin, with its scheme and port. The origin must match exactly. */
12
+ origin: string;
13
+ }
3
14
  /** Delivery role. It tells if this context sends its records or forwards them upstream. */
4
15
  export type BusRole = "sender" | "forwarder";
5
16
  /**
@@ -24,16 +35,20 @@ export type LinkKind =
24
35
  | "worker";
25
36
  /** Origin and transport metadata for an incoming bus message. */
26
37
  export interface MessageSource {
38
+ /** Source identity from the transport. The source does not supply it in message.from. */
39
+ peer?: object | string;
27
40
  /** Inbound transport channel kind. */
28
41
  link: LinkKind;
29
42
  /** `event.origin` for `parent` and `children`. Other links use `"same-origin"` or `"openfin"`. */
30
43
  origin: string;
44
+ /** Sends an answer to this source only. A link that cannot address one source omits it. */
45
+ reply?: (message: BusMessage) => void;
31
46
  }
32
47
  /** Discriminated union of control and telemetry payload messages. */
33
48
  export type BusMessage =
34
49
  /** Handshake discovery announcement from a starting forwarder. */
35
50
  {
36
- t: "hello";
51
+ t: typeof BUS_TYPE.hello;
37
52
  from: string;
38
53
  tabId: string;
39
54
  }
@@ -43,41 +58,49 @@ export type BusMessage =
43
58
  * each waiting view accepts the welcome as its own.
44
59
  */
45
60
  | {
46
- t: "welcome";
61
+ t: typeof BUS_TYPE.welcome;
47
62
  from: string;
48
63
  to: string;
49
64
  tabId: string;
65
+ routingContextId?: string;
50
66
  }
51
67
  /** Telemetry log records forwarded to an upstream sender. */
52
68
  | {
53
- t: "records";
69
+ t: typeof BUS_TYPE.records;
54
70
  from: string;
55
71
  records: LogRecord[];
72
+ routingContextId?: string;
73
+ }
74
+ /** Delivery context update. Only the owner from the handshake can send it to its children. */
75
+ | {
76
+ t: typeof BUS_TYPE.securityContext;
77
+ from: string;
78
+ id: string;
56
79
  }
57
80
  /**
58
81
  * Journey update, or the answer to a journey question. An answer holds the address of the
59
82
  * context that asked in `to`. The payload comes from another realm. The receiver parses it.
60
83
  */
61
84
  | {
62
- t: "journey";
85
+ t: typeof BUS_TYPE.journey;
63
86
  from: string;
64
87
  to?: string;
65
88
  journey: unknown;
66
89
  }
67
90
  /** Query requesting active journey state from connected peers. */
68
91
  | {
69
- t: "journey?";
92
+ t: typeof BUS_TYPE.journeyRequest;
70
93
  from: string;
71
94
  }
72
95
  /** Tab identifier claim broadcast to detect collisions across windows. */
73
96
  | {
74
- t: "tab";
97
+ t: typeof BUS_TYPE.tab;
75
98
  from: string;
76
99
  tabId: string;
77
100
  }
78
101
  /** Request of a forwarder for the remote sampling rules in force. */
79
102
  | {
80
- t: "sampling?";
103
+ t: typeof BUS_TYPE.samplingRequest;
81
104
  from: string;
82
105
  }
83
106
  /**
@@ -86,7 +109,7 @@ export type BusMessage =
86
109
  * Null rules end the copy of the forwarder.
87
110
  */
88
111
  | {
89
- t: "sampling";
112
+ t: typeof BUS_TYPE.sampling;
90
113
  from: string;
91
114
  to: string;
92
115
  rules: unknown;