@utk09/ui-observability 1.0.0 → 1.1.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 (221) hide show
  1. package/CHANGELOG.md +69 -219
  2. package/README.md +24 -26
  3. package/dist/{batch-CXmPmTse.js → batch-D3NHhF9L.js} +3 -3
  4. package/dist/{batch-CXmPmTse.js.map → batch-D3NHhF9L.js.map} +1 -1
  5. package/dist/{batch-mmPigCpi.cjs → batch-DnYRJqhU.cjs} +2 -2
  6. package/dist/{batch-mmPigCpi.cjs.map → batch-DnYRJqhU.cjs.map} +1 -1
  7. package/dist/bus/bus.d.cts +26 -2
  8. package/dist/bus/bus.d.ts +26 -2
  9. package/dist/bus-B__467mL.cjs +2 -0
  10. package/dist/bus-B__467mL.cjs.map +1 -0
  11. package/dist/{bus-C39wspFV.js → bus-dw7T92sO.js} +37 -24
  12. package/dist/bus-dw7T92sO.js.map +1 -0
  13. package/dist/capture/interactions.d.cts +35 -3
  14. package/dist/capture/interactions.d.ts +35 -3
  15. package/dist/capture/observed-windows.d.cts +51 -0
  16. package/dist/capture/observed-windows.d.ts +51 -0
  17. package/dist/{compression-CvED_Jel.cjs → compression-C0hUHKR-.cjs} +2 -2
  18. package/dist/{compression-CvED_Jel.cjs.map → compression-C0hUHKR-.cjs.map} +1 -1
  19. package/dist/{compression-tVtXwVjX.js → compression-SHPAvS4U.js} +2 -2
  20. package/dist/{compression-tVtXwVjX.js.map → compression-SHPAvS4U.js.map} +1 -1
  21. package/dist/{config-SgQcCP1_.js → config-CSNcS7OZ.js} +194 -196
  22. package/dist/config-CSNcS7OZ.js.map +1 -0
  23. package/dist/config-CybPP5VM.cjs +2 -0
  24. package/dist/config-CybPP5VM.cjs.map +1 -0
  25. package/dist/{console-BGgGnjSi.js → console-BsM-fSCQ.js} +4 -4
  26. package/dist/{console-BGgGnjSi.js.map → console-BsM-fSCQ.js.map} +1 -1
  27. package/dist/{console-CSZ5_Vx5.cjs → console-Dkxs6IVQ.cjs} +2 -2
  28. package/dist/{console-CSZ5_Vx5.cjs.map → console-Dkxs6IVQ.cjs.map} +1 -1
  29. package/dist/{constants-CUyd9cTZ.js → constants-BwJDXzj6.js} +23 -23
  30. package/dist/constants-BwJDXzj6.js.map +1 -0
  31. package/dist/constants-CtF52hIV.cjs +2 -0
  32. package/dist/constants-CtF52hIV.cjs.map +1 -0
  33. package/dist/constants.d.cts +12 -0
  34. package/dist/constants.d.ts +12 -0
  35. package/dist/core/diagnostics.d.cts +1 -1
  36. package/dist/core/diagnostics.d.ts +1 -1
  37. package/dist/core/rotation.d.cts +26 -2
  38. package/dist/core/rotation.d.ts +26 -2
  39. package/dist/core/runtime.d.cts +9 -0
  40. package/dist/core/runtime.d.ts +9 -0
  41. package/dist/{debug-bundle-BXIlwDKM.cjs → debug-bundle-B2v6Cym-.cjs} +2 -2
  42. package/dist/{debug-bundle-BXIlwDKM.cjs.map → debug-bundle-B2v6Cym-.cjs.map} +1 -1
  43. package/dist/{debug-bundle-CRpYV_ui.js → debug-bundle-Cs_YWzTa.js} +4 -4
  44. package/dist/{debug-bundle-CRpYV_ui.js.map → debug-bundle-Cs_YWzTa.js.map} +1 -1
  45. package/dist/doctor.cjs +1 -1
  46. package/dist/doctor.js +31 -31
  47. package/dist/doctor.js.map +1 -1
  48. package/dist/{errors-CNPbesMs.cjs → errors-DP2RUm4V.cjs} +2 -2
  49. package/dist/{errors-CNPbesMs.cjs.map → errors-DP2RUm4V.cjs.map} +1 -1
  50. package/dist/{errors-BE_EZV7Q.js → errors-Q3Ng1ciC.js} +3 -3
  51. package/dist/{errors-BE_EZV7Q.js.map → errors-Q3Ng1ciC.js.map} +1 -1
  52. package/dist/{factory-CTi0Is3F.js → factory-DV17sm2p.js} +22 -22
  53. package/dist/{factory-CTi0Is3F.js.map → factory-DV17sm2p.js.map} +1 -1
  54. package/dist/{factory-hRrH32v5.cjs → factory-K8O6gpux.cjs} +2 -2
  55. package/dist/{factory-hRrH32v5.cjs.map → factory-K8O6gpux.cjs.map} +1 -1
  56. package/dist/{identity-DdhKgrpk.js → identity-BgtHyY4u.js} +38 -27
  57. package/dist/identity-BgtHyY4u.js.map +1 -0
  58. package/dist/identity-CvuyqZk7.cjs +2 -0
  59. package/dist/identity-CvuyqZk7.cjs.map +1 -0
  60. package/dist/index.cjs +1 -1
  61. package/dist/index.cjs.map +1 -1
  62. package/dist/index.d.cts +1 -0
  63. package/dist/index.d.ts +1 -0
  64. package/dist/index.js +600 -569
  65. package/dist/index.js.map +1 -1
  66. package/dist/{indexeddb-storage-CL9uqBCy.cjs → indexeddb-storage-D4KVcqdD.cjs} +2 -2
  67. package/dist/{indexeddb-storage-CL9uqBCy.cjs.map → indexeddb-storage-D4KVcqdD.cjs.map} +1 -1
  68. package/dist/{indexeddb-storage-GHdl0t8A.js → indexeddb-storage-e-13ZLWm.js} +17 -17
  69. package/dist/{indexeddb-storage-GHdl0t8A.js.map → indexeddb-storage-e-13ZLWm.js.map} +1 -1
  70. package/dist/interactions-Byxf1C82.js +207 -0
  71. package/dist/interactions-Byxf1C82.js.map +1 -0
  72. package/dist/interactions-OK85T-Dk.cjs +2 -0
  73. package/dist/interactions-OK85T-Dk.cjs.map +1 -0
  74. package/dist/{journey-D2_sia57.js → journey-C93FTYcs.js} +14 -14
  75. package/dist/{journey-D2_sia57.js.map → journey-C93FTYcs.js.map} +1 -1
  76. package/dist/{journey-B4Adltjm.cjs → journey-nMbob3OB.cjs} +2 -2
  77. package/dist/{journey-B4Adltjm.cjs.map → journey-nMbob3OB.cjs.map} +1 -1
  78. package/dist/{library-console-CPW6bvZH.cjs → library-console-DJUQzcgM.cjs} +2 -2
  79. package/dist/{library-console-CPW6bvZH.cjs.map → library-console-DJUQzcgM.cjs.map} +1 -1
  80. package/dist/{library-console-Btrzt814.js → library-console-DklSmucS.js} +2 -2
  81. package/dist/{library-console-Btrzt814.js.map → library-console-DklSmucS.js.map} +1 -1
  82. package/dist/{library-request-BJ9PLRaD.js → library-request-UGEwOHpf.js} +2 -2
  83. package/dist/{library-request-BJ9PLRaD.js.map → library-request-UGEwOHpf.js.map} +1 -1
  84. package/dist/{library-request-D7OvTxZV.cjs → library-request-kY9iTpIF.cjs} +2 -2
  85. package/dist/{library-request-D7OvTxZV.cjs.map → library-request-kY9iTpIF.cjs.map} +1 -1
  86. package/dist/{lifecycle-22CUCrc9.js → lifecycle-B2PlIuQu.js} +2 -2
  87. package/dist/{lifecycle-22CUCrc9.js.map → lifecycle-B2PlIuQu.js.map} +1 -1
  88. package/dist/{lifecycle-IaAm1mOC.cjs → lifecycle-DaMdH_X7.cjs} +2 -2
  89. package/dist/{lifecycle-IaAm1mOC.cjs.map → lifecycle-DaMdH_X7.cjs.map} +1 -1
  90. package/dist/{log-record-CkivuiEl.cjs → log-record-Bmx6etMh.cjs} +2 -2
  91. package/dist/{log-record-CkivuiEl.cjs.map → log-record-Bmx6etMh.cjs.map} +1 -1
  92. package/dist/{log-record-BNiLfqtL.js → log-record-DSt2P-Sr.js} +2 -2
  93. package/dist/{log-record-BNiLfqtL.js.map → log-record-DSt2P-Sr.js.map} +1 -1
  94. package/dist/{long-frames-DNFaRnC3.js → long-frames-Bamjs1WV.js} +3 -3
  95. package/dist/{long-frames-DNFaRnC3.js.map → long-frames-Bamjs1WV.js.map} +1 -1
  96. package/dist/{long-frames-BUUbXd-B.cjs → long-frames-lhtONgGt.cjs} +2 -2
  97. package/dist/{long-frames-BUUbXd-B.cjs.map → long-frames-lhtONgGt.cjs.map} +1 -1
  98. package/dist/models/bus.d.cts +6 -1
  99. package/dist/models/bus.d.ts +6 -1
  100. package/dist/models/config.d.cts +23 -8
  101. package/dist/models/config.d.ts +23 -8
  102. package/dist/models/serializer.d.cts +3 -1
  103. package/dist/models/serializer.d.ts +3 -1
  104. package/dist/{network-CGMLQ-mA.cjs → network-BCn8Gn47.cjs} +2 -2
  105. package/dist/{network-CGMLQ-mA.cjs.map → network-BCn8Gn47.cjs.map} +1 -1
  106. package/dist/{network-on2zZT6H.js → network-Cg1L2w2r.js} +12 -12
  107. package/dist/{network-on2zZT6H.js.map → network-Cg1L2w2r.js.map} +1 -1
  108. package/dist/observed-windows-B3gJkdql.cjs +2 -0
  109. package/dist/observed-windows-B3gJkdql.cjs.map +1 -0
  110. package/dist/observed-windows-BrwaJNlj.js +64 -0
  111. package/dist/observed-windows-BrwaJNlj.js.map +1 -0
  112. package/dist/{otlp-BENHf3g9.cjs → otlp-CrAWkQdO.cjs} +2 -2
  113. package/dist/{otlp-BENHf3g9.cjs.map → otlp-CrAWkQdO.cjs.map} +1 -1
  114. package/dist/{otlp-DimfrRor.js → otlp-D6dRZyB8.js} +6 -6
  115. package/dist/{otlp-DimfrRor.js.map → otlp-D6dRZyB8.js.map} +1 -1
  116. package/dist/{platform-BaaFIPCU.js → platform-8DLhjddo.js} +7 -7
  117. package/dist/{platform-BaaFIPCU.js.map → platform-8DLhjddo.js.map} +1 -1
  118. package/dist/{platform-CfA3-7sJ.cjs → platform-BqRc-7RO.cjs} +2 -2
  119. package/dist/{platform-CfA3-7sJ.cjs.map → platform-BqRc-7RO.cjs.map} +1 -1
  120. package/dist/{profiler-BAZoh7A4.js → profiler-BaXSqCfz.js} +59 -59
  121. package/dist/{profiler-BAZoh7A4.js.map → profiler-BaXSqCfz.js.map} +1 -1
  122. package/dist/{profiler-D4tJpDRc.cjs → profiler-BvWW2kNM.cjs} +2 -2
  123. package/dist/{profiler-D4tJpDRc.cjs.map → profiler-BvWW2kNM.cjs.map} +1 -1
  124. package/dist/{profiler-frames-cJMx9wNM.js → profiler-frames-C4ySHN0X.js} +16 -16
  125. package/dist/{profiler-frames-cJMx9wNM.js.map → profiler-frames-C4ySHN0X.js.map} +1 -1
  126. package/dist/{profiler-frames-C4xr7KfH.cjs → profiler-frames-DeaBiB-5.cjs} +2 -2
  127. package/dist/{profiler-frames-C4xr7KfH.cjs.map → profiler-frames-DeaBiB-5.cjs.map} +1 -1
  128. package/dist/{remote-rules-_tY0zj5o.cjs → remote-rules-D7L6D_D2.cjs} +2 -2
  129. package/dist/{remote-rules-_tY0zj5o.cjs.map → remote-rules-D7L6D_D2.cjs.map} +1 -1
  130. package/dist/{remote-rules-Dz9MRAsB.js → remote-rules-Dq9xe7Qn.js} +22 -22
  131. package/dist/{remote-rules-Dz9MRAsB.js.map → remote-rules-Dq9xe7Qn.js.map} +1 -1
  132. package/dist/{replay-Ds-ANH34.js → replay-B0M8kWz_.js} +24 -24
  133. package/dist/{replay-Ds-ANH34.js.map → replay-B0M8kWz_.js.map} +1 -1
  134. package/dist/{replay-B3gFXIZd.cjs → replay-QOFBpAXh.cjs} +2 -2
  135. package/dist/{replay-B3gFXIZd.cjs.map → replay-QOFBpAXh.cjs.map} +1 -1
  136. package/dist/{reports-C-thq-bk.js → reports--8APRLa-.js} +3 -3
  137. package/dist/{reports-C-thq-bk.js.map → reports--8APRLa-.js.map} +1 -1
  138. package/dist/{reports-BDSe4dFH.cjs → reports-ojuMKGO7.cjs} +2 -2
  139. package/dist/{reports-BDSe4dFH.cjs.map → reports-ojuMKGO7.cjs.map} +1 -1
  140. package/dist/{resource-timing-eUl2dNgC.js → resource-timing-BzR05rE-.js} +4 -4
  141. package/dist/{resource-timing-eUl2dNgC.js.map → resource-timing-BzR05rE-.js.map} +1 -1
  142. package/dist/{resource-timing-C576gFIQ.cjs → resource-timing-pAG3ZhB5.cjs} +2 -2
  143. package/dist/{resource-timing-C576gFIQ.cjs.map → resource-timing-pAG3ZhB5.cjs.map} +1 -1
  144. package/dist/{response-body-eoSQpLiH.js → response-body-BWvwKQ2p.js} +106 -106
  145. package/dist/{response-body-eoSQpLiH.js.map → response-body-BWvwKQ2p.js.map} +1 -1
  146. package/dist/{response-body-YdNl-HkR.cjs → response-body-CKEJ5itk.cjs} +3 -3
  147. package/dist/{response-body-YdNl-HkR.cjs.map → response-body-CKEJ5itk.cjs.map} +1 -1
  148. package/dist/{rotation-Cwct4ckk.js → rotation-BylN1B9e.js} +10 -11
  149. package/dist/rotation-BylN1B9e.js.map +1 -0
  150. package/dist/rotation-E2eKClIs.cjs +2 -0
  151. package/dist/rotation-E2eKClIs.cjs.map +1 -0
  152. package/dist/{sampling-mXt4dstx.cjs → sampling-B46LW0cy.cjs} +2 -2
  153. package/dist/{sampling-mXt4dstx.cjs.map → sampling-B46LW0cy.cjs.map} +1 -1
  154. package/dist/{sampling-BlrI8jor.js → sampling-zXA6r-Nw.js} +16 -16
  155. package/dist/{sampling-BlrI8jor.js.map → sampling-zXA6r-Nw.js.map} +1 -1
  156. package/dist/{sanitize-Ba0KqU06.js → sanitize-DjnR6RXR.js} +2 -2
  157. package/dist/{sanitize-Ba0KqU06.js.map → sanitize-DjnR6RXR.js.map} +1 -1
  158. package/dist/{sanitize-DQyiI_KY.cjs → sanitize-Qj6LuZqp.cjs} +2 -2
  159. package/dist/{sanitize-DQyiI_KY.cjs.map → sanitize-Qj6LuZqp.cjs.map} +1 -1
  160. package/dist/{sender-Dv8rAmpV.js → sender-Bdp-TAS4.js} +71 -71
  161. package/dist/{sender-Dv8rAmpV.js.map → sender-Bdp-TAS4.js.map} +1 -1
  162. package/dist/{sender-BdRuNVhF.cjs → sender-DR7ZycZY.cjs} +2 -2
  163. package/dist/{sender-BdRuNVhF.cjs.map → sender-DR7ZycZY.cjs.map} +1 -1
  164. package/dist/{stored-context-CXt7eHZL.cjs → stored-context-BOu54M8Y.cjs} +2 -2
  165. package/dist/{stored-context-CXt7eHZL.cjs.map → stored-context-BOu54M8Y.cjs.map} +1 -1
  166. package/dist/{stored-context-B2EzVuYm.js → stored-context-CSttrAsw.js} +6 -6
  167. package/dist/{stored-context-B2EzVuYm.js.map → stored-context-CSttrAsw.js.map} +1 -1
  168. package/dist/{storm-C-zYSdDX.cjs → storm-BHgI12iS.cjs} +2 -2
  169. package/dist/{storm-C-zYSdDX.cjs.map → storm-BHgI12iS.cjs.map} +1 -1
  170. package/dist/{storm-DjKetLKZ.js → storm-DKlpv0FL.js} +2 -2
  171. package/dist/{storm-DjKetLKZ.js.map → storm-DKlpv0FL.js.map} +1 -1
  172. package/dist/{unclean-exit-py99ApzT.cjs → unclean-exit-BYPYYkQ5.cjs} +2 -2
  173. package/dist/{unclean-exit-py99ApzT.cjs.map → unclean-exit-BYPYYkQ5.cjs.map} +1 -1
  174. package/dist/{unclean-exit-DQD1cT7c.js → unclean-exit-BcOB8A2e.js} +2 -2
  175. package/dist/{unclean-exit-DQD1cT7c.js.map → unclean-exit-BcOB8A2e.js.map} +1 -1
  176. package/dist/{user-timing-BePqb1uN.js → user-timing-4KIJ74Vi.js} +2 -2
  177. package/dist/{user-timing-BePqb1uN.js.map → user-timing-4KIJ74Vi.js.map} +1 -1
  178. package/dist/{user-timing-D6XTmpuM.cjs → user-timing-BsU2wQKE.cjs} +2 -2
  179. package/dist/{user-timing-D6XTmpuM.cjs.map → user-timing-BsU2wQKE.cjs.map} +1 -1
  180. package/dist/utils/identity.d.cts +5 -0
  181. package/dist/utils/identity.d.ts +5 -0
  182. package/dist/{web-socket-CoIUBM3C.cjs → web-socket-Cs1ZbmmN.cjs} +2 -2
  183. package/dist/{web-socket-CoIUBM3C.cjs.map → web-socket-Cs1ZbmmN.cjs.map} +1 -1
  184. package/dist/{web-socket-DSHgDiZ6.js → web-socket-Zg0hj1LB.js} +4 -4
  185. package/dist/{web-socket-DSHgDiZ6.js.map → web-socket-Zg0hj1LB.js.map} +1 -1
  186. package/dist/{worker-protocol-x074Rpet.js → worker-protocol-CYpAbrVl.js} +4 -4
  187. package/dist/{worker-protocol-x074Rpet.js.map → worker-protocol-CYpAbrVl.js.map} +1 -1
  188. package/dist/{worker-protocol-QbvqNazn.cjs → worker-protocol-DFYXIFus.cjs} +2 -2
  189. package/dist/{worker-protocol-QbvqNazn.cjs.map → worker-protocol-DFYXIFus.cjs.map} +1 -1
  190. package/dist/{worker-server-CFe4nvos.cjs → worker-server--yGTadTA.cjs} +2 -2
  191. package/dist/{worker-server-CFe4nvos.cjs.map → worker-server--yGTadTA.cjs.map} +1 -1
  192. package/dist/{worker-server-iUVSjH8L.js → worker-server-BokySIII.js} +25 -25
  193. package/dist/{worker-server-iUVSjH8L.js.map → worker-server-BokySIII.js.map} +1 -1
  194. package/dist/worker-transport-BdEvh_-a.cjs +2 -0
  195. package/dist/worker-transport-BdEvh_-a.cjs.map +1 -0
  196. package/dist/{worker-transport-Dy1KMA7t.js → worker-transport-JK-Fby9J.js} +23 -19
  197. package/dist/worker-transport-JK-Fby9J.js.map +1 -0
  198. package/llms.txt +13 -10
  199. package/package.json +13 -5
  200. package/dist/bus-C39wspFV.js.map +0 -1
  201. package/dist/bus-_EaOVPGq.cjs +0 -2
  202. package/dist/bus-_EaOVPGq.cjs.map +0 -1
  203. package/dist/config-DUs7uHHt.cjs +0 -2
  204. package/dist/config-DUs7uHHt.cjs.map +0 -1
  205. package/dist/config-SgQcCP1_.js.map +0 -1
  206. package/dist/constants-CUyd9cTZ.js.map +0 -1
  207. package/dist/constants-CqdJhTxH.cjs +0 -2
  208. package/dist/constants-CqdJhTxH.cjs.map +0 -1
  209. package/dist/identity-DdhKgrpk.js.map +0 -1
  210. package/dist/identity-DlWRIuwy.cjs +0 -2
  211. package/dist/identity-DlWRIuwy.cjs.map +0 -1
  212. package/dist/interactions-CUkzK8sR.cjs +0 -2
  213. package/dist/interactions-CUkzK8sR.cjs.map +0 -1
  214. package/dist/interactions-DiFvCosX.js +0 -111
  215. package/dist/interactions-DiFvCosX.js.map +0 -1
  216. package/dist/rotation-Cwct4ckk.js.map +0 -1
  217. package/dist/rotation-D4qUAHAu.cjs +0 -2
  218. package/dist/rotation-D4qUAHAu.cjs.map +0 -1
  219. package/dist/worker-transport-CRAX-09c.cjs +0 -2
  220. package/dist/worker-transport-CRAX-09c.cjs.map +0 -1
  221. package/dist/worker-transport-Dy1KMA7t.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"replay-Ds-ANH34.js","names":["META_EVENT","REPLAY_ID_KEY","HEADER_CONTENT_ENCODING","HEADER_CONTENT_TYPE","HEADER_ATTEMPT","ENCODING_GZIP","HEADER_BATCH_ID","IGNORE_SELECTOR","CONTENT_TYPE_JSON","newId","runAsLibraryRequest","isLibraryRequest","unrefTimer","_defineProperty","gzip","withDeadline","allowInWindow","matchesAny","META_EVENT$1","KEPT_PARTS","ReplayBuffer","maxBytes","opens","isCheckout","type","last","text","limit","taken","part","size","CREDENTIAL_STATUSES","UNKNOWN_ERROR","STATUS_TOO_MANY","STATUS_SERVER_FAULT","ReplayUploader","config","diagnostics","ids","texts","maxSegmentBytes","maxSegmentEvents","flushIntervalMs","payload","segment","dropped","oldest","result","attempt","generation","replay","wait","delivery","source","timeoutMs","onSegment","error","endpoint","controller","timer","given","headers","_count","head","body","zipped","response","SESSION_ID","TAB_ID","MASK_CHARACTER","RECORD_OPTION_KEYS","MASK_EACH_INPUT","MASKED_INPUT","META_EVENT","INCREMENTAL_EVENT","MUTATION_SOURCE","TEXT_NODE","ReplayCapture","forced","maskSelectors","element","maskText","url","request","capture","event","uploadsPerWindow","lost","takeFullSnapshot","record","afterErrorMs","ctx","loader","selectors","loaded","tools","made","plugins","make","extra","ignored","key","value","stopRecorder","plugin","running","selector","blockSelectors","list","data","change","add","node","id","host","once","message"],"sources":["../src/capture/replay-buffer.ts","../src/capture/replay-upload.ts","../src/capture/replay.ts"],"sourcesContent":["// src/capture/replay-buffer.ts\n//\n// Keeps the recent session replay events in memory as JSON text. Events are grouped into\n// parts, and every part starts with a full snapshot, so a player can start from any of them.\n\n/** Event type of the meta event. The recorder sends it right before a full snapshot. */\nconst META_EVENT = 4;\n\n/** How many parts we keep. With a snapshot every half window, 3 parts cover a full window. */\nconst KEPT_PARTS = 3;\n\n/** Size-limited ring of recent replay events. */\nexport class ReplayBuffer {\n /** Events per part, as JSON text. The last part is the open one. */\n private parts: string[][] = [];\n\n /** Size of each part: the sum of its text lengths. */\n private sizes: number[] = [];\n\n /** Size of all parts together. */\n private total = 0;\n\n /**\n * True after the buffer had to drop its only part. Everything up to the next full snapshot\n * has no snapshot in front of it, which makes it useless to a player.\n */\n private starved = false;\n\n /** Events dropped by the size limit since the last take. */\n private lost = 0;\n\n /**\n * @param maxBytes Returns the size limit for all parts together.\n */\n constructor(private readonly maxBytes: () => number) {}\n\n /**\n * Adds one event.\n * @param text The event as JSON text.\n * @param type The recorder's event type.\n * @param isCheckout True for the events of a new full snapshot.\n * @returns True if this event made the buffer drop its only part.\n */\n add(text: string, type: number, isCheckout: boolean): boolean {\n // The meta event and the snapshot both carry the flag, but only the meta event opens a part.\n const opens = isCheckout && type === META_EVENT;\n\n if (this.starved && !opens) {\n this.lost++;\n return false;\n }\n\n if (opens || this.parts.length === 0) {\n this.starved = false;\n this.parts.push([]);\n this.sizes.push(0);\n\n if (this.parts.length > KEPT_PARTS) {\n this.dropOldest();\n }\n }\n\n const last = this.parts.length - 1;\n this.parts[last].push(text);\n this.sizes[last] += text.length;\n this.total += text.length;\n\n const limit = this.maxBytes();\n while (this.total > limit && this.parts.length > 0) {\n // Nothing with a snapshot comes after the last part, so once it goes the events that\n // follow can't be played.\n this.starved = this.parts.length === 1;\n this.lost += this.dropOldest();\n }\n\n return this.starved;\n }\n\n /**\n * Returns every event in order with the dropped count, and empties the buffer. A starved\n * buffer stays starved, because the events after a take still have no snapshot in front.\n * @returns The events as JSON text, and how many events the size limit dropped.\n */\n take(): { texts: string[]; lost: number } {\n const taken = { texts: this.parts.flat(), lost: this.lost };\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.lost = 0;\n return taken;\n }\n\n /** Empties the buffer and its dropped count, so the next upload doesn't report old drops. */\n clear(): void {\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.starved = false;\n this.lost = 0;\n }\n\n /**\n * Removes the oldest part.\n * @returns The number of events in that part.\n */\n private dropOldest(): number {\n const [part] = this.parts.splice(0, 1);\n const [size] = this.sizes.splice(0, 1);\n this.total -= size;\n return part.length;\n }\n}\n","// src/capture/replay-upload.ts\n//\n// Cuts session replay events into segments and sends them. A segment closes on an event count,\n// on a size, or after a wait. Only one segment is in flight at a time, which keeps them in\n// order. Segments live in memory only, and the exit flush doesn't send them.\n\nimport {\n COMPRESSION_THRESHOLD_BYTES,\n CONTENT_TYPE_JSON,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { ReplaySegment } from \"../models/replay\";\nimport { gzip } from \"../transport/compression\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\n\n/** The ids stamped on every segment of a recording. */\nexport interface ReplayIds {\n /** Recording id. */\n replayId: string;\n /** Session id from the record that triggered the upload. */\n sessionId: string;\n /** Tab id from the record that triggered the upload. */\n tabId: string;\n}\n\n/** Outcome of one send. `retry` means a later attempt might work. */\ntype SendResult = \"sent\" | \"retry\" | \"drop\";\n\n/** Statuses that mean our credentials were rejected. The next attempt re-reads the headers. */\nconst CREDENTIAL_STATUSES = [401, 403];\n\n/** Name used for a thrown value that isn't an Error. Reports only ever show the error name. */\nconst UNKNOWN_ERROR = \"Error\";\n\n/** The server is asking us to slow down. */\nconst STATUS_TOO_MANY = 429;\n\n/** Server faults start here. */\nconst STATUS_SERVER_FAULT = 500;\n\n/** Cuts replay events into segments and sends them in order. */\nexport class ReplayUploader {\n /** Events in the open segment, as JSON text. */\n private open: string[] = [];\n\n /** Size of the open segment. */\n private openBytes = 0;\n\n /** Closes a segment that didn't fill up in time. */\n private flushTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Closed segments waiting to be sent. The one in flight isn't in here. */\n private queue: ReplaySegment[] = [];\n\n /** Total size of the queued segments. */\n private queueBytes = 0;\n\n /** True while a segment is in flight or waiting for its next attempt. */\n private busy = false;\n\n /** Timer for the in-flight segment's next attempt. */\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Ids for the segments we cut next. */\n private ids: ReplayIds | undefined;\n\n /** Sequence number for the recording's next segment. */\n private sequence = 0;\n\n /** Bumped on every stop, so a send that finishes after a stop changes nothing. */\n private generation = 0;\n\n /** Aborts the request in flight. Once stopped, the uploader must not send anything else. */\n private inFlight: AbortController | undefined;\n\n /**\n * @param config Returns the current configuration.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: () => ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Sets the ids for the segments that follow. A new recording restarts the sequence at 0.\n * @param ids Ids of the recording and of the record that triggered the upload.\n */\n begin(ids: ReplayIds): void {\n if (ids.replayId !== this.ids?.replayId) {\n this.sequence = 0;\n }\n\n this.ids = ids;\n }\n\n /**\n * Adds events. A full segment closes right away, a partial one closes after the wait.\n * @param texts The events as JSON text, in order.\n */\n push(texts: readonly string[]): void {\n const { maxSegmentEvents, maxSegmentBytes, flushIntervalMs } = this.config().replay;\n\n for (const text of texts) {\n // If this event doesn't fit, close the segment first. A huge event ends up in its own.\n if (this.open.length > 0 && this.openBytes + text.length > maxSegmentBytes) {\n this.flush();\n }\n\n this.open.push(text);\n this.openBytes += text.length;\n\n if (this.open.length >= maxSegmentEvents || this.openBytes >= maxSegmentBytes) {\n this.flush();\n }\n }\n\n if (this.open.length > 0 && this.flushTimer === undefined) {\n this.flushTimer = setTimeout(() => {\n this.flushTimer = undefined;\n this.flush();\n }, flushIntervalMs);\n unrefTimer(this.flushTimer);\n }\n }\n\n /** Closes the open segment and gets it sent. */\n flush(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n\n const { ids } = this;\n if (this.open.length === 0 || !ids) {\n return;\n }\n\n const payload = `[${this.open.join(\",\")}]`;\n const segment: ReplaySegment = {\n \"replay.id\": ids.replayId,\n \"session.id\": ids.sessionId,\n \"tab.id\": ids.tabId,\n \"service.name\": this.config().serviceName,\n sequence: this.sequence++,\n events: this.open.length,\n bytes: payload.length,\n payload,\n };\n this.open = [];\n this.openBytes = 0;\n this.queue.push(segment);\n this.queueBytes += segment.bytes;\n\n let dropped = 0;\n while (this.queueBytes > this.config().replay.maxQueueBytes && this.queue.length > 1) {\n const [oldest] = this.queue.splice(0, 1);\n this.queueBytes -= oldest.bytes;\n dropped++;\n }\n\n if (dropped > 0) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The replay queue is above replay.maxQueueBytes. The library dropped ${String(dropped)} segments.`,\n );\n }\n\n this.drain();\n }\n\n /**\n * Drops the events of the open segment and keeps the closed ones. A snapshot that fails\n * halfway leaves its first events here, and a lone meta event is useless to a player.\n */\n discardOpen(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n this.open = [];\n this.openBytes = 0;\n }\n\n /** Drops everything that is waiting. A send still in flight no longer changes any state. */\n stop(): void {\n this.generation++;\n this.inFlight?.abort();\n this.inFlight = undefined;\n clearTimeout(this.retryTimer);\n this.retryTimer = undefined;\n this.discardOpen();\n this.queue = [];\n this.queueBytes = 0;\n this.busy = false;\n }\n\n /** Sends the next segment, unless one is already in flight. */\n private drain(): void {\n if (this.busy || this.queue.length === 0) {\n return;\n }\n\n const [segment] = this.queue.splice(0, 1);\n this.queueBytes -= segment.bytes;\n this.busy = true;\n void this.deliver(segment, 1, this.generation);\n }\n\n /**\n * Sends one segment, backing off before each retry.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n */\n private async deliver(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<void> {\n const result = await this.send(segment, attempt, generation);\n\n if (generation !== this.generation) {\n return;\n }\n\n const { replay, delivery } = this.config();\n if (result === \"retry\" && attempt < replay.maxAttempts) {\n const wait = Math.min(\n delivery.retryBaseDelayMs * 2 ** (attempt - 1),\n delivery.retryMaxDelayMs,\n );\n this.retryTimer = setTimeout(() => {\n this.retryTimer = undefined;\n void this.deliver(segment, attempt + 1, generation);\n }, wait);\n unrefTimer(this.retryTimer);\n return;\n }\n\n if (result !== \"sent\") {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The library dropped the replay segment ${String(segment.sequence)} after ${String(attempt)} attempts.`,\n { \"replay.id\": segment[\"replay.id\"], sequence: segment.sequence },\n );\n }\n\n this.busy = false;\n this.drain();\n }\n\n /**\n * Hands a segment to the app's onSegment function, or posts it to the endpoint. Never throws.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n * @returns How the send went.\n */\n private async send(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<SendResult> {\n const config = this.config();\n const { onSegment, endpoint, headers: source } = config.replay;\n const timeoutMs = config.delivery.requestTimeoutMs;\n\n if (onSegment) {\n try {\n // Don't let a callback that never settles block the uploader forever.\n await withDeadline(Promise.resolve(onSegment(segment)), timeoutMs);\n return \"sent\";\n } catch (error) {\n this.diagnostics.report(\n \"capture.record_failed\",\n `The replay.onSegment function threw an error, or it did not end in ${String(timeoutMs)} ms.`,\n undefined,\n error,\n );\n return \"drop\";\n }\n }\n\n // The capture starts only with an endpoint or onSegment, but a later configure() can remove\n // both while a segment waits.\n if (endpoint === null) {\n return \"drop\";\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, timeoutMs);\n unrefTimer(timer);\n\n try {\n // The replay endpoint only gets replay.headers. The log endpoint's headers may carry a\n // token meant for a different host.\n const given =\n typeof source === \"function\"\n ? await withDeadline(Promise.resolve(source()), timeoutMs)\n : source;\n const headers = new Headers(given ?? {});\n headers.set(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);\n headers.set(HEADER_BATCH_ID, `${segment[\"replay.id\"]}-${String(segment.sequence)}`);\n headers.set(HEADER_ATTEMPT, String(attempt - 1));\n\n // In the body \"events\" is the event list itself. Its length is the count.\n const { payload, events: _count, ...head } = segment;\n const text = `${JSON.stringify(head).slice(0, -1)},\"events\":${payload}}`;\n let body: string | Uint8Array<ArrayBuffer> = text;\n\n if (config.compression === ENCODING_GZIP && text.length >= COMPRESSION_THRESHOLD_BYTES) {\n const zipped = await gzip(text);\n\n if (zipped) {\n body = zipped;\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n }\n\n // If we were stopped during the awaits above, send nothing.\n if (generation !== this.generation) {\n return \"drop\";\n }\n\n this.inFlight = controller;\n\n // Network capture skips requests started in this scope. The replay endpoint is also in\n // capture.ignoreUrls, in case some wrapper starts the request later.\n const response = await runAsLibraryRequest(() =>\n fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n cache: \"no-store\",\n signal: controller.signal,\n }),\n );\n\n if (response.ok) {\n return \"sent\";\n }\n\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay endpoint returned ${String(response.status)}.`,\n );\n\n return CREDENTIAL_STATUSES.includes(response.status) ||\n response.status === STATUS_TOO_MANY ||\n response.status >= STATUS_SERVER_FAULT\n ? \"retry\"\n : \"drop\";\n } catch (error) {\n // A request error's message can contain the URL, and a URL can contain a credential.\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay request failed with ${error instanceof Error ? error.name : UNKNOWN_ERROR}.`,\n );\n return \"retry\";\n } finally {\n clearTimeout(timer);\n this.inFlight = undefined;\n }\n }\n}\n","// src/capture/replay.ts\n//\n// Session replay. The app's recorder package records the DOM, and this capture keeps the recent\n// events in memory. When an ERROR or FATAL record comes through, it uploads the buffer plus a\n// few seconds of what happens next. All text and input values are masked by default.\n\nimport { IGNORE_SELECTOR, REPLAY_ID_KEY, REPLAY_UNMASK_ATTRIBUTE } from \"../constants\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { ReplayEvent, ReplayPluginTools, ReplayRecord } from \"../models/replay\";\nimport { newId } from \"../utils/identity\";\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { ReplayBuffer } from \"./replay-buffer\";\nimport { ReplayUploader } from \"./replay-upload\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Resource attribute for the session id. */\nconst SESSION_ID = \"session.id\";\n\n/** Resource attribute for the tab id. */\nconst TAB_ID = \"tab.id\";\n\n/** Every non-space character of masked text becomes this. */\nconst MASK_CHARACTER = \"*\";\n\n/**\n * The replay.recordOptions keys we pass through to the recorder. Everything else the recorder\n * accepts is a mask, block, canvas, plugin or event option, and those are ours to set.\n */\nconst RECORD_OPTION_KEYS = [\n \"sampling\",\n \"slimDOMOptions\",\n \"ignoreClass\",\n \"ignoreSelector\",\n \"ignoreCSSAttributes\",\n \"userTriggeredOnInput\",\n \"recordAfter\",\n \"inlineStylesheet\",\n \"dataURLOptions\",\n];\n\n/**\n * Per-element input mask for the recorder. We don't use its \"mask all inputs\" switch because\n * that list leaves out hidden and file inputs.\n */\nconst MASK_EACH_INPUT = { input: true, textarea: true, select: true };\n\n/** What every masked input value turns into. Fixed length, so it doesn't give away a PIN's. */\nconst MASKED_INPUT = \"********\";\n\n/** Event type of the meta event, which carries the page URL. */\nconst META_EVENT = 4;\n\n/** Event type of an incremental snapshot. */\nconst INCREMENTAL_EVENT = 3;\n\n/** Incremental snapshot source for DOM mutations. */\nconst MUTATION_SOURCE = 0;\n\n/** Node type of a text node in the recorder's serialized nodes. */\nconst TEXT_NODE = 3;\n\n/** The bits of a recorder event we rewrite before keeping it. */\ninterface ScrubData {\n /** Page URL, on a meta event. */\n href?: unknown;\n /** Source of an incremental snapshot. */\n source?: unknown;\n /** Text changes in a mutation. */\n texts?: { id: number; value: unknown }[];\n /** Nodes added by a mutation. */\n adds?: { node?: { id: number; type: number; textContent?: unknown } }[];\n}\n\n/** Records the DOM and uploads the recent events after an error. */\nexport class ReplayCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"replay\";\n\n /** Recent events. An upload empties it. */\n private readonly buffer: ReplayBuffer;\n\n /** Cuts the events into segments and sends them. */\n private readonly uploader: ReplayUploader;\n\n /** Upload rate limit, so an error storm doesn't upload the page over and over. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** The recorder's record function. Undefined while the recorder isn't running. */\n private record: ReplayRecord | undefined;\n\n /** Stops the recorder. */\n private stopRecorder: (() => void) | undefined;\n\n /** Id of the current recording. */\n private replayId = \"\";\n\n /** True between install() and uninstall(). */\n private installed = false;\n\n /** True while start() is loading the recorder. */\n private starting = false;\n\n /** Bumped on every stop, so a start that finishes after a stop records nothing. */\n private generation = 0;\n\n /** True right after an error, while new events go straight to the uploader. */\n private live = false;\n\n /** True once we've reported a full snapshot that doesn't fit in the buffer. */\n private starvedReported = false;\n\n /** Ends the live period after an error. */\n private liveTimer: ReturnType<typeof setTimeout> | undefined;\n\n /**\n * @param ctx Capture context: configuration, diagnostics and the runtime hooks.\n */\n constructor(private readonly ctx: CaptureContext) {\n this.buffer = new ReplayBuffer(() => this.ctx.config.replay.maxBufferBytes);\n this.uploader = new ReplayUploader(() => this.ctx.config, this.ctx.diagnostics);\n }\n\n /** Starts listening for error records, and starts the recorder unless consent is still needed. */\n install(): void {\n if (this.installed) {\n return;\n }\n\n this.installed = true;\n this.ctx.onError?.(this.onError);\n\n // If the app called stopReplay(), that still holds after the captures are reinstalled.\n if (this.ctx.replayConsent?.() ?? !this.ctx.config.replay.requireConsent) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n uninstall(): void {\n this.installed = false;\n this.ctx.onError?.(undefined);\n this.stop();\n }\n\n /**\n * Loads the recorder and starts it. Never rejects.\n * @returns A promise that resolves once the recorder is running, or can't run.\n */\n async start(): Promise<void> {\n const { diagnostics } = this.ctx;\n const { loader, endpoint, onSegment, plugins } = this.ctx.config.replay;\n\n if (!this.installed || this.record || this.starting) {\n return;\n }\n\n if (typeof document === \"undefined\") {\n this.reportOnce(\"This context has no document. The session replay is off.\");\n return;\n }\n\n if (!loader || (endpoint === null && !onSegment)) {\n diagnostics.report(\n \"config.invalid\",\n \"The session replay needs replay.loader, and replay.endpoint or replay.onSegment. The session replay is off.\",\n );\n return;\n }\n\n const selectors = this.selectors();\n if (!selectors) {\n return;\n }\n\n const { generation } = this;\n this.starting = true;\n const loaded = await diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the replay recorder.\",\n loader,\n );\n const tools: ReplayPluginTools = { transformRequest: this.transformRequest };\n const made = await Promise.all(\n plugins.map((make) =>\n diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load a replay plugin.\",\n () => Promise.resolve(make(tools)),\n ),\n ),\n );\n\n // A stop or an uninstall while we were loading cancels this start.\n if (generation !== this.generation) {\n return;\n }\n\n this.starting = false;\n\n // The loader failed, and the guard has already reported it.\n if (!loaded) {\n return;\n }\n\n const { record } = loaded;\n if (typeof record !== \"function\") {\n diagnostics.report(\n \"capture.install_failed\",\n \"The replay loader gave no record function. The session replay is off.\",\n );\n return;\n }\n\n const config = this.ctx.config.replay;\n diagnostics.guard(\"capture.install_failed\", \"The replay recorder did not start.\", () => {\n const extra: Record<string, unknown> = {};\n const ignored: string[] = [];\n\n for (const [key, value] of Object.entries(config.recordOptions)) {\n if (RECORD_OPTION_KEYS.includes(key)) {\n extra[key] = value;\n } else {\n ignored.push(key);\n }\n }\n\n if (ignored.length > 0) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores these keys of replay.recordOptions: ${ignored.join(\", \")}. It sets the mask, block, canvas, plugin and event options itself.`,\n );\n }\n\n // The real recorder takes its first snapshot inside record(), so a starve report can come\n // before record() returns.\n this.starvedReported = false;\n\n const stopRecorder = record({\n ...extra,\n emit: this.emit,\n // Take a full snapshot every half window, so the buffer always begins with one.\n checkoutEveryNms: config.bufferMs / 2,\n // The per-element list covers every input type. Passwords are masked no matter what.\n maskAllInputs: false,\n maskInputOptions: config.maskInputs ? MASK_EACH_INPUT : { password: true },\n maskInputFn: this.maskInput,\n maskTextSelector: selectors.mask,\n maskTextFn: this.maskText,\n blockSelector: selectors.block,\n recordCanvas: config.recordCanvas,\n errorHandler: this.onFault,\n plugins: made.filter((plugin) => plugin !== undefined),\n });\n\n // The recorder swallows errors from its own startup and just returns no stop function.\n if (typeof stopRecorder !== \"function\") {\n diagnostics.report(\"capture.install_failed\", \"The replay recorder did not start.\");\n return;\n }\n\n this.stopRecorder = stopRecorder;\n this.record = record;\n this.replayId = newId(this.ctx.diagnostics);\n this.ctx.setContext?.(REPLAY_ID_KEY, this.replayId);\n });\n }\n\n /**\n * Drops the buffer and, if the recorder was running, starts a fresh recording. The runtime\n * calls this on a new session, so the next user never gets the previous user's page.\n */\n reset(): void {\n const running = this.record !== undefined || this.starting;\n\n this.stop();\n if (running) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n stop(): void {\n const { stopRecorder } = this;\n\n this.generation++;\n this.starting = false;\n this.record = undefined;\n this.stopRecorder = undefined;\n this.live = false;\n clearTimeout(this.liveTimer);\n this.liveTimer = undefined;\n this.buffer.clear();\n this.uploader.stop();\n\n if (stopRecorder) {\n this.ctx.setContext?.(REPLAY_ID_KEY, undefined);\n this.ctx.diagnostics.guard(\n \"capture.install_failed\",\n \"The replay recorder did not stop.\",\n stopRecorder,\n );\n }\n }\n\n /**\n * Reads the mask and block selectors. An invalid selector aborts the start: a replay with a\n * missing mask would show text the app meant to hide.\n * @returns The selectors for the recorder, or undefined if one of them is invalid.\n */\n private selectors(): { mask: string | undefined; block: string } | undefined {\n const { maskText, maskSelectors, blockSelectors } = this.ctx.config.replay;\n\n for (const selector of [...maskSelectors, ...blockSelectors]) {\n try {\n document.createDocumentFragment().querySelector(selector);\n } catch (error) {\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `The replay selector ${selector} is not a valid CSS selector. The session replay is off.`,\n undefined,\n error,\n );\n return undefined;\n }\n }\n\n const join = (list: string[]): string | undefined =>\n list.length > 0 ? list.join(\",\") : undefined;\n\n // Click capture skips the ignored regions, so a replay must not show them either. The app\n // can't turn this off.\n return {\n mask: maskText ? \"*\" : join(maskSelectors),\n block: [IGNORE_SELECTOR, ...blockSelectors].join(\",\"),\n };\n }\n\n /**\n * Masks one piece of page text. The recorder calls this for every text the mask selector\n * matches.\n * @param text The node's text.\n * @param element The element that holds the text, or null.\n * @returns The text to record.\n */\n private readonly maskText = (text: string, element: Element | null): string => {\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const forced = maskSelectors.length > 0 && element?.closest(maskSelectors.join(\",\"));\n\n // With maskText off, the recorder only calls us for text under a mask selector.\n if (maskText && !forced && element?.closest(`[${REPLAY_UNMASK_ATTRIBUTE}]`)) {\n return text;\n }\n\n return text.replace(/\\S/g, MASK_CHARACTER);\n };\n\n /**\n * Masks an input value. The result always has the same length.\n * @param text The input's value.\n * @returns The text to record.\n */\n private readonly maskInput = (text: string): string => (text === \"\" ? \"\" : MASKED_INPUT);\n\n /**\n * Strips what the recorder's own masking misses: the query string of the page URL, and text\n * sitting directly in a shadow root that changed after the snapshot.\n * @param event Recorder event.\n */\n private scrub(event: ReplayEvent): void {\n const { data } = event as { data?: ScrubData };\n\n if (!data) {\n return;\n }\n\n if (event.type === META_EVENT) {\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n if (typeof data.href === \"string\" && !this.ctx.config.capture.fullUrls) {\n data.href = data.href.split(/[?#]/)[0];\n }\n return;\n }\n\n if (event.type !== INCREMENTAL_EVENT || data.source !== MUTATION_SOURCE) {\n return;\n }\n\n for (const change of data.texts ?? []) {\n change.value = this.shadowText(change.value, change.id);\n }\n\n for (const add of data.adds ?? []) {\n if (add.node?.type === TEXT_NODE) {\n // The recorder holds on to this node object, so change a copy.\n add.node = {\n ...add.node,\n textContent: this.shadowText(add.node.textContent, add.node.id),\n };\n }\n }\n }\n\n /**\n * Masks text that sits directly in a shadow root. The recorder masks it in a full snapshot\n * but not in later mutations.\n * @param text Text from the mutation.\n * @param id The recorder's id for the text node.\n * @returns The text to record.\n */\n private shadowText(text: unknown, id: number): unknown {\n const node = this.record?.mirror?.getNode(id) as Node | null | undefined;\n\n // Text with an element parent has already been through the recorder's mask function.\n if (typeof text !== \"string\" || !node || node.parentElement) {\n return text;\n }\n\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const host = (node.parentNode as ShadowRoot | null)?.host ?? null;\n\n if (maskText) {\n return this.maskText(text, host);\n }\n\n return maskSelectors.length > 0 && host?.closest(maskSelectors.join(\",\"))\n ? text.replace(/\\S/g, MASK_CHARACTER)\n : text;\n }\n\n /**\n * Vets a request from the recorder's network plugin.\n * @param request The plugin's request.\n * @returns The request to record, or undefined to skip it.\n */\n private readonly transformRequest: ReplayPluginTools[\"transformRequest\"] = (request) => {\n // The plugin calls this from inside its fetch wrapper, so a throw here could reach the\n // app's request.\n try {\n const { capture } = this.ctx.config;\n const url = request.name;\n\n // The plugin calls us after the request, outside the library-request scope, so also check\n // the ignore list. It has every library endpoint, including the replay one. Otherwise a\n // recorded upload becomes a new event, which becomes a new upload.\n if (isLibraryRequest() || matchesAny(url, capture.ignoreUrls)) {\n return undefined;\n }\n\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n return capture.fullUrls ? request : { ...request, name: url.split(/[?#]/)[0] };\n } catch (error) {\n this.onFault(error);\n return undefined;\n }\n };\n\n /**\n * Receives one event from the recorder, which calls this from its observers.\n * @param event Recorder event.\n * @param isCheckout True for the events of a new full snapshot.\n */\n private readonly emit = (event: ReplayEvent, isCheckout?: boolean): void => {\n try {\n this.scrub(event);\n\n // Stringify once: we need the text for the upload and for the size limit anyway.\n const text = JSON.stringify(event);\n\n if (this.live) {\n this.uploader.push([text]);\n return;\n }\n\n if (this.buffer.add(text, event.type, isCheckout === true) && !this.starvedReported) {\n this.starvedReported = true;\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n \"One part of the replay is above replay.maxBufferBytes. The buffer is empty until the next full snapshot. The replay of an error in that time starts at the error, with no events from before it. Raise the limit, or block a large element with replay.blockSelectors.\",\n );\n }\n } catch (error) {\n this.onFault(error);\n }\n };\n\n /**\n * Reports an error from the recorder, or from serializing an event.\n * @param error What the recorder caught.\n */\n private readonly onFault = (error: unknown): void => {\n this.ctx.diagnostics.report(\n \"capture.record_failed\",\n \"The replay recorder had an error.\",\n undefined,\n error,\n );\n };\n\n /**\n * Starts an upload when an ERROR or FATAL record comes through.\n * @param record The record the runtime emitted.\n */\n private readonly onError = (record: LogRecord): void => {\n const { diagnostics, config } = this.ctx;\n\n diagnostics.guard(\"capture.record_failed\", \"The replay upload did not start.\", () => {\n if (!this.record) {\n return;\n }\n\n const { afterErrorMs, uploadsPerWindow } = config.replay;\n\n // An error during the live period rides along in the same upload and doesn't extend it.\n // That way a stream of errors can't hold the upload open, and the upload limit still bites.\n if (\n this.live ||\n !allowInWindow(\n this.window,\n uploadsPerWindow,\n diagnostics,\n \"replay uploads\",\n config.replay.uploadWindowMs,\n )\n ) {\n return;\n }\n\n const { texts, lost } = this.buffer.take();\n if (lost > 0) {\n diagnostics.report(\n \"capture.rate_limited\",\n `The replay buffer was above replay.maxBufferBytes. The library dropped ${String(lost)} events.`,\n );\n }\n\n const { takeFullSnapshot } = this.record;\n\n // An empty buffer has no full snapshot, and a player can't do anything without one.\n if (texts.length === 0 && !takeFullSnapshot) {\n return;\n }\n\n this.uploader.begin({\n replayId: this.replayId,\n sessionId: String(record.resource[SESSION_ID]),\n tabId: String(record.resource[TAB_ID]),\n });\n this.live = true;\n\n if (texts.length === 0) {\n // We're live, so this snapshot goes straight to the uploader. The real recorder throws\n // here before its start, and without the reset the live period would never end.\n const taken = diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot. The library sends no replay for this error.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n return true;\n },\n );\n\n // Nothing went out, so drop what a half-done snapshot left and give the slot back.\n // The uploader's open segment was empty, because live was off until begin().\n if (!taken) {\n this.live = false;\n this.uploader.discardOpen();\n this.window.count = Math.max(0, this.window.count - 1);\n return;\n }\n } else {\n this.uploader.push(texts);\n }\n\n this.liveTimer = setTimeout(this.endLive, afterErrorMs);\n unrefTimer(this.liveTimer);\n });\n };\n\n /** Ends the live period. The buffer starts over with a full snapshot. */\n private readonly endLive = (): void => {\n this.liveTimer = undefined;\n this.live = false;\n this.uploader.flush();\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n },\n );\n };\n\n /**\n * Reports why the replay is off, once per document.\n * @param message Report text.\n */\n private reportOnce(message: string): void {\n const { once } = this.ctx;\n\n if (!once.replay) {\n once.replay = true;\n this.ctx.diagnostics.report(\"capture.install_failed\", message);\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAMA,IAAMA,IAAa,GAGbmB,IAAa,GAGNC,IAAb,MAA0B;CAsBxB,YAAY,GAAyC;EAAxB,AAAAP,EAAA,MAAA,YAAA,KAAA,CAAA,GApB7BA,EAAA,MAAA,SAA4B,CAAC,CAAA,GAG7BA,EAAA,MAAA,SAA0B,CAAC,CAAA,GAG3BA,EAAA,MAAA,SAAgB,CAAA,GAMhBA,EAAA,MAAA,WAAkB,EAAA,GAGlBA,EAAA,MAAA,QAAe,CAAA,GAKc,KAAA,WAAAQ;CAAyB;CAStD,IAAI,GAAc,GAAc,GAA8B;EAE5D,IAAMC,IAAQC,KAAcC,MAASxB;EAErC,IAAI,KAAK,WAAW,CAACsB,GAEnB,OADA,KAAK,QACE;EAGT,CAAIA,KAAS,KAAK,MAAM,WAAW,OACjC,KAAK,UAAU,IACf,KAAK,MAAM,KAAK,CAAC,CAAC,GAClB,KAAK,MAAM,KAAK,CAAC,GAEb,KAAK,MAAM,SAASH,KACtB,KAAK,WAAW;EAIpB,IAAMM,IAAO,KAAK,MAAM,SAAS;EAGjC,AAFA,KAAK,MAAMA,EAAK,CAAC,KAAKC,CAAI,GAC1B,KAAK,MAAMD,MAASC,EAAK,QACzB,KAAK,SAASA,EAAK;EAEnB,IAAMC,IAAQ,KAAK,SAAS;EAC5B,OAAO,KAAK,QAAQA,KAAS,KAAK,MAAM,SAAS,IAI/C,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GAC9B,AAAIE,EAAI,MAAM,SAASnC,MAErB,EAAI,OAAO;KACT,GAAGmC,EAAI;KACP,aAAa,KAAK,WAAWA,EAAI,KAAK,aAAaA,EAAI,KAAK,EAAE;IAChE;GAToD;EAPxD;CAmBF;CASA,WAAmB,GAAe,GAAqB;EACrD,IAAMC,IAAO,KAAK,QAAQ,QAAQ,QAAQC,CAAE;EAG5C,IAAI,OAAOvF,KAAS,YAAY,CAACsF,KAAQA,EAAK,eAC5C,OAAOtF;EAGT,IAAM,EAAE,aAAU,qBAAkB,KAAK,IAAI,OAAO,QAC9CwF,IAAQF,EAAK,YAAkC,QAAQ;EAM7D,OAJI/B,IACK,KAAK,SAASvD,GAAMwF,CAAI,IAG1BnC,EAAc,SAAS,KAAKmC,GAAM,QAAQnC,EAAc,KAAK,GAAG,CAAC,IACpErD,EAAK,QAAQ,OAAO2C,CAAc,IAClC3C;CACN;CAyKA,WAAmB,GAAuB;EACxC,IAAM,EAAE,YAAS,KAAK;EAEtB,AAAKyF,EAAK,WACR,EAAK,SAAS,IACd,KAAK,IAAI,YAAY,OAAO,0BAA0BC,CAAO;CAEjE;AACF"}
1
+ {"version":3,"file":"replay-B0M8kWz_.js","names":["META_EVENT","HEADER_BATCH_ID","HEADER_CONTENT_ENCODING","REPLAY_ID_KEY","ENCODING_GZIP","HEADER_CONTENT_TYPE","HEADER_ATTEMPT","IGNORE_SELECTOR","CONTENT_TYPE_JSON","newId","runAsLibraryRequest","isLibraryRequest","unrefTimer","_defineProperty","gzip","withDeadline","allowInWindow","matchesAny","META_EVENT$1","KEPT_PARTS","ReplayBuffer","maxBytes","opens","isCheckout","type","last","text","limit","taken","part","size","CREDENTIAL_STATUSES","UNKNOWN_ERROR","STATUS_TOO_MANY","STATUS_SERVER_FAULT","ReplayUploader","config","diagnostics","ids","texts","maxSegmentBytes","maxSegmentEvents","flushIntervalMs","payload","segment","dropped","oldest","result","attempt","generation","replay","wait","delivery","source","timeoutMs","onSegment","error","endpoint","controller","timer","given","headers","_count","head","body","zipped","response","SESSION_ID","TAB_ID","MASK_CHARACTER","RECORD_OPTION_KEYS","MASK_EACH_INPUT","MASKED_INPUT","META_EVENT","INCREMENTAL_EVENT","MUTATION_SOURCE","TEXT_NODE","ReplayCapture","forced","maskSelectors","element","maskText","url","request","capture","event","uploadsPerWindow","lost","takeFullSnapshot","record","afterErrorMs","ctx","loader","selectors","loaded","tools","made","plugins","make","extra","ignored","key","value","stopRecorder","plugin","running","selector","blockSelectors","list","data","change","add","node","id","host","once","message"],"sources":["../src/capture/replay-buffer.ts","../src/capture/replay-upload.ts","../src/capture/replay.ts"],"sourcesContent":["// src/capture/replay-buffer.ts\n//\n// Keeps the recent session replay events in memory as JSON text. Events are grouped into\n// parts, and every part starts with a full snapshot, so a player can start from any of them.\n\n/** Event type of the meta event. The recorder sends it right before a full snapshot. */\nconst META_EVENT = 4;\n\n/** How many parts we keep. With a snapshot every half window, 3 parts cover a full window. */\nconst KEPT_PARTS = 3;\n\n/** Size-limited ring of recent replay events. */\nexport class ReplayBuffer {\n /** Events per part, as JSON text. The last part is the open one. */\n private parts: string[][] = [];\n\n /** Size of each part: the sum of its text lengths. */\n private sizes: number[] = [];\n\n /** Size of all parts together. */\n private total = 0;\n\n /**\n * True after the buffer had to drop its only part. Everything up to the next full snapshot\n * has no snapshot in front of it, which makes it useless to a player.\n */\n private starved = false;\n\n /** Events dropped by the size limit since the last take. */\n private lost = 0;\n\n /**\n * @param maxBytes Returns the size limit for all parts together.\n */\n constructor(private readonly maxBytes: () => number) {}\n\n /**\n * Adds one event.\n * @param text The event as JSON text.\n * @param type The recorder's event type.\n * @param isCheckout True for the events of a new full snapshot.\n * @returns True if this event made the buffer drop its only part.\n */\n add(text: string, type: number, isCheckout: boolean): boolean {\n // The meta event and the snapshot both carry the flag, but only the meta event opens a part.\n const opens = isCheckout && type === META_EVENT;\n\n if (this.starved && !opens) {\n this.lost++;\n return false;\n }\n\n if (opens || this.parts.length === 0) {\n this.starved = false;\n this.parts.push([]);\n this.sizes.push(0);\n\n if (this.parts.length > KEPT_PARTS) {\n this.dropOldest();\n }\n }\n\n const last = this.parts.length - 1;\n this.parts[last].push(text);\n this.sizes[last] += text.length;\n this.total += text.length;\n\n const limit = this.maxBytes();\n while (this.total > limit && this.parts.length > 0) {\n // Nothing with a snapshot comes after the last part, so once it goes the events that\n // follow can't be played.\n this.starved = this.parts.length === 1;\n this.lost += this.dropOldest();\n }\n\n return this.starved;\n }\n\n /**\n * Returns every event in order with the dropped count, and empties the buffer. A starved\n * buffer stays starved, because the events after a take still have no snapshot in front.\n * @returns The events as JSON text, and how many events the size limit dropped.\n */\n take(): { texts: string[]; lost: number } {\n const taken = { texts: this.parts.flat(), lost: this.lost };\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.lost = 0;\n return taken;\n }\n\n /** Empties the buffer and its dropped count, so the next upload doesn't report old drops. */\n clear(): void {\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.starved = false;\n this.lost = 0;\n }\n\n /**\n * Removes the oldest part.\n * @returns The number of events in that part.\n */\n private dropOldest(): number {\n const [part] = this.parts.splice(0, 1);\n const [size] = this.sizes.splice(0, 1);\n this.total -= size;\n return part.length;\n }\n}\n","// src/capture/replay-upload.ts\n//\n// Cuts session replay events into segments and sends them. A segment closes on an event count,\n// on a size, or after a wait. Only one segment is in flight at a time, which keeps them in\n// order. Segments live in memory only, and the exit flush doesn't send them.\n\nimport {\n COMPRESSION_THRESHOLD_BYTES,\n CONTENT_TYPE_JSON,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { ReplaySegment } from \"../models/replay\";\nimport { gzip } from \"../transport/compression\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\n\n/** The ids stamped on every segment of a recording. */\nexport interface ReplayIds {\n /** Recording id. */\n replayId: string;\n /** Session id from the record that triggered the upload. */\n sessionId: string;\n /** Tab id from the record that triggered the upload. */\n tabId: string;\n}\n\n/** Outcome of one send. `retry` means a later attempt might work. */\ntype SendResult = \"sent\" | \"retry\" | \"drop\";\n\n/** Statuses that mean our credentials were rejected. The next attempt re-reads the headers. */\nconst CREDENTIAL_STATUSES = [401, 403];\n\n/** Name used for a thrown value that isn't an Error. Reports only ever show the error name. */\nconst UNKNOWN_ERROR = \"Error\";\n\n/** The server is asking us to slow down. */\nconst STATUS_TOO_MANY = 429;\n\n/** Server faults start here. */\nconst STATUS_SERVER_FAULT = 500;\n\n/** Cuts replay events into segments and sends them in order. */\nexport class ReplayUploader {\n /** Events in the open segment, as JSON text. */\n private open: string[] = [];\n\n /** Size of the open segment. */\n private openBytes = 0;\n\n /** Closes a segment that didn't fill up in time. */\n private flushTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Closed segments waiting to be sent. The one in flight isn't in here. */\n private queue: ReplaySegment[] = [];\n\n /** Total size of the queued segments. */\n private queueBytes = 0;\n\n /** True while a segment is in flight or waiting for its next attempt. */\n private busy = false;\n\n /** Timer for the in-flight segment's next attempt. */\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Ids for the segments we cut next. */\n private ids: ReplayIds | undefined;\n\n /** Sequence number for the recording's next segment. */\n private sequence = 0;\n\n /** Bumped on every stop, so a send that finishes after a stop changes nothing. */\n private generation = 0;\n\n /** Aborts the request in flight. Once stopped, the uploader must not send anything else. */\n private inFlight: AbortController | undefined;\n\n /**\n * @param config Returns the current configuration.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: () => ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Sets the ids for the segments that follow. A new recording restarts the sequence at 0.\n * @param ids Ids of the recording and of the record that triggered the upload.\n */\n begin(ids: ReplayIds): void {\n if (ids.replayId !== this.ids?.replayId) {\n this.sequence = 0;\n }\n\n this.ids = ids;\n }\n\n /**\n * Adds events. A full segment closes right away, a partial one closes after the wait.\n * @param texts The events as JSON text, in order.\n */\n push(texts: readonly string[]): void {\n const { maxSegmentEvents, maxSegmentBytes, flushIntervalMs } = this.config().replay;\n\n for (const text of texts) {\n // If this event doesn't fit, close the segment first. A huge event ends up in its own.\n if (this.open.length > 0 && this.openBytes + text.length > maxSegmentBytes) {\n this.flush();\n }\n\n this.open.push(text);\n this.openBytes += text.length;\n\n if (this.open.length >= maxSegmentEvents || this.openBytes >= maxSegmentBytes) {\n this.flush();\n }\n }\n\n if (this.open.length > 0 && this.flushTimer === undefined) {\n this.flushTimer = setTimeout(() => {\n this.flushTimer = undefined;\n this.flush();\n }, flushIntervalMs);\n unrefTimer(this.flushTimer);\n }\n }\n\n /** Closes the open segment and gets it sent. */\n flush(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n\n const { ids } = this;\n if (this.open.length === 0 || !ids) {\n return;\n }\n\n const payload = `[${this.open.join(\",\")}]`;\n const segment: ReplaySegment = {\n \"replay.id\": ids.replayId,\n \"session.id\": ids.sessionId,\n \"tab.id\": ids.tabId,\n \"service.name\": this.config().serviceName,\n sequence: this.sequence++,\n events: this.open.length,\n bytes: payload.length,\n payload,\n };\n this.open = [];\n this.openBytes = 0;\n this.queue.push(segment);\n this.queueBytes += segment.bytes;\n\n let dropped = 0;\n while (this.queueBytes > this.config().replay.maxQueueBytes && this.queue.length > 1) {\n const [oldest] = this.queue.splice(0, 1);\n this.queueBytes -= oldest.bytes;\n dropped++;\n }\n\n if (dropped > 0) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The replay queue is above replay.maxQueueBytes. The library dropped ${String(dropped)} segments.`,\n );\n }\n\n this.drain();\n }\n\n /**\n * Drops the events of the open segment and keeps the closed ones. A snapshot that fails\n * halfway leaves its first events here, and a lone meta event is useless to a player.\n */\n discardOpen(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n this.open = [];\n this.openBytes = 0;\n }\n\n /** Drops everything that is waiting. A send still in flight no longer changes any state. */\n stop(): void {\n this.generation++;\n this.inFlight?.abort();\n this.inFlight = undefined;\n clearTimeout(this.retryTimer);\n this.retryTimer = undefined;\n this.discardOpen();\n this.queue = [];\n this.queueBytes = 0;\n this.busy = false;\n }\n\n /** Sends the next segment, unless one is already in flight. */\n private drain(): void {\n if (this.busy || this.queue.length === 0) {\n return;\n }\n\n const [segment] = this.queue.splice(0, 1);\n this.queueBytes -= segment.bytes;\n this.busy = true;\n void this.deliver(segment, 1, this.generation);\n }\n\n /**\n * Sends one segment, backing off before each retry.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n */\n private async deliver(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<void> {\n const result = await this.send(segment, attempt, generation);\n\n if (generation !== this.generation) {\n return;\n }\n\n const { replay, delivery } = this.config();\n if (result === \"retry\" && attempt < replay.maxAttempts) {\n const wait = Math.min(\n delivery.retryBaseDelayMs * 2 ** (attempt - 1),\n delivery.retryMaxDelayMs,\n );\n this.retryTimer = setTimeout(() => {\n this.retryTimer = undefined;\n void this.deliver(segment, attempt + 1, generation);\n }, wait);\n unrefTimer(this.retryTimer);\n return;\n }\n\n if (result !== \"sent\") {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The library dropped the replay segment ${String(segment.sequence)} after ${String(attempt)} attempts.`,\n { \"replay.id\": segment[\"replay.id\"], sequence: segment.sequence },\n );\n }\n\n this.busy = false;\n this.drain();\n }\n\n /**\n * Hands a segment to the app's onSegment function, or posts it to the endpoint. Never throws.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n * @returns How the send went.\n */\n private async send(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<SendResult> {\n const config = this.config();\n const { onSegment, endpoint, headers: source } = config.replay;\n const timeoutMs = config.delivery.requestTimeoutMs;\n\n if (onSegment) {\n try {\n // Don't let a callback that never settles block the uploader forever.\n await withDeadline(Promise.resolve(onSegment(segment)), timeoutMs);\n return \"sent\";\n } catch (error) {\n this.diagnostics.report(\n \"capture.record_failed\",\n `The replay.onSegment function threw an error, or it did not end in ${String(timeoutMs)} ms.`,\n undefined,\n error,\n );\n return \"drop\";\n }\n }\n\n // The capture starts only with an endpoint or onSegment, but a later configure() can remove\n // both while a segment waits.\n if (endpoint === null) {\n return \"drop\";\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, timeoutMs);\n unrefTimer(timer);\n\n try {\n // The replay endpoint only gets replay.headers. The log endpoint's headers may carry a\n // token meant for a different host.\n const given =\n typeof source === \"function\"\n ? await withDeadline(Promise.resolve(source()), timeoutMs)\n : source;\n const headers = new Headers(given ?? {});\n headers.set(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);\n headers.set(HEADER_BATCH_ID, `${segment[\"replay.id\"]}-${String(segment.sequence)}`);\n headers.set(HEADER_ATTEMPT, String(attempt - 1));\n\n // In the body \"events\" is the event list itself. Its length is the count.\n const { payload, events: _count, ...head } = segment;\n const text = `${JSON.stringify(head).slice(0, -1)},\"events\":${payload}}`;\n let body: string | Uint8Array<ArrayBuffer> = text;\n\n if (config.compression === ENCODING_GZIP && text.length >= COMPRESSION_THRESHOLD_BYTES) {\n const zipped = await gzip(text);\n\n if (zipped) {\n body = zipped;\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n }\n\n // If we were stopped during the awaits above, send nothing.\n if (generation !== this.generation) {\n return \"drop\";\n }\n\n this.inFlight = controller;\n\n // Network capture skips requests started in this scope. The replay endpoint is also in\n // capture.ignoreUrls, in case some wrapper starts the request later.\n const response = await runAsLibraryRequest(() =>\n fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n cache: \"no-store\",\n signal: controller.signal,\n }),\n );\n\n if (response.ok) {\n return \"sent\";\n }\n\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay endpoint returned ${String(response.status)}.`,\n );\n\n return CREDENTIAL_STATUSES.includes(response.status) ||\n response.status === STATUS_TOO_MANY ||\n response.status >= STATUS_SERVER_FAULT\n ? \"retry\"\n : \"drop\";\n } catch (error) {\n // A request error's message can contain the URL, and a URL can contain a credential.\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay request failed with ${error instanceof Error ? error.name : UNKNOWN_ERROR}.`,\n );\n return \"retry\";\n } finally {\n clearTimeout(timer);\n this.inFlight = undefined;\n }\n }\n}\n","// src/capture/replay.ts\n//\n// Session replay. The app's recorder package records the DOM, and this capture keeps the recent\n// events in memory. When an ERROR or FATAL record comes through, it uploads the buffer plus a\n// few seconds of what happens next. All text and input values are masked by default.\n\nimport { IGNORE_SELECTOR, REPLAY_ID_KEY, REPLAY_UNMASK_ATTRIBUTE } from \"../constants\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { ReplayEvent, ReplayPluginTools, ReplayRecord } from \"../models/replay\";\nimport { newId } from \"../utils/identity\";\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { ReplayBuffer } from \"./replay-buffer\";\nimport { ReplayUploader } from \"./replay-upload\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Resource attribute for the session id. */\nconst SESSION_ID = \"session.id\";\n\n/** Resource attribute for the tab id. */\nconst TAB_ID = \"tab.id\";\n\n/** Every non-space character of masked text becomes this. */\nconst MASK_CHARACTER = \"*\";\n\n/**\n * The replay.recordOptions keys we pass through to the recorder. Everything else the recorder\n * accepts is a mask, block, canvas, plugin or event option, and those are ours to set.\n */\nconst RECORD_OPTION_KEYS = [\n \"sampling\",\n \"slimDOMOptions\",\n \"ignoreClass\",\n \"ignoreSelector\",\n \"ignoreCSSAttributes\",\n \"userTriggeredOnInput\",\n \"recordAfter\",\n \"inlineStylesheet\",\n \"dataURLOptions\",\n];\n\n/**\n * Per-element input mask for the recorder. We don't use its \"mask all inputs\" switch because\n * that list leaves out hidden and file inputs.\n */\nconst MASK_EACH_INPUT = { input: true, textarea: true, select: true };\n\n/** What every masked input value turns into. Fixed length, so it doesn't give away a PIN's. */\nconst MASKED_INPUT = \"********\";\n\n/** Event type of the meta event, which carries the page URL. */\nconst META_EVENT = 4;\n\n/** Event type of an incremental snapshot. */\nconst INCREMENTAL_EVENT = 3;\n\n/** Incremental snapshot source for DOM mutations. */\nconst MUTATION_SOURCE = 0;\n\n/** Node type of a text node in the recorder's serialized nodes. */\nconst TEXT_NODE = 3;\n\n/** The bits of a recorder event we rewrite before keeping it. */\ninterface ScrubData {\n /** Page URL, on a meta event. */\n href?: unknown;\n /** Source of an incremental snapshot. */\n source?: unknown;\n /** Text changes in a mutation. */\n texts?: { id: number; value: unknown }[];\n /** Nodes added by a mutation. */\n adds?: { node?: { id: number; type: number; textContent?: unknown } }[];\n}\n\n/** Records the DOM and uploads the recent events after an error. */\nexport class ReplayCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"replay\";\n\n /** Recent events. An upload empties it. */\n private readonly buffer: ReplayBuffer;\n\n /** Cuts the events into segments and sends them. */\n private readonly uploader: ReplayUploader;\n\n /** Upload rate limit, so an error storm doesn't upload the page over and over. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** The recorder's record function. Undefined while the recorder isn't running. */\n private record: ReplayRecord | undefined;\n\n /** Stops the recorder. */\n private stopRecorder: (() => void) | undefined;\n\n /** Id of the current recording. */\n private replayId = \"\";\n\n /** True between install() and uninstall(). */\n private installed = false;\n\n /** True while start() is loading the recorder. */\n private starting = false;\n\n /** Bumped on every stop, so a start that finishes after a stop records nothing. */\n private generation = 0;\n\n /** True right after an error, while new events go straight to the uploader. */\n private live = false;\n\n /** True once we've reported a full snapshot that doesn't fit in the buffer. */\n private starvedReported = false;\n\n /** Ends the live period after an error. */\n private liveTimer: ReturnType<typeof setTimeout> | undefined;\n\n /**\n * @param ctx Capture context: configuration, diagnostics and the runtime hooks.\n */\n constructor(private readonly ctx: CaptureContext) {\n this.buffer = new ReplayBuffer(() => this.ctx.config.replay.maxBufferBytes);\n this.uploader = new ReplayUploader(() => this.ctx.config, this.ctx.diagnostics);\n }\n\n /** Starts listening for error records, and starts the recorder unless consent is still needed. */\n install(): void {\n if (this.installed) {\n return;\n }\n\n this.installed = true;\n this.ctx.onError?.(this.onError);\n\n // If the app called stopReplay(), that still holds after the captures are reinstalled.\n if (this.ctx.replayConsent?.() ?? !this.ctx.config.replay.requireConsent) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n uninstall(): void {\n this.installed = false;\n this.ctx.onError?.(undefined);\n this.stop();\n }\n\n /**\n * Loads the recorder and starts it. Never rejects.\n * @returns A promise that resolves once the recorder is running, or can't run.\n */\n async start(): Promise<void> {\n const { diagnostics } = this.ctx;\n const { loader, endpoint, onSegment, plugins } = this.ctx.config.replay;\n\n if (!this.installed || this.record || this.starting) {\n return;\n }\n\n if (typeof document === \"undefined\") {\n this.reportOnce(\"This context has no document. The session replay is off.\");\n return;\n }\n\n if (!loader || (endpoint === null && !onSegment)) {\n diagnostics.report(\n \"config.invalid\",\n \"The session replay needs replay.loader, and replay.endpoint or replay.onSegment. The session replay is off.\",\n );\n return;\n }\n\n const selectors = this.selectors();\n if (!selectors) {\n return;\n }\n\n const { generation } = this;\n this.starting = true;\n const loaded = await diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the replay recorder.\",\n loader,\n );\n const tools: ReplayPluginTools = { transformRequest: this.transformRequest };\n const made = await Promise.all(\n plugins.map((make) =>\n diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load a replay plugin.\",\n () => Promise.resolve(make(tools)),\n ),\n ),\n );\n\n // A stop or an uninstall while we were loading cancels this start.\n if (generation !== this.generation) {\n return;\n }\n\n this.starting = false;\n\n // The loader failed, and the guard has already reported it.\n if (!loaded) {\n return;\n }\n\n const { record } = loaded;\n if (typeof record !== \"function\") {\n diagnostics.report(\n \"capture.install_failed\",\n \"The replay loader gave no record function. The session replay is off.\",\n );\n return;\n }\n\n const config = this.ctx.config.replay;\n diagnostics.guard(\"capture.install_failed\", \"The replay recorder did not start.\", () => {\n const extra: Record<string, unknown> = {};\n const ignored: string[] = [];\n\n for (const [key, value] of Object.entries(config.recordOptions)) {\n if (RECORD_OPTION_KEYS.includes(key)) {\n extra[key] = value;\n } else {\n ignored.push(key);\n }\n }\n\n if (ignored.length > 0) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores these keys of replay.recordOptions: ${ignored.join(\", \")}. It sets the mask, block, canvas, plugin and event options itself.`,\n );\n }\n\n // The real recorder takes its first snapshot inside record(), so a starve report can come\n // before record() returns.\n this.starvedReported = false;\n\n const stopRecorder = record({\n ...extra,\n emit: this.emit,\n // Take a full snapshot every half window, so the buffer always begins with one.\n checkoutEveryNms: config.bufferMs / 2,\n // The per-element list covers every input type. Passwords are masked no matter what.\n maskAllInputs: false,\n maskInputOptions: config.maskInputs ? MASK_EACH_INPUT : { password: true },\n maskInputFn: this.maskInput,\n maskTextSelector: selectors.mask,\n maskTextFn: this.maskText,\n blockSelector: selectors.block,\n recordCanvas: config.recordCanvas,\n errorHandler: this.onFault,\n plugins: made.filter((plugin) => plugin !== undefined),\n });\n\n // The recorder swallows errors from its own startup and just returns no stop function.\n if (typeof stopRecorder !== \"function\") {\n diagnostics.report(\"capture.install_failed\", \"The replay recorder did not start.\");\n return;\n }\n\n this.stopRecorder = stopRecorder;\n this.record = record;\n this.replayId = newId(this.ctx.diagnostics);\n this.ctx.setContext?.(REPLAY_ID_KEY, this.replayId);\n });\n }\n\n /**\n * Drops the buffer and, if the recorder was running, starts a fresh recording. The runtime\n * calls this on a new session, so the next user never gets the previous user's page.\n */\n reset(): void {\n const running = this.record !== undefined || this.starting;\n\n this.stop();\n if (running) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n stop(): void {\n const { stopRecorder } = this;\n\n this.generation++;\n this.starting = false;\n this.record = undefined;\n this.stopRecorder = undefined;\n this.live = false;\n clearTimeout(this.liveTimer);\n this.liveTimer = undefined;\n this.buffer.clear();\n this.uploader.stop();\n\n if (stopRecorder) {\n this.ctx.setContext?.(REPLAY_ID_KEY, undefined);\n this.ctx.diagnostics.guard(\n \"capture.install_failed\",\n \"The replay recorder did not stop.\",\n stopRecorder,\n );\n }\n }\n\n /**\n * Reads the mask and block selectors. An invalid selector aborts the start: a replay with a\n * missing mask would show text the app meant to hide.\n * @returns The selectors for the recorder, or undefined if one of them is invalid.\n */\n private selectors(): { mask: string | undefined; block: string } | undefined {\n const { maskText, maskSelectors, blockSelectors } = this.ctx.config.replay;\n\n for (const selector of [...maskSelectors, ...blockSelectors]) {\n try {\n document.createDocumentFragment().querySelector(selector);\n } catch (error) {\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `The replay selector ${selector} is not a valid CSS selector. The session replay is off.`,\n undefined,\n error,\n );\n return undefined;\n }\n }\n\n const join = (list: string[]): string | undefined =>\n list.length > 0 ? list.join(\",\") : undefined;\n\n // Click capture skips the ignored regions, so a replay must not show them either. The app\n // can't turn this off.\n return {\n mask: maskText ? \"*\" : join(maskSelectors),\n block: [IGNORE_SELECTOR, ...blockSelectors].join(\",\"),\n };\n }\n\n /**\n * Masks one piece of page text. The recorder calls this for every text the mask selector\n * matches.\n * @param text The node's text.\n * @param element The element that holds the text, or null.\n * @returns The text to record.\n */\n private readonly maskText = (text: string, element: Element | null): string => {\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const forced = maskSelectors.length > 0 && element?.closest(maskSelectors.join(\",\"));\n\n // With maskText off, the recorder only calls us for text under a mask selector.\n if (maskText && !forced && element?.closest(`[${REPLAY_UNMASK_ATTRIBUTE}]`)) {\n return text;\n }\n\n return text.replace(/\\S/g, MASK_CHARACTER);\n };\n\n /**\n * Masks an input value. The result always has the same length.\n * @param text The input's value.\n * @returns The text to record.\n */\n private readonly maskInput = (text: string): string => (text === \"\" ? \"\" : MASKED_INPUT);\n\n /**\n * Strips what the recorder's own masking misses: the query string of the page URL, and text\n * sitting directly in a shadow root that changed after the snapshot.\n * @param event Recorder event.\n */\n private scrub(event: ReplayEvent): void {\n const { data } = event as { data?: ScrubData };\n\n if (!data) {\n return;\n }\n\n if (event.type === META_EVENT) {\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n if (typeof data.href === \"string\" && !this.ctx.config.capture.fullUrls) {\n data.href = data.href.split(/[?#]/)[0];\n }\n return;\n }\n\n if (event.type !== INCREMENTAL_EVENT || data.source !== MUTATION_SOURCE) {\n return;\n }\n\n for (const change of data.texts ?? []) {\n change.value = this.shadowText(change.value, change.id);\n }\n\n for (const add of data.adds ?? []) {\n if (add.node?.type === TEXT_NODE) {\n // The recorder holds on to this node object, so change a copy.\n add.node = {\n ...add.node,\n textContent: this.shadowText(add.node.textContent, add.node.id),\n };\n }\n }\n }\n\n /**\n * Masks text that sits directly in a shadow root. The recorder masks it in a full snapshot\n * but not in later mutations.\n * @param text Text from the mutation.\n * @param id The recorder's id for the text node.\n * @returns The text to record.\n */\n private shadowText(text: unknown, id: number): unknown {\n const node = this.record?.mirror?.getNode(id) as Node | null | undefined;\n\n // Text with an element parent has already been through the recorder's mask function.\n if (typeof text !== \"string\" || !node || node.parentElement) {\n return text;\n }\n\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const host = (node.parentNode as ShadowRoot | null)?.host ?? null;\n\n if (maskText) {\n return this.maskText(text, host);\n }\n\n return maskSelectors.length > 0 && host?.closest(maskSelectors.join(\",\"))\n ? text.replace(/\\S/g, MASK_CHARACTER)\n : text;\n }\n\n /**\n * Vets a request from the recorder's network plugin.\n * @param request The plugin's request.\n * @returns The request to record, or undefined to skip it.\n */\n private readonly transformRequest: ReplayPluginTools[\"transformRequest\"] = (request) => {\n // The plugin calls this from inside its fetch wrapper, so a throw here could reach the\n // app's request.\n try {\n const { capture } = this.ctx.config;\n const url = request.name;\n\n // The plugin calls us after the request, outside the library-request scope, so also check\n // the ignore list. It has every library endpoint, including the replay one. Otherwise a\n // recorded upload becomes a new event, which becomes a new upload.\n if (isLibraryRequest() || matchesAny(url, capture.ignoreUrls)) {\n return undefined;\n }\n\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n return capture.fullUrls ? request : { ...request, name: url.split(/[?#]/)[0] };\n } catch (error) {\n this.onFault(error);\n return undefined;\n }\n };\n\n /**\n * Receives one event from the recorder, which calls this from its observers.\n * @param event Recorder event.\n * @param isCheckout True for the events of a new full snapshot.\n */\n private readonly emit = (event: ReplayEvent, isCheckout?: boolean): void => {\n try {\n this.scrub(event);\n\n // Stringify once: we need the text for the upload and for the size limit anyway.\n const text = JSON.stringify(event);\n\n if (this.live) {\n this.uploader.push([text]);\n return;\n }\n\n if (this.buffer.add(text, event.type, isCheckout === true) && !this.starvedReported) {\n this.starvedReported = true;\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n \"One part of the replay is above replay.maxBufferBytes. The buffer is empty until the next full snapshot. The replay of an error in that time starts at the error, with no events from before it. Raise the limit, or block a large element with replay.blockSelectors.\",\n );\n }\n } catch (error) {\n this.onFault(error);\n }\n };\n\n /**\n * Reports an error from the recorder, or from serializing an event.\n * @param error What the recorder caught.\n */\n private readonly onFault = (error: unknown): void => {\n this.ctx.diagnostics.report(\n \"capture.record_failed\",\n \"The replay recorder had an error.\",\n undefined,\n error,\n );\n };\n\n /**\n * Starts an upload when an ERROR or FATAL record comes through.\n * @param record The record the runtime emitted.\n */\n private readonly onError = (record: LogRecord): void => {\n const { diagnostics, config } = this.ctx;\n\n diagnostics.guard(\"capture.record_failed\", \"The replay upload did not start.\", () => {\n if (!this.record) {\n return;\n }\n\n const { afterErrorMs, uploadsPerWindow } = config.replay;\n\n // An error during the live period rides along in the same upload and doesn't extend it.\n // That way a stream of errors can't hold the upload open, and the upload limit still bites.\n if (\n this.live ||\n !allowInWindow(\n this.window,\n uploadsPerWindow,\n diagnostics,\n \"replay uploads\",\n config.replay.uploadWindowMs,\n )\n ) {\n return;\n }\n\n const { texts, lost } = this.buffer.take();\n if (lost > 0) {\n diagnostics.report(\n \"capture.rate_limited\",\n `The replay buffer was above replay.maxBufferBytes. The library dropped ${String(lost)} events.`,\n );\n }\n\n const { takeFullSnapshot } = this.record;\n\n // An empty buffer has no full snapshot, and a player can't do anything without one.\n if (texts.length === 0 && !takeFullSnapshot) {\n return;\n }\n\n this.uploader.begin({\n replayId: this.replayId,\n sessionId: String(record.resource[SESSION_ID]),\n tabId: String(record.resource[TAB_ID]),\n });\n this.live = true;\n\n if (texts.length === 0) {\n // We're live, so this snapshot goes straight to the uploader. The real recorder throws\n // here before its start, and without the reset the live period would never end.\n const taken = diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot. The library sends no replay for this error.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n return true;\n },\n );\n\n // Nothing went out, so drop what a half-done snapshot left and give the slot back.\n // The uploader's open segment was empty, because live was off until begin().\n if (!taken) {\n this.live = false;\n this.uploader.discardOpen();\n this.window.count = Math.max(0, this.window.count - 1);\n return;\n }\n } else {\n this.uploader.push(texts);\n }\n\n this.liveTimer = setTimeout(this.endLive, afterErrorMs);\n unrefTimer(this.liveTimer);\n });\n };\n\n /** Ends the live period. The buffer starts over with a full snapshot. */\n private readonly endLive = (): void => {\n this.liveTimer = undefined;\n this.live = false;\n this.uploader.flush();\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n },\n );\n };\n\n /**\n * Reports why the replay is off, once per document.\n * @param message Report text.\n */\n private reportOnce(message: string): void {\n const { once } = this.ctx;\n\n if (!once.replay) {\n once.replay = true;\n this.ctx.diagnostics.report(\"capture.install_failed\", message);\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAMA,IAAMA,IAAa,GAGbmB,IAAa,GAGNC,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ASvD,GAAMwF,CAAI,IAG1BnC,EAAc,SAAS,KAAKmC,GAAM,QAAQnC,EAAc,KAAK,GAAG,CAAC,IACpErD,EAAK,QAAQ,OAAO2C,CAAc,IAClC3C;CACN;CAyKA,WAAmB,GAAuB;EACxC,IAAM,EAAE,YAAS,KAAK;EAEtB,AAAKyF,EAAK,WACR,EAAK,SAAS,IACd,KAAK,IAAI,YAAY,OAAO,0BAA0BC,CAAO;CAEjE;AACF"}
@@ -1,2 +1,2 @@
1
- const e=require("./constants-CqdJhTxH.cjs"),t=require("./identity-DlWRIuwy.cjs"),n=require("./library-request-D7OvTxZV.cjs"),r=require("./unref-CU9Nyz_9.cjs"),i=require("./defineProperty-X1c4tIPD.cjs"),a=require("./compression-CvED_Jel.cjs"),o=require("./deadline-CUGbto-y.cjs"),s=require("./storm-C-zYSdDX.cjs"),c=require("./types-C7WNpnG1.cjs");var l=4,u=3,d=class{constructor(e){i.t(this,`maxBytes`,void 0),i.t(this,`parts`,[]),i.t(this,`sizes`,[]),i.t(this,`total`,0),i.t(this,`starved`,!1),i.t(this,`lost`,0),this.maxBytes=e}add(e,t,n){let r=n&&t===l;if(this.starved&&!r)return this.lost++,!1;(r||this.parts.length===0)&&(this.starved=!1,this.parts.push([]),this.sizes.push(0),this.parts.length>u&&this.dropOldest());let i=this.parts.length-1;this.parts[i].push(e),this.sizes[i]+=e.length,this.total+=e.length;let a=this.maxBytes();for(;this.total>a&&this.parts.length>0;)this.starved=this.parts.length===1,this.lost+=this.dropOldest();return this.starved}take(){let e={texts:this.parts.flat(),lost:this.lost};return this.parts=[],this.sizes=[],this.total=0,this.lost=0,e}clear(){this.parts=[],this.sizes=[],this.total=0,this.starved=!1,this.lost=0}dropOldest(){let[e]=this.parts.splice(0,1),[t]=this.sizes.splice(0,1);return this.total-=t,e.length}},f=[401,403],p=`Error`,m=429,h=500,g=class{constructor(e,t){i.t(this,`config`,void 0),i.t(this,`diagnostics`,void 0),i.t(this,`open`,[]),i.t(this,`openBytes`,0),i.t(this,`flushTimer`,void 0),i.t(this,`queue`,[]),i.t(this,`queueBytes`,0),i.t(this,`busy`,!1),i.t(this,`retryTimer`,void 0),i.t(this,`ids`,void 0),i.t(this,`sequence`,0),i.t(this,`generation`,0),i.t(this,`inFlight`,void 0),this.config=e,this.diagnostics=t}begin(e){e.replayId!==this.ids?.replayId&&(this.sequence=0),this.ids=e}push(e){let{maxSegmentEvents:t,maxSegmentBytes:n,flushIntervalMs:i}=this.config().replay;for(let r of e)this.open.length>0&&this.openBytes+r.length>n&&this.flush(),this.open.push(r),this.openBytes+=r.length,(this.open.length>=t||this.openBytes>=n)&&this.flush();this.open.length>0&&this.flushTimer===void 0&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush()},i),r.t(this.flushTimer))}flush(){clearTimeout(this.flushTimer),this.flushTimer=void 0;let{ids:e}=this;if(this.open.length===0||!e)return;let t=`[${this.open.join(`,`)}]`,n={"replay.id":e.replayId,"session.id":e.sessionId,"tab.id":e.tabId,"service.name":this.config().serviceName,sequence:this.sequence++,events:this.open.length,bytes:t.length,payload:t};this.open=[],this.openBytes=0,this.queue.push(n),this.queueBytes+=n.bytes;let r=0;for(;this.queueBytes>this.config().replay.maxQueueBytes&&this.queue.length>1;){let[e]=this.queue.splice(0,1);this.queueBytes-=e.bytes,r++}r>0&&this.diagnostics.report(`transport.dropped_permanent`,`The replay queue is above replay.maxQueueBytes. The library dropped ${String(r)} segments.`),this.drain()}discardOpen(){clearTimeout(this.flushTimer),this.flushTimer=void 0,this.open=[],this.openBytes=0}stop(){this.generation++,this.inFlight?.abort(),this.inFlight=void 0,clearTimeout(this.retryTimer),this.retryTimer=void 0,this.discardOpen(),this.queue=[],this.queueBytes=0,this.busy=!1}drain(){if(this.busy||this.queue.length===0)return;let[e]=this.queue.splice(0,1);this.queueBytes-=e.bytes,this.busy=!0,this.deliver(e,1,this.generation)}async deliver(e,t,n){let i=await this.send(e,t,n);if(n!==this.generation)return;let{replay:a,delivery:o}=this.config();if(i===`retry`&&t<a.maxAttempts){let i=Math.min(o.retryBaseDelayMs*2**(t-1),o.retryMaxDelayMs);this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.deliver(e,t+1,n)},i),r.t(this.retryTimer)}else i!==`sent`&&this.diagnostics.report(`transport.dropped_permanent`,`The library dropped the replay segment ${String(e.sequence)} after ${String(t)} attempts.`,{"replay.id":e[`replay.id`],sequence:e.sequence}),this.busy=!1,this.drain()}async send(t,i,s){let c=this.config(),{onSegment:l,endpoint:u,headers:d}=c.replay,g=c.delivery.requestTimeoutMs;if(l)try{return await o.n(Promise.resolve(l(t)),g),`sent`}catch(e){return this.diagnostics.report(`capture.record_failed`,`The replay.onSegment function threw an error, or it did not end in ${String(g)} ms.`,void 0,e),`drop`}if(u===null)return`drop`;let _=new AbortController,v=setTimeout(()=>{_.abort()},g);r.t(v);try{let r=typeof d==`function`?await o.n(Promise.resolve(d()),g):d,l=new Headers(r??{});l.set(e.ft,e.z),l.set(e.ut,`${t[`replay.id`]}-${String(t.sequence)}`),l.set(e.lt,String(i-1));let{payload:p,events:v,...y}=t,b=`${JSON.stringify(y).slice(0,-1)},"events":${p}}`,x=b;if(c.compression===`gzip`&&b.length>=1024){let t=await a.t(b);t&&(x=t,l.set(e.dt,e.tt))}if(s!==this.generation)return`drop`;this.inFlight=_;let S=await n.r(()=>fetch(u,{method:`POST`,headers:l,body:x,credentials:c.credentials,cache:`no-store`,signal:_.signal}));return S.ok?`sent`:(this.diagnostics.report(`transport.http_error`,`The replay endpoint returned ${String(S.status)}.`),f.includes(S.status)||S.status===m||S.status>=h?`retry`:`drop`)}catch(e){return this.diagnostics.report(`transport.http_error`,`The replay request failed with ${e instanceof Error?e.name:p}.`),`retry`}finally{clearTimeout(v),this.inFlight=void 0}}},_=`session.id`,v=`tab.id`,y=`*`,b=[`sampling`,`slimDOMOptions`,`ignoreClass`,`ignoreSelector`,`ignoreCSSAttributes`,`userTriggeredOnInput`,`recordAfter`,`inlineStylesheet`,`dataURLOptions`],x={input:!0,textarea:!0,select:!0},S=`********`,C=4,w=3,T=0,E=3,D=class{constructor(e){i.t(this,`ctx`,void 0),i.t(this,`name`,`replay`),i.t(this,`buffer`,void 0),i.t(this,`uploader`,void 0),i.t(this,`window`,{start:0,count:0}),i.t(this,`record`,void 0),i.t(this,`stopRecorder`,void 0),i.t(this,`replayId`,``),i.t(this,`installed`,!1),i.t(this,`starting`,!1),i.t(this,`generation`,0),i.t(this,`live`,!1),i.t(this,`starvedReported`,!1),i.t(this,`liveTimer`,void 0),i.t(this,`maskText`,(e,t)=>{let{maskText:n,maskSelectors:r}=this.ctx.config.replay,i=r.length>0&&t?.closest(r.join(`,`));return n&&!i&&t?.closest(`[data-observability-unmask]`)?e:e.replace(/\S/g,y)}),i.t(this,`maskInput`,e=>e===``?``:S),i.t(this,`transformRequest`,e=>{try{let{capture:t}=this.ctx.config,r=e.name;return n.t()||c.t(r,t.ignoreUrls)?void 0:t.fullUrls?e:{...e,name:r.split(/[?#]/)[0]}}catch(e){this.onFault(e);return}}),i.t(this,`emit`,(e,t)=>{try{this.scrub(e);let n=JSON.stringify(e);if(this.live){this.uploader.push([n]);return}this.buffer.add(n,e.type,t===!0)&&!this.starvedReported&&(this.starvedReported=!0,this.ctx.diagnostics.report(`capture.rate_limited`,`One part of the replay is above replay.maxBufferBytes. The buffer is empty until the next full snapshot. The replay of an error in that time starts at the error, with no events from before it. Raise the limit, or block a large element with replay.blockSelectors.`))}catch(e){this.onFault(e)}}),i.t(this,`onFault`,e=>{this.ctx.diagnostics.report(`capture.record_failed`,`The replay recorder had an error.`,void 0,e)}),i.t(this,`onError`,e=>{let{diagnostics:t,config:n}=this.ctx;t.guard(`capture.record_failed`,`The replay upload did not start.`,()=>{if(!this.record)return;let{afterErrorMs:i,uploadsPerWindow:a}=n.replay;if(this.live||!s.t(this.window,a,t,`replay uploads`,n.replay.uploadWindowMs))return;let{texts:o,lost:c}=this.buffer.take();c>0&&t.report(`capture.rate_limited`,`The replay buffer was above replay.maxBufferBytes. The library dropped ${String(c)} events.`);let{takeFullSnapshot:l}=this.record;if(o.length!==0||l){if(this.uploader.begin({replayId:this.replayId,sessionId:String(e.resource[_]),tabId:String(e.resource[v])}),this.live=!0,o.length===0){if(!t.guard(`capture.record_failed`,`The replay recorder did not take a full snapshot. The library sends no replay for this error.`,()=>(this.record?.takeFullSnapshot?.(!0),!0))){this.live=!1,this.uploader.discardOpen(),this.window.count=Math.max(0,this.window.count-1);return}}else this.uploader.push(o);this.liveTimer=setTimeout(this.endLive,i),r.t(this.liveTimer)}})}),i.t(this,`endLive`,()=>{this.liveTimer=void 0,this.live=!1,this.uploader.flush(),this.ctx.diagnostics.guard(`capture.record_failed`,`The replay recorder did not take a full snapshot.`,()=>{this.record?.takeFullSnapshot?.(!0)})}),this.ctx=e,this.buffer=new d(()=>this.ctx.config.replay.maxBufferBytes),this.uploader=new g(()=>this.ctx.config,this.ctx.diagnostics)}install(){this.installed||(this.installed=!0,this.ctx.onError?.(this.onError),(this.ctx.replayConsent?.()??!this.ctx.config.replay.requireConsent)&&this.start())}uninstall(){this.installed=!1,this.ctx.onError?.(void 0),this.stop()}async start(){let{diagnostics:n}=this.ctx,{loader:r,endpoint:i,onSegment:a,plugins:o}=this.ctx.config.replay;if(!this.installed||this.record||this.starting)return;if(typeof document>`u`){this.reportOnce(`This context has no document. The session replay is off.`);return}if(!r||i===null&&!a){n.report(`config.invalid`,`The session replay needs replay.loader, and replay.endpoint or replay.onSegment. The session replay is off.`);return}let s=this.selectors();if(!s)return;let{generation:c}=this;this.starting=!0;let l=await n.guardAsync(`capture.install_failed`,`The library could not load the replay recorder.`,r),u={transformRequest:this.transformRequest},d=await Promise.all(o.map(e=>n.guardAsync(`capture.install_failed`,`The library could not load a replay plugin.`,()=>Promise.resolve(e(u)))));if(c!==this.generation||(this.starting=!1,!l))return;let{record:f}=l;if(typeof f!=`function`){n.report(`capture.install_failed`,`The replay loader gave no record function. The session replay is off.`);return}let p=this.ctx.config.replay;n.guard(`capture.install_failed`,`The replay recorder did not start.`,()=>{let r={},i=[];for(let[e,t]of Object.entries(p.recordOptions))b.includes(e)?r[e]=t:i.push(e);i.length>0&&n.report(`config.invalid`,`The library ignores these keys of replay.recordOptions: ${i.join(`, `)}. It sets the mask, block, canvas, plugin and event options itself.`),this.starvedReported=!1;let a=f({...r,emit:this.emit,checkoutEveryNms:p.bufferMs/2,maskAllInputs:!1,maskInputOptions:p.maskInputs?x:{password:!0},maskInputFn:this.maskInput,maskTextSelector:s.mask,maskTextFn:this.maskText,blockSelector:s.block,recordCanvas:p.recordCanvas,errorHandler:this.onFault,plugins:d.filter(e=>e!==void 0)});typeof a==`function`?(this.stopRecorder=a,this.record=f,this.replayId=t.i(this.ctx.diagnostics),this.ctx.setContext?.(e.dn,this.replayId)):n.report(`capture.install_failed`,`The replay recorder did not start.`)})}reset(){let e=this.record!==void 0||this.starting;this.stop(),e&&this.start()}stop(){let{stopRecorder:t}=this;this.generation++,this.starting=!1,this.record=void 0,this.stopRecorder=void 0,this.live=!1,clearTimeout(this.liveTimer),this.liveTimer=void 0,this.buffer.clear(),this.uploader.stop(),t&&(this.ctx.setContext?.(e.dn,void 0),this.ctx.diagnostics.guard(`capture.install_failed`,`The replay recorder did not stop.`,t))}selectors(){let{maskText:t,maskSelectors:n,blockSelectors:r}=this.ctx.config.replay;for(let e of[...n,...r])try{document.createDocumentFragment().querySelector(e)}catch(t){this.ctx.diagnostics.report(`config.invalid`,`The replay selector ${e} is not a valid CSS selector. The session replay is off.`,void 0,t);return}return{mask:t?`*`:(e=>e.length>0?e.join(`,`):void 0)(n),block:[e.vt,...r].join(`,`)}}scrub(e){let{data:t}=e;if(t){if(e.type===C)typeof t.href==`string`&&!this.ctx.config.capture.fullUrls&&(t.href=t.href.split(/[?#]/)[0]);else if(e.type===w&&t.source===T){for(let e of t.texts??[])e.value=this.shadowText(e.value,e.id);for(let e of t.adds??[])e.node?.type===E&&(e.node={...e.node,textContent:this.shadowText(e.node.textContent,e.node.id)})}}}shadowText(e,t){let n=this.record?.mirror?.getNode(t);if(typeof e!=`string`||!n||n.parentElement)return e;let{maskText:r,maskSelectors:i}=this.ctx.config.replay,a=n.parentNode?.host??null;return r?this.maskText(e,a):i.length>0&&a?.closest(i.join(`,`))?e.replace(/\S/g,y):e}reportOnce(e){let{once:t}=this.ctx;t.replay||(t.replay=!0,this.ctx.diagnostics.report(`capture.install_failed`,e))}};exports.ReplayCapture=D;
2
- //# sourceMappingURL=replay-B3gFXIZd.cjs.map
1
+ const e=require("./constants-CtF52hIV.cjs"),t=require("./identity-CvuyqZk7.cjs"),n=require("./library-request-kY9iTpIF.cjs"),r=require("./unref-CU9Nyz_9.cjs"),i=require("./defineProperty-X1c4tIPD.cjs"),a=require("./compression-C0hUHKR-.cjs"),o=require("./deadline-CUGbto-y.cjs"),s=require("./storm-BHgI12iS.cjs"),c=require("./types-C7WNpnG1.cjs");var l=4,u=3,d=class{constructor(e){i.t(this,`maxBytes`,void 0),i.t(this,`parts`,[]),i.t(this,`sizes`,[]),i.t(this,`total`,0),i.t(this,`starved`,!1),i.t(this,`lost`,0),this.maxBytes=e}add(e,t,n){let r=n&&t===l;if(this.starved&&!r)return this.lost++,!1;(r||this.parts.length===0)&&(this.starved=!1,this.parts.push([]),this.sizes.push(0),this.parts.length>u&&this.dropOldest());let i=this.parts.length-1;this.parts[i].push(e),this.sizes[i]+=e.length,this.total+=e.length;let a=this.maxBytes();for(;this.total>a&&this.parts.length>0;)this.starved=this.parts.length===1,this.lost+=this.dropOldest();return this.starved}take(){let e={texts:this.parts.flat(),lost:this.lost};return this.parts=[],this.sizes=[],this.total=0,this.lost=0,e}clear(){this.parts=[],this.sizes=[],this.total=0,this.starved=!1,this.lost=0}dropOldest(){let[e]=this.parts.splice(0,1),[t]=this.sizes.splice(0,1);return this.total-=t,e.length}},f=[401,403],p=`Error`,m=429,h=500,g=class{constructor(e,t){i.t(this,`config`,void 0),i.t(this,`diagnostics`,void 0),i.t(this,`open`,[]),i.t(this,`openBytes`,0),i.t(this,`flushTimer`,void 0),i.t(this,`queue`,[]),i.t(this,`queueBytes`,0),i.t(this,`busy`,!1),i.t(this,`retryTimer`,void 0),i.t(this,`ids`,void 0),i.t(this,`sequence`,0),i.t(this,`generation`,0),i.t(this,`inFlight`,void 0),this.config=e,this.diagnostics=t}begin(e){e.replayId!==this.ids?.replayId&&(this.sequence=0),this.ids=e}push(e){let{maxSegmentEvents:t,maxSegmentBytes:n,flushIntervalMs:i}=this.config().replay;for(let r of e)this.open.length>0&&this.openBytes+r.length>n&&this.flush(),this.open.push(r),this.openBytes+=r.length,(this.open.length>=t||this.openBytes>=n)&&this.flush();this.open.length>0&&this.flushTimer===void 0&&(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flush()},i),r.t(this.flushTimer))}flush(){clearTimeout(this.flushTimer),this.flushTimer=void 0;let{ids:e}=this;if(this.open.length===0||!e)return;let t=`[${this.open.join(`,`)}]`,n={"replay.id":e.replayId,"session.id":e.sessionId,"tab.id":e.tabId,"service.name":this.config().serviceName,sequence:this.sequence++,events:this.open.length,bytes:t.length,payload:t};this.open=[],this.openBytes=0,this.queue.push(n),this.queueBytes+=n.bytes;let r=0;for(;this.queueBytes>this.config().replay.maxQueueBytes&&this.queue.length>1;){let[e]=this.queue.splice(0,1);this.queueBytes-=e.bytes,r++}r>0&&this.diagnostics.report(`transport.dropped_permanent`,`The replay queue is above replay.maxQueueBytes. The library dropped ${String(r)} segments.`),this.drain()}discardOpen(){clearTimeout(this.flushTimer),this.flushTimer=void 0,this.open=[],this.openBytes=0}stop(){this.generation++,this.inFlight?.abort(),this.inFlight=void 0,clearTimeout(this.retryTimer),this.retryTimer=void 0,this.discardOpen(),this.queue=[],this.queueBytes=0,this.busy=!1}drain(){if(this.busy||this.queue.length===0)return;let[e]=this.queue.splice(0,1);this.queueBytes-=e.bytes,this.busy=!0,this.deliver(e,1,this.generation)}async deliver(e,t,n){let i=await this.send(e,t,n);if(n!==this.generation)return;let{replay:a,delivery:o}=this.config();if(i===`retry`&&t<a.maxAttempts){let i=Math.min(o.retryBaseDelayMs*2**(t-1),o.retryMaxDelayMs);this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.deliver(e,t+1,n)},i),r.t(this.retryTimer)}else i!==`sent`&&this.diagnostics.report(`transport.dropped_permanent`,`The library dropped the replay segment ${String(e.sequence)} after ${String(t)} attempts.`,{"replay.id":e[`replay.id`],sequence:e.sequence}),this.busy=!1,this.drain()}async send(t,i,s){let c=this.config(),{onSegment:l,endpoint:u,headers:d}=c.replay,g=c.delivery.requestTimeoutMs;if(l)try{return await o.n(Promise.resolve(l(t)),g),`sent`}catch(e){return this.diagnostics.report(`capture.record_failed`,`The replay.onSegment function threw an error, or it did not end in ${String(g)} ms.`,void 0,e),`drop`}if(u===null)return`drop`;let _=new AbortController,v=setTimeout(()=>{_.abort()},g);r.t(v);try{let r=typeof d==`function`?await o.n(Promise.resolve(d()),g):d,l=new Headers(r??{});l.set(e.pt,e.z),l.set(e.dt,`${t[`replay.id`]}-${String(t.sequence)}`),l.set(e.ut,String(i-1));let{payload:p,events:v,...y}=t,b=`${JSON.stringify(y).slice(0,-1)},"events":${p}}`,x=b;if(c.compression===`gzip`&&b.length>=1024){let t=await a.t(b);t&&(x=t,l.set(e.ft,e.nt))}if(s!==this.generation)return`drop`;this.inFlight=_;let S=await n.r(()=>fetch(u,{method:`POST`,headers:l,body:x,credentials:c.credentials,cache:`no-store`,signal:_.signal}));return S.ok?`sent`:(this.diagnostics.report(`transport.http_error`,`The replay endpoint returned ${String(S.status)}.`),f.includes(S.status)||S.status===m||S.status>=h?`retry`:`drop`)}catch(e){return this.diagnostics.report(`transport.http_error`,`The replay request failed with ${e instanceof Error?e.name:p}.`),`retry`}finally{clearTimeout(v),this.inFlight=void 0}}},_=`session.id`,v=`tab.id`,y=`*`,b=[`sampling`,`slimDOMOptions`,`ignoreClass`,`ignoreSelector`,`ignoreCSSAttributes`,`userTriggeredOnInput`,`recordAfter`,`inlineStylesheet`,`dataURLOptions`],x={input:!0,textarea:!0,select:!0},S=`********`,C=4,w=3,T=0,E=3,D=class{constructor(e){i.t(this,`ctx`,void 0),i.t(this,`name`,`replay`),i.t(this,`buffer`,void 0),i.t(this,`uploader`,void 0),i.t(this,`window`,{start:0,count:0}),i.t(this,`record`,void 0),i.t(this,`stopRecorder`,void 0),i.t(this,`replayId`,``),i.t(this,`installed`,!1),i.t(this,`starting`,!1),i.t(this,`generation`,0),i.t(this,`live`,!1),i.t(this,`starvedReported`,!1),i.t(this,`liveTimer`,void 0),i.t(this,`maskText`,(e,t)=>{let{maskText:n,maskSelectors:r}=this.ctx.config.replay,i=r.length>0&&t?.closest(r.join(`,`));return n&&!i&&t?.closest(`[data-observability-unmask]`)?e:e.replace(/\S/g,y)}),i.t(this,`maskInput`,e=>e===``?``:S),i.t(this,`transformRequest`,e=>{try{let{capture:t}=this.ctx.config,r=e.name;return n.t()||c.t(r,t.ignoreUrls)?void 0:t.fullUrls?e:{...e,name:r.split(/[?#]/)[0]}}catch(e){this.onFault(e);return}}),i.t(this,`emit`,(e,t)=>{try{this.scrub(e);let n=JSON.stringify(e);if(this.live){this.uploader.push([n]);return}this.buffer.add(n,e.type,t===!0)&&!this.starvedReported&&(this.starvedReported=!0,this.ctx.diagnostics.report(`capture.rate_limited`,`One part of the replay is above replay.maxBufferBytes. The buffer is empty until the next full snapshot. The replay of an error in that time starts at the error, with no events from before it. Raise the limit, or block a large element with replay.blockSelectors.`))}catch(e){this.onFault(e)}}),i.t(this,`onFault`,e=>{this.ctx.diagnostics.report(`capture.record_failed`,`The replay recorder had an error.`,void 0,e)}),i.t(this,`onError`,e=>{let{diagnostics:t,config:n}=this.ctx;t.guard(`capture.record_failed`,`The replay upload did not start.`,()=>{if(!this.record)return;let{afterErrorMs:i,uploadsPerWindow:a}=n.replay;if(this.live||!s.t(this.window,a,t,`replay uploads`,n.replay.uploadWindowMs))return;let{texts:o,lost:c}=this.buffer.take();c>0&&t.report(`capture.rate_limited`,`The replay buffer was above replay.maxBufferBytes. The library dropped ${String(c)} events.`);let{takeFullSnapshot:l}=this.record;if(o.length!==0||l){if(this.uploader.begin({replayId:this.replayId,sessionId:String(e.resource[_]),tabId:String(e.resource[v])}),this.live=!0,o.length===0){if(!t.guard(`capture.record_failed`,`The replay recorder did not take a full snapshot. The library sends no replay for this error.`,()=>(this.record?.takeFullSnapshot?.(!0),!0))){this.live=!1,this.uploader.discardOpen(),this.window.count=Math.max(0,this.window.count-1);return}}else this.uploader.push(o);this.liveTimer=setTimeout(this.endLive,i),r.t(this.liveTimer)}})}),i.t(this,`endLive`,()=>{this.liveTimer=void 0,this.live=!1,this.uploader.flush(),this.ctx.diagnostics.guard(`capture.record_failed`,`The replay recorder did not take a full snapshot.`,()=>{this.record?.takeFullSnapshot?.(!0)})}),this.ctx=e,this.buffer=new d(()=>this.ctx.config.replay.maxBufferBytes),this.uploader=new g(()=>this.ctx.config,this.ctx.diagnostics)}install(){this.installed||(this.installed=!0,this.ctx.onError?.(this.onError),(this.ctx.replayConsent?.()??!this.ctx.config.replay.requireConsent)&&this.start())}uninstall(){this.installed=!1,this.ctx.onError?.(void 0),this.stop()}async start(){let{diagnostics:n}=this.ctx,{loader:r,endpoint:i,onSegment:a,plugins:o}=this.ctx.config.replay;if(!this.installed||this.record||this.starting)return;if(typeof document>`u`){this.reportOnce(`This context has no document. The session replay is off.`);return}if(!r||i===null&&!a){n.report(`config.invalid`,`The session replay needs replay.loader, and replay.endpoint or replay.onSegment. The session replay is off.`);return}let s=this.selectors();if(!s)return;let{generation:c}=this;this.starting=!0;let l=await n.guardAsync(`capture.install_failed`,`The library could not load the replay recorder.`,r),u={transformRequest:this.transformRequest},d=await Promise.all(o.map(e=>n.guardAsync(`capture.install_failed`,`The library could not load a replay plugin.`,()=>Promise.resolve(e(u)))));if(c!==this.generation||(this.starting=!1,!l))return;let{record:f}=l;if(typeof f!=`function`){n.report(`capture.install_failed`,`The replay loader gave no record function. The session replay is off.`);return}let p=this.ctx.config.replay;n.guard(`capture.install_failed`,`The replay recorder did not start.`,()=>{let r={},i=[];for(let[e,t]of Object.entries(p.recordOptions))b.includes(e)?r[e]=t:i.push(e);i.length>0&&n.report(`config.invalid`,`The library ignores these keys of replay.recordOptions: ${i.join(`, `)}. It sets the mask, block, canvas, plugin and event options itself.`),this.starvedReported=!1;let a=f({...r,emit:this.emit,checkoutEveryNms:p.bufferMs/2,maskAllInputs:!1,maskInputOptions:p.maskInputs?x:{password:!0},maskInputFn:this.maskInput,maskTextSelector:s.mask,maskTextFn:this.maskText,blockSelector:s.block,recordCanvas:p.recordCanvas,errorHandler:this.onFault,plugins:d.filter(e=>e!==void 0)});typeof a==`function`?(this.stopRecorder=a,this.record=f,this.replayId=t.i(this.ctx.diagnostics),this.ctx.setContext?.(e.mn,this.replayId)):n.report(`capture.install_failed`,`The replay recorder did not start.`)})}reset(){let e=this.record!==void 0||this.starting;this.stop(),e&&this.start()}stop(){let{stopRecorder:t}=this;this.generation++,this.starting=!1,this.record=void 0,this.stopRecorder=void 0,this.live=!1,clearTimeout(this.liveTimer),this.liveTimer=void 0,this.buffer.clear(),this.uploader.stop(),t&&(this.ctx.setContext?.(e.mn,void 0),this.ctx.diagnostics.guard(`capture.install_failed`,`The replay recorder did not stop.`,t))}selectors(){let{maskText:t,maskSelectors:n,blockSelectors:r}=this.ctx.config.replay;for(let e of[...n,...r])try{document.createDocumentFragment().querySelector(e)}catch(t){this.ctx.diagnostics.report(`config.invalid`,`The replay selector ${e} is not a valid CSS selector. The session replay is off.`,void 0,t);return}return{mask:t?`*`:(e=>e.length>0?e.join(`,`):void 0)(n),block:[e.yt,...r].join(`,`)}}scrub(e){let{data:t}=e;if(t){if(e.type===C)typeof t.href==`string`&&!this.ctx.config.capture.fullUrls&&(t.href=t.href.split(/[?#]/)[0]);else if(e.type===w&&t.source===T){for(let e of t.texts??[])e.value=this.shadowText(e.value,e.id);for(let e of t.adds??[])e.node?.type===E&&(e.node={...e.node,textContent:this.shadowText(e.node.textContent,e.node.id)})}}}shadowText(e,t){let n=this.record?.mirror?.getNode(t);if(typeof e!=`string`||!n||n.parentElement)return e;let{maskText:r,maskSelectors:i}=this.ctx.config.replay,a=n.parentNode?.host??null;return r?this.maskText(e,a):i.length>0&&a?.closest(i.join(`,`))?e.replace(/\S/g,y):e}reportOnce(e){let{once:t}=this.ctx;t.replay||(t.replay=!0,this.ctx.diagnostics.report(`capture.install_failed`,e))}};exports.ReplayCapture=D;
2
+ //# sourceMappingURL=replay-QOFBpAXh.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"replay-B3gFXIZd.cjs","names":["META_EVENT","withDeadline","HEADER_CONTENT_TYPE","CONTENT_TYPE_JSON","HEADER_BATCH_ID","HEADER_ATTEMPT","gzip","HEADER_CONTENT_ENCODING","ENCODING_GZIP","runAsLibraryRequest","isLibraryRequest","matchesAny","allowInWindow","newId","REPLAY_ID_KEY","IGNORE_SELECTOR","require_constants","require_identity","require_library_request","require_unref","require_defineProperty","require_compression","require_deadline","require_storm","require_types","META_EVENT$1","KEPT_PARTS","ReplayBuffer","maxBytes","opens","isCheckout","type","last","text","limit","taken","part","size","CREDENTIAL_STATUSES","UNKNOWN_ERROR","STATUS_TOO_MANY","STATUS_SERVER_FAULT","ReplayUploader","config","diagnostics","ids","texts","maxSegmentBytes","maxSegmentEvents","flushIntervalMs","payload","segment","dropped","oldest","result","attempt","generation","replay","wait","delivery","source","timeoutMs","onSegment","error","endpoint","controller","timer","given","headers","_count","head","body","zipped","response","SESSION_ID","TAB_ID","MASK_CHARACTER","RECORD_OPTION_KEYS","MASK_EACH_INPUT","MASKED_INPUT","META_EVENT","INCREMENTAL_EVENT","MUTATION_SOURCE","TEXT_NODE","ReplayCapture","forced","maskSelectors","element","maskText","url","request","capture","event","uploadsPerWindow","lost","takeFullSnapshot","record","afterErrorMs","ctx","loader","selectors","loaded","tools","made","plugins","make","extra","ignored","key","value","stopRecorder","plugin","running","selector","blockSelectors","list","data","change","add","node","id","host","once","message"],"sources":["../src/capture/replay-buffer.ts","../src/capture/replay-upload.ts","../src/capture/replay.ts"],"sourcesContent":["// src/capture/replay-buffer.ts\n//\n// Keeps the recent session replay events in memory as JSON text. Events are grouped into\n// parts, and every part starts with a full snapshot, so a player can start from any of them.\n\n/** Event type of the meta event. The recorder sends it right before a full snapshot. */\nconst META_EVENT = 4;\n\n/** How many parts we keep. With a snapshot every half window, 3 parts cover a full window. */\nconst KEPT_PARTS = 3;\n\n/** Size-limited ring of recent replay events. */\nexport class ReplayBuffer {\n /** Events per part, as JSON text. The last part is the open one. */\n private parts: string[][] = [];\n\n /** Size of each part: the sum of its text lengths. */\n private sizes: number[] = [];\n\n /** Size of all parts together. */\n private total = 0;\n\n /**\n * True after the buffer had to drop its only part. Everything up to the next full snapshot\n * has no snapshot in front of it, which makes it useless to a player.\n */\n private starved = false;\n\n /** Events dropped by the size limit since the last take. */\n private lost = 0;\n\n /**\n * @param maxBytes Returns the size limit for all parts together.\n */\n constructor(private readonly maxBytes: () => number) {}\n\n /**\n * Adds one event.\n * @param text The event as JSON text.\n * @param type The recorder's event type.\n * @param isCheckout True for the events of a new full snapshot.\n * @returns True if this event made the buffer drop its only part.\n */\n add(text: string, type: number, isCheckout: boolean): boolean {\n // The meta event and the snapshot both carry the flag, but only the meta event opens a part.\n const opens = isCheckout && type === META_EVENT;\n\n if (this.starved && !opens) {\n this.lost++;\n return false;\n }\n\n if (opens || this.parts.length === 0) {\n this.starved = false;\n this.parts.push([]);\n this.sizes.push(0);\n\n if (this.parts.length > KEPT_PARTS) {\n this.dropOldest();\n }\n }\n\n const last = this.parts.length - 1;\n this.parts[last].push(text);\n this.sizes[last] += text.length;\n this.total += text.length;\n\n const limit = this.maxBytes();\n while (this.total > limit && this.parts.length > 0) {\n // Nothing with a snapshot comes after the last part, so once it goes the events that\n // follow can't be played.\n this.starved = this.parts.length === 1;\n this.lost += this.dropOldest();\n }\n\n return this.starved;\n }\n\n /**\n * Returns every event in order with the dropped count, and empties the buffer. A starved\n * buffer stays starved, because the events after a take still have no snapshot in front.\n * @returns The events as JSON text, and how many events the size limit dropped.\n */\n take(): { texts: string[]; lost: number } {\n const taken = { texts: this.parts.flat(), lost: this.lost };\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.lost = 0;\n return taken;\n }\n\n /** Empties the buffer and its dropped count, so the next upload doesn't report old drops. */\n clear(): void {\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.starved = false;\n this.lost = 0;\n }\n\n /**\n * Removes the oldest part.\n * @returns The number of events in that part.\n */\n private dropOldest(): number {\n const [part] = this.parts.splice(0, 1);\n const [size] = this.sizes.splice(0, 1);\n this.total -= size;\n return part.length;\n }\n}\n","// src/capture/replay-upload.ts\n//\n// Cuts session replay events into segments and sends them. A segment closes on an event count,\n// on a size, or after a wait. Only one segment is in flight at a time, which keeps them in\n// order. Segments live in memory only, and the exit flush doesn't send them.\n\nimport {\n COMPRESSION_THRESHOLD_BYTES,\n CONTENT_TYPE_JSON,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { ReplaySegment } from \"../models/replay\";\nimport { gzip } from \"../transport/compression\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\n\n/** The ids stamped on every segment of a recording. */\nexport interface ReplayIds {\n /** Recording id. */\n replayId: string;\n /** Session id from the record that triggered the upload. */\n sessionId: string;\n /** Tab id from the record that triggered the upload. */\n tabId: string;\n}\n\n/** Outcome of one send. `retry` means a later attempt might work. */\ntype SendResult = \"sent\" | \"retry\" | \"drop\";\n\n/** Statuses that mean our credentials were rejected. The next attempt re-reads the headers. */\nconst CREDENTIAL_STATUSES = [401, 403];\n\n/** Name used for a thrown value that isn't an Error. Reports only ever show the error name. */\nconst UNKNOWN_ERROR = \"Error\";\n\n/** The server is asking us to slow down. */\nconst STATUS_TOO_MANY = 429;\n\n/** Server faults start here. */\nconst STATUS_SERVER_FAULT = 500;\n\n/** Cuts replay events into segments and sends them in order. */\nexport class ReplayUploader {\n /** Events in the open segment, as JSON text. */\n private open: string[] = [];\n\n /** Size of the open segment. */\n private openBytes = 0;\n\n /** Closes a segment that didn't fill up in time. */\n private flushTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Closed segments waiting to be sent. The one in flight isn't in here. */\n private queue: ReplaySegment[] = [];\n\n /** Total size of the queued segments. */\n private queueBytes = 0;\n\n /** True while a segment is in flight or waiting for its next attempt. */\n private busy = false;\n\n /** Timer for the in-flight segment's next attempt. */\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Ids for the segments we cut next. */\n private ids: ReplayIds | undefined;\n\n /** Sequence number for the recording's next segment. */\n private sequence = 0;\n\n /** Bumped on every stop, so a send that finishes after a stop changes nothing. */\n private generation = 0;\n\n /** Aborts the request in flight. Once stopped, the uploader must not send anything else. */\n private inFlight: AbortController | undefined;\n\n /**\n * @param config Returns the current configuration.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: () => ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Sets the ids for the segments that follow. A new recording restarts the sequence at 0.\n * @param ids Ids of the recording and of the record that triggered the upload.\n */\n begin(ids: ReplayIds): void {\n if (ids.replayId !== this.ids?.replayId) {\n this.sequence = 0;\n }\n\n this.ids = ids;\n }\n\n /**\n * Adds events. A full segment closes right away, a partial one closes after the wait.\n * @param texts The events as JSON text, in order.\n */\n push(texts: readonly string[]): void {\n const { maxSegmentEvents, maxSegmentBytes, flushIntervalMs } = this.config().replay;\n\n for (const text of texts) {\n // If this event doesn't fit, close the segment first. A huge event ends up in its own.\n if (this.open.length > 0 && this.openBytes + text.length > maxSegmentBytes) {\n this.flush();\n }\n\n this.open.push(text);\n this.openBytes += text.length;\n\n if (this.open.length >= maxSegmentEvents || this.openBytes >= maxSegmentBytes) {\n this.flush();\n }\n }\n\n if (this.open.length > 0 && this.flushTimer === undefined) {\n this.flushTimer = setTimeout(() => {\n this.flushTimer = undefined;\n this.flush();\n }, flushIntervalMs);\n unrefTimer(this.flushTimer);\n }\n }\n\n /** Closes the open segment and gets it sent. */\n flush(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n\n const { ids } = this;\n if (this.open.length === 0 || !ids) {\n return;\n }\n\n const payload = `[${this.open.join(\",\")}]`;\n const segment: ReplaySegment = {\n \"replay.id\": ids.replayId,\n \"session.id\": ids.sessionId,\n \"tab.id\": ids.tabId,\n \"service.name\": this.config().serviceName,\n sequence: this.sequence++,\n events: this.open.length,\n bytes: payload.length,\n payload,\n };\n this.open = [];\n this.openBytes = 0;\n this.queue.push(segment);\n this.queueBytes += segment.bytes;\n\n let dropped = 0;\n while (this.queueBytes > this.config().replay.maxQueueBytes && this.queue.length > 1) {\n const [oldest] = this.queue.splice(0, 1);\n this.queueBytes -= oldest.bytes;\n dropped++;\n }\n\n if (dropped > 0) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The replay queue is above replay.maxQueueBytes. The library dropped ${String(dropped)} segments.`,\n );\n }\n\n this.drain();\n }\n\n /**\n * Drops the events of the open segment and keeps the closed ones. A snapshot that fails\n * halfway leaves its first events here, and a lone meta event is useless to a player.\n */\n discardOpen(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n this.open = [];\n this.openBytes = 0;\n }\n\n /** Drops everything that is waiting. A send still in flight no longer changes any state. */\n stop(): void {\n this.generation++;\n this.inFlight?.abort();\n this.inFlight = undefined;\n clearTimeout(this.retryTimer);\n this.retryTimer = undefined;\n this.discardOpen();\n this.queue = [];\n this.queueBytes = 0;\n this.busy = false;\n }\n\n /** Sends the next segment, unless one is already in flight. */\n private drain(): void {\n if (this.busy || this.queue.length === 0) {\n return;\n }\n\n const [segment] = this.queue.splice(0, 1);\n this.queueBytes -= segment.bytes;\n this.busy = true;\n void this.deliver(segment, 1, this.generation);\n }\n\n /**\n * Sends one segment, backing off before each retry.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n */\n private async deliver(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<void> {\n const result = await this.send(segment, attempt, generation);\n\n if (generation !== this.generation) {\n return;\n }\n\n const { replay, delivery } = this.config();\n if (result === \"retry\" && attempt < replay.maxAttempts) {\n const wait = Math.min(\n delivery.retryBaseDelayMs * 2 ** (attempt - 1),\n delivery.retryMaxDelayMs,\n );\n this.retryTimer = setTimeout(() => {\n this.retryTimer = undefined;\n void this.deliver(segment, attempt + 1, generation);\n }, wait);\n unrefTimer(this.retryTimer);\n return;\n }\n\n if (result !== \"sent\") {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The library dropped the replay segment ${String(segment.sequence)} after ${String(attempt)} attempts.`,\n { \"replay.id\": segment[\"replay.id\"], sequence: segment.sequence },\n );\n }\n\n this.busy = false;\n this.drain();\n }\n\n /**\n * Hands a segment to the app's onSegment function, or posts it to the endpoint. Never throws.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n * @returns How the send went.\n */\n private async send(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<SendResult> {\n const config = this.config();\n const { onSegment, endpoint, headers: source } = config.replay;\n const timeoutMs = config.delivery.requestTimeoutMs;\n\n if (onSegment) {\n try {\n // Don't let a callback that never settles block the uploader forever.\n await withDeadline(Promise.resolve(onSegment(segment)), timeoutMs);\n return \"sent\";\n } catch (error) {\n this.diagnostics.report(\n \"capture.record_failed\",\n `The replay.onSegment function threw an error, or it did not end in ${String(timeoutMs)} ms.`,\n undefined,\n error,\n );\n return \"drop\";\n }\n }\n\n // The capture starts only with an endpoint or onSegment, but a later configure() can remove\n // both while a segment waits.\n if (endpoint === null) {\n return \"drop\";\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, timeoutMs);\n unrefTimer(timer);\n\n try {\n // The replay endpoint only gets replay.headers. The log endpoint's headers may carry a\n // token meant for a different host.\n const given =\n typeof source === \"function\"\n ? await withDeadline(Promise.resolve(source()), timeoutMs)\n : source;\n const headers = new Headers(given ?? {});\n headers.set(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);\n headers.set(HEADER_BATCH_ID, `${segment[\"replay.id\"]}-${String(segment.sequence)}`);\n headers.set(HEADER_ATTEMPT, String(attempt - 1));\n\n // In the body \"events\" is the event list itself. Its length is the count.\n const { payload, events: _count, ...head } = segment;\n const text = `${JSON.stringify(head).slice(0, -1)},\"events\":${payload}}`;\n let body: string | Uint8Array<ArrayBuffer> = text;\n\n if (config.compression === ENCODING_GZIP && text.length >= COMPRESSION_THRESHOLD_BYTES) {\n const zipped = await gzip(text);\n\n if (zipped) {\n body = zipped;\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n }\n\n // If we were stopped during the awaits above, send nothing.\n if (generation !== this.generation) {\n return \"drop\";\n }\n\n this.inFlight = controller;\n\n // Network capture skips requests started in this scope. The replay endpoint is also in\n // capture.ignoreUrls, in case some wrapper starts the request later.\n const response = await runAsLibraryRequest(() =>\n fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n cache: \"no-store\",\n signal: controller.signal,\n }),\n );\n\n if (response.ok) {\n return \"sent\";\n }\n\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay endpoint returned ${String(response.status)}.`,\n );\n\n return CREDENTIAL_STATUSES.includes(response.status) ||\n response.status === STATUS_TOO_MANY ||\n response.status >= STATUS_SERVER_FAULT\n ? \"retry\"\n : \"drop\";\n } catch (error) {\n // A request error's message can contain the URL, and a URL can contain a credential.\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay request failed with ${error instanceof Error ? error.name : UNKNOWN_ERROR}.`,\n );\n return \"retry\";\n } finally {\n clearTimeout(timer);\n this.inFlight = undefined;\n }\n }\n}\n","// src/capture/replay.ts\n//\n// Session replay. The app's recorder package records the DOM, and this capture keeps the recent\n// events in memory. When an ERROR or FATAL record comes through, it uploads the buffer plus a\n// few seconds of what happens next. All text and input values are masked by default.\n\nimport { IGNORE_SELECTOR, REPLAY_ID_KEY, REPLAY_UNMASK_ATTRIBUTE } from \"../constants\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { ReplayEvent, ReplayPluginTools, ReplayRecord } from \"../models/replay\";\nimport { newId } from \"../utils/identity\";\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { ReplayBuffer } from \"./replay-buffer\";\nimport { ReplayUploader } from \"./replay-upload\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Resource attribute for the session id. */\nconst SESSION_ID = \"session.id\";\n\n/** Resource attribute for the tab id. */\nconst TAB_ID = \"tab.id\";\n\n/** Every non-space character of masked text becomes this. */\nconst MASK_CHARACTER = \"*\";\n\n/**\n * The replay.recordOptions keys we pass through to the recorder. Everything else the recorder\n * accepts is a mask, block, canvas, plugin or event option, and those are ours to set.\n */\nconst RECORD_OPTION_KEYS = [\n \"sampling\",\n \"slimDOMOptions\",\n \"ignoreClass\",\n \"ignoreSelector\",\n \"ignoreCSSAttributes\",\n \"userTriggeredOnInput\",\n \"recordAfter\",\n \"inlineStylesheet\",\n \"dataURLOptions\",\n];\n\n/**\n * Per-element input mask for the recorder. We don't use its \"mask all inputs\" switch because\n * that list leaves out hidden and file inputs.\n */\nconst MASK_EACH_INPUT = { input: true, textarea: true, select: true };\n\n/** What every masked input value turns into. Fixed length, so it doesn't give away a PIN's. */\nconst MASKED_INPUT = \"********\";\n\n/** Event type of the meta event, which carries the page URL. */\nconst META_EVENT = 4;\n\n/** Event type of an incremental snapshot. */\nconst INCREMENTAL_EVENT = 3;\n\n/** Incremental snapshot source for DOM mutations. */\nconst MUTATION_SOURCE = 0;\n\n/** Node type of a text node in the recorder's serialized nodes. */\nconst TEXT_NODE = 3;\n\n/** The bits of a recorder event we rewrite before keeping it. */\ninterface ScrubData {\n /** Page URL, on a meta event. */\n href?: unknown;\n /** Source of an incremental snapshot. */\n source?: unknown;\n /** Text changes in a mutation. */\n texts?: { id: number; value: unknown }[];\n /** Nodes added by a mutation. */\n adds?: { node?: { id: number; type: number; textContent?: unknown } }[];\n}\n\n/** Records the DOM and uploads the recent events after an error. */\nexport class ReplayCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"replay\";\n\n /** Recent events. An upload empties it. */\n private readonly buffer: ReplayBuffer;\n\n /** Cuts the events into segments and sends them. */\n private readonly uploader: ReplayUploader;\n\n /** Upload rate limit, so an error storm doesn't upload the page over and over. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** The recorder's record function. Undefined while the recorder isn't running. */\n private record: ReplayRecord | undefined;\n\n /** Stops the recorder. */\n private stopRecorder: (() => void) | undefined;\n\n /** Id of the current recording. */\n private replayId = \"\";\n\n /** True between install() and uninstall(). */\n private installed = false;\n\n /** True while start() is loading the recorder. */\n private starting = false;\n\n /** Bumped on every stop, so a start that finishes after a stop records nothing. */\n private generation = 0;\n\n /** True right after an error, while new events go straight to the uploader. */\n private live = false;\n\n /** True once we've reported a full snapshot that doesn't fit in the buffer. */\n private starvedReported = false;\n\n /** Ends the live period after an error. */\n private liveTimer: ReturnType<typeof setTimeout> | undefined;\n\n /**\n * @param ctx Capture context: configuration, diagnostics and the runtime hooks.\n */\n constructor(private readonly ctx: CaptureContext) {\n this.buffer = new ReplayBuffer(() => this.ctx.config.replay.maxBufferBytes);\n this.uploader = new ReplayUploader(() => this.ctx.config, this.ctx.diagnostics);\n }\n\n /** Starts listening for error records, and starts the recorder unless consent is still needed. */\n install(): void {\n if (this.installed) {\n return;\n }\n\n this.installed = true;\n this.ctx.onError?.(this.onError);\n\n // If the app called stopReplay(), that still holds after the captures are reinstalled.\n if (this.ctx.replayConsent?.() ?? !this.ctx.config.replay.requireConsent) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n uninstall(): void {\n this.installed = false;\n this.ctx.onError?.(undefined);\n this.stop();\n }\n\n /**\n * Loads the recorder and starts it. Never rejects.\n * @returns A promise that resolves once the recorder is running, or can't run.\n */\n async start(): Promise<void> {\n const { diagnostics } = this.ctx;\n const { loader, endpoint, onSegment, plugins } = this.ctx.config.replay;\n\n if (!this.installed || this.record || this.starting) {\n return;\n }\n\n if (typeof document === \"undefined\") {\n this.reportOnce(\"This context has no document. The session replay is off.\");\n return;\n }\n\n if (!loader || (endpoint === null && !onSegment)) {\n diagnostics.report(\n \"config.invalid\",\n \"The session replay needs replay.loader, and replay.endpoint or replay.onSegment. The session replay is off.\",\n );\n return;\n }\n\n const selectors = this.selectors();\n if (!selectors) {\n return;\n }\n\n const { generation } = this;\n this.starting = true;\n const loaded = await diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the replay recorder.\",\n loader,\n );\n const tools: ReplayPluginTools = { transformRequest: this.transformRequest };\n const made = await Promise.all(\n plugins.map((make) =>\n diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load a replay plugin.\",\n () => Promise.resolve(make(tools)),\n ),\n ),\n );\n\n // A stop or an uninstall while we were loading cancels this start.\n if (generation !== this.generation) {\n return;\n }\n\n this.starting = false;\n\n // The loader failed, and the guard has already reported it.\n if (!loaded) {\n return;\n }\n\n const { record } = loaded;\n if (typeof record !== \"function\") {\n diagnostics.report(\n \"capture.install_failed\",\n \"The replay loader gave no record function. The session replay is off.\",\n );\n return;\n }\n\n const config = this.ctx.config.replay;\n diagnostics.guard(\"capture.install_failed\", \"The replay recorder did not start.\", () => {\n const extra: Record<string, unknown> = {};\n const ignored: string[] = [];\n\n for (const [key, value] of Object.entries(config.recordOptions)) {\n if (RECORD_OPTION_KEYS.includes(key)) {\n extra[key] = value;\n } else {\n ignored.push(key);\n }\n }\n\n if (ignored.length > 0) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores these keys of replay.recordOptions: ${ignored.join(\", \")}. It sets the mask, block, canvas, plugin and event options itself.`,\n );\n }\n\n // The real recorder takes its first snapshot inside record(), so a starve report can come\n // before record() returns.\n this.starvedReported = false;\n\n const stopRecorder = record({\n ...extra,\n emit: this.emit,\n // Take a full snapshot every half window, so the buffer always begins with one.\n checkoutEveryNms: config.bufferMs / 2,\n // The per-element list covers every input type. Passwords are masked no matter what.\n maskAllInputs: false,\n maskInputOptions: config.maskInputs ? MASK_EACH_INPUT : { password: true },\n maskInputFn: this.maskInput,\n maskTextSelector: selectors.mask,\n maskTextFn: this.maskText,\n blockSelector: selectors.block,\n recordCanvas: config.recordCanvas,\n errorHandler: this.onFault,\n plugins: made.filter((plugin) => plugin !== undefined),\n });\n\n // The recorder swallows errors from its own startup and just returns no stop function.\n if (typeof stopRecorder !== \"function\") {\n diagnostics.report(\"capture.install_failed\", \"The replay recorder did not start.\");\n return;\n }\n\n this.stopRecorder = stopRecorder;\n this.record = record;\n this.replayId = newId(this.ctx.diagnostics);\n this.ctx.setContext?.(REPLAY_ID_KEY, this.replayId);\n });\n }\n\n /**\n * Drops the buffer and, if the recorder was running, starts a fresh recording. The runtime\n * calls this on a new session, so the next user never gets the previous user's page.\n */\n reset(): void {\n const running = this.record !== undefined || this.starting;\n\n this.stop();\n if (running) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n stop(): void {\n const { stopRecorder } = this;\n\n this.generation++;\n this.starting = false;\n this.record = undefined;\n this.stopRecorder = undefined;\n this.live = false;\n clearTimeout(this.liveTimer);\n this.liveTimer = undefined;\n this.buffer.clear();\n this.uploader.stop();\n\n if (stopRecorder) {\n this.ctx.setContext?.(REPLAY_ID_KEY, undefined);\n this.ctx.diagnostics.guard(\n \"capture.install_failed\",\n \"The replay recorder did not stop.\",\n stopRecorder,\n );\n }\n }\n\n /**\n * Reads the mask and block selectors. An invalid selector aborts the start: a replay with a\n * missing mask would show text the app meant to hide.\n * @returns The selectors for the recorder, or undefined if one of them is invalid.\n */\n private selectors(): { mask: string | undefined; block: string } | undefined {\n const { maskText, maskSelectors, blockSelectors } = this.ctx.config.replay;\n\n for (const selector of [...maskSelectors, ...blockSelectors]) {\n try {\n document.createDocumentFragment().querySelector(selector);\n } catch (error) {\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `The replay selector ${selector} is not a valid CSS selector. The session replay is off.`,\n undefined,\n error,\n );\n return undefined;\n }\n }\n\n const join = (list: string[]): string | undefined =>\n list.length > 0 ? list.join(\",\") : undefined;\n\n // Click capture skips the ignored regions, so a replay must not show them either. The app\n // can't turn this off.\n return {\n mask: maskText ? \"*\" : join(maskSelectors),\n block: [IGNORE_SELECTOR, ...blockSelectors].join(\",\"),\n };\n }\n\n /**\n * Masks one piece of page text. The recorder calls this for every text the mask selector\n * matches.\n * @param text The node's text.\n * @param element The element that holds the text, or null.\n * @returns The text to record.\n */\n private readonly maskText = (text: string, element: Element | null): string => {\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const forced = maskSelectors.length > 0 && element?.closest(maskSelectors.join(\",\"));\n\n // With maskText off, the recorder only calls us for text under a mask selector.\n if (maskText && !forced && element?.closest(`[${REPLAY_UNMASK_ATTRIBUTE}]`)) {\n return text;\n }\n\n return text.replace(/\\S/g, MASK_CHARACTER);\n };\n\n /**\n * Masks an input value. The result always has the same length.\n * @param text The input's value.\n * @returns The text to record.\n */\n private readonly maskInput = (text: string): string => (text === \"\" ? \"\" : MASKED_INPUT);\n\n /**\n * Strips what the recorder's own masking misses: the query string of the page URL, and text\n * sitting directly in a shadow root that changed after the snapshot.\n * @param event Recorder event.\n */\n private scrub(event: ReplayEvent): void {\n const { data } = event as { data?: ScrubData };\n\n if (!data) {\n return;\n }\n\n if (event.type === META_EVENT) {\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n if (typeof data.href === \"string\" && !this.ctx.config.capture.fullUrls) {\n data.href = data.href.split(/[?#]/)[0];\n }\n return;\n }\n\n if (event.type !== INCREMENTAL_EVENT || data.source !== MUTATION_SOURCE) {\n return;\n }\n\n for (const change of data.texts ?? []) {\n change.value = this.shadowText(change.value, change.id);\n }\n\n for (const add of data.adds ?? []) {\n if (add.node?.type === TEXT_NODE) {\n // The recorder holds on to this node object, so change a copy.\n add.node = {\n ...add.node,\n textContent: this.shadowText(add.node.textContent, add.node.id),\n };\n }\n }\n }\n\n /**\n * Masks text that sits directly in a shadow root. The recorder masks it in a full snapshot\n * but not in later mutations.\n * @param text Text from the mutation.\n * @param id The recorder's id for the text node.\n * @returns The text to record.\n */\n private shadowText(text: unknown, id: number): unknown {\n const node = this.record?.mirror?.getNode(id) as Node | null | undefined;\n\n // Text with an element parent has already been through the recorder's mask function.\n if (typeof text !== \"string\" || !node || node.parentElement) {\n return text;\n }\n\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const host = (node.parentNode as ShadowRoot | null)?.host ?? null;\n\n if (maskText) {\n return this.maskText(text, host);\n }\n\n return maskSelectors.length > 0 && host?.closest(maskSelectors.join(\",\"))\n ? text.replace(/\\S/g, MASK_CHARACTER)\n : text;\n }\n\n /**\n * Vets a request from the recorder's network plugin.\n * @param request The plugin's request.\n * @returns The request to record, or undefined to skip it.\n */\n private readonly transformRequest: ReplayPluginTools[\"transformRequest\"] = (request) => {\n // The plugin calls this from inside its fetch wrapper, so a throw here could reach the\n // app's request.\n try {\n const { capture } = this.ctx.config;\n const url = request.name;\n\n // The plugin calls us after the request, outside the library-request scope, so also check\n // the ignore list. It has every library endpoint, including the replay one. Otherwise a\n // recorded upload becomes a new event, which becomes a new upload.\n if (isLibraryRequest() || matchesAny(url, capture.ignoreUrls)) {\n return undefined;\n }\n\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n return capture.fullUrls ? request : { ...request, name: url.split(/[?#]/)[0] };\n } catch (error) {\n this.onFault(error);\n return undefined;\n }\n };\n\n /**\n * Receives one event from the recorder, which calls this from its observers.\n * @param event Recorder event.\n * @param isCheckout True for the events of a new full snapshot.\n */\n private readonly emit = (event: ReplayEvent, isCheckout?: boolean): void => {\n try {\n this.scrub(event);\n\n // Stringify once: we need the text for the upload and for the size limit anyway.\n const text = JSON.stringify(event);\n\n if (this.live) {\n this.uploader.push([text]);\n return;\n }\n\n if (this.buffer.add(text, event.type, isCheckout === true) && !this.starvedReported) {\n this.starvedReported = true;\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n \"One part of the replay is above replay.maxBufferBytes. The buffer is empty until the next full snapshot. The replay of an error in that time starts at the error, with no events from before it. Raise the limit, or block a large element with replay.blockSelectors.\",\n );\n }\n } catch (error) {\n this.onFault(error);\n }\n };\n\n /**\n * Reports an error from the recorder, or from serializing an event.\n * @param error What the recorder caught.\n */\n private readonly onFault = (error: unknown): void => {\n this.ctx.diagnostics.report(\n \"capture.record_failed\",\n \"The replay recorder had an error.\",\n undefined,\n error,\n );\n };\n\n /**\n * Starts an upload when an ERROR or FATAL record comes through.\n * @param record The record the runtime emitted.\n */\n private readonly onError = (record: LogRecord): void => {\n const { diagnostics, config } = this.ctx;\n\n diagnostics.guard(\"capture.record_failed\", \"The replay upload did not start.\", () => {\n if (!this.record) {\n return;\n }\n\n const { afterErrorMs, uploadsPerWindow } = config.replay;\n\n // An error during the live period rides along in the same upload and doesn't extend it.\n // That way a stream of errors can't hold the upload open, and the upload limit still bites.\n if (\n this.live ||\n !allowInWindow(\n this.window,\n uploadsPerWindow,\n diagnostics,\n \"replay uploads\",\n config.replay.uploadWindowMs,\n )\n ) {\n return;\n }\n\n const { texts, lost } = this.buffer.take();\n if (lost > 0) {\n diagnostics.report(\n \"capture.rate_limited\",\n `The replay buffer was above replay.maxBufferBytes. The library dropped ${String(lost)} events.`,\n );\n }\n\n const { takeFullSnapshot } = this.record;\n\n // An empty buffer has no full snapshot, and a player can't do anything without one.\n if (texts.length === 0 && !takeFullSnapshot) {\n return;\n }\n\n this.uploader.begin({\n replayId: this.replayId,\n sessionId: String(record.resource[SESSION_ID]),\n tabId: String(record.resource[TAB_ID]),\n });\n this.live = true;\n\n if (texts.length === 0) {\n // We're live, so this snapshot goes straight to the uploader. The real recorder throws\n // here before its start, and without the reset the live period would never end.\n const taken = diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot. The library sends no replay for this error.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n return true;\n },\n );\n\n // Nothing went out, so drop what a half-done snapshot left and give the slot back.\n // The uploader's open segment was empty, because live was off until begin().\n if (!taken) {\n this.live = false;\n this.uploader.discardOpen();\n this.window.count = Math.max(0, this.window.count - 1);\n return;\n }\n } else {\n this.uploader.push(texts);\n }\n\n this.liveTimer = setTimeout(this.endLive, afterErrorMs);\n unrefTimer(this.liveTimer);\n });\n };\n\n /** Ends the live period. The buffer starts over with a full snapshot. */\n private readonly endLive = (): void => {\n this.liveTimer = undefined;\n this.live = false;\n this.uploader.flush();\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n },\n );\n };\n\n /**\n * Reports why the replay is off, once per document.\n * @param message Report text.\n */\n private reportOnce(message: string): void {\n const { once } = this.ctx;\n\n if (!once.replay) {\n once.replay = true;\n this.ctx.diagnostics.report(\"capture.install_failed\", message);\n }\n }\n}\n"],"mappings":"A,2VAMA,IAAMA,EAAa,EAGb0B,EAAa,EAGNC,EAAb,KAA0B,CAsBxB,YAAY,EAAyC,CAAxBP,EAAA,EAAA,KAAA,WAAA,IAAA,EAAA,EApB7BA,EAAA,EAAA,KAAA,QAA4B,CAAC,CAAA,EAG7BA,EAAA,EAAA,KAAA,QAA0B,CAAC,CAAA,EAG3BA,EAAA,EAAA,KAAA,QAAgB,CAAA,EAMhBA,EAAA,EAAA,KAAA,UAAkB,EAAA,EAGlBA,EAAA,EAAA,KAAA,OAAe,CAAA,EAKc,KAAA,SAAAQ,CAAyB,CAStD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C,GAAM,CAAE,QAAS,KAAK,IAEjByF,EAAK,SACR,EAAK,OAAS,GACd,KAAK,IAAI,YAAY,OAAO,yBAA0BC,CAAO,EAEjE,CACF,E"}
1
+ {"version":3,"file":"replay-QOFBpAXh.cjs","names":["META_EVENT","withDeadline","HEADER_CONTENT_TYPE","CONTENT_TYPE_JSON","HEADER_BATCH_ID","HEADER_ATTEMPT","gzip","HEADER_CONTENT_ENCODING","ENCODING_GZIP","runAsLibraryRequest","isLibraryRequest","matchesAny","allowInWindow","newId","REPLAY_ID_KEY","IGNORE_SELECTOR","require_constants","require_identity","require_library_request","require_unref","require_defineProperty","require_compression","require_deadline","require_storm","require_types","META_EVENT$1","KEPT_PARTS","ReplayBuffer","maxBytes","opens","isCheckout","type","last","text","limit","taken","part","size","CREDENTIAL_STATUSES","UNKNOWN_ERROR","STATUS_TOO_MANY","STATUS_SERVER_FAULT","ReplayUploader","config","diagnostics","ids","texts","maxSegmentBytes","maxSegmentEvents","flushIntervalMs","payload","segment","dropped","oldest","result","attempt","generation","replay","wait","delivery","source","timeoutMs","onSegment","error","endpoint","controller","timer","given","headers","_count","head","body","zipped","response","SESSION_ID","TAB_ID","MASK_CHARACTER","RECORD_OPTION_KEYS","MASK_EACH_INPUT","MASKED_INPUT","META_EVENT","INCREMENTAL_EVENT","MUTATION_SOURCE","TEXT_NODE","ReplayCapture","forced","maskSelectors","element","maskText","url","request","capture","event","uploadsPerWindow","lost","takeFullSnapshot","record","afterErrorMs","ctx","loader","selectors","loaded","tools","made","plugins","make","extra","ignored","key","value","stopRecorder","plugin","running","selector","blockSelectors","list","data","change","add","node","id","host","once","message"],"sources":["../src/capture/replay-buffer.ts","../src/capture/replay-upload.ts","../src/capture/replay.ts"],"sourcesContent":["// src/capture/replay-buffer.ts\n//\n// Keeps the recent session replay events in memory as JSON text. Events are grouped into\n// parts, and every part starts with a full snapshot, so a player can start from any of them.\n\n/** Event type of the meta event. The recorder sends it right before a full snapshot. */\nconst META_EVENT = 4;\n\n/** How many parts we keep. With a snapshot every half window, 3 parts cover a full window. */\nconst KEPT_PARTS = 3;\n\n/** Size-limited ring of recent replay events. */\nexport class ReplayBuffer {\n /** Events per part, as JSON text. The last part is the open one. */\n private parts: string[][] = [];\n\n /** Size of each part: the sum of its text lengths. */\n private sizes: number[] = [];\n\n /** Size of all parts together. */\n private total = 0;\n\n /**\n * True after the buffer had to drop its only part. Everything up to the next full snapshot\n * has no snapshot in front of it, which makes it useless to a player.\n */\n private starved = false;\n\n /** Events dropped by the size limit since the last take. */\n private lost = 0;\n\n /**\n * @param maxBytes Returns the size limit for all parts together.\n */\n constructor(private readonly maxBytes: () => number) {}\n\n /**\n * Adds one event.\n * @param text The event as JSON text.\n * @param type The recorder's event type.\n * @param isCheckout True for the events of a new full snapshot.\n * @returns True if this event made the buffer drop its only part.\n */\n add(text: string, type: number, isCheckout: boolean): boolean {\n // The meta event and the snapshot both carry the flag, but only the meta event opens a part.\n const opens = isCheckout && type === META_EVENT;\n\n if (this.starved && !opens) {\n this.lost++;\n return false;\n }\n\n if (opens || this.parts.length === 0) {\n this.starved = false;\n this.parts.push([]);\n this.sizes.push(0);\n\n if (this.parts.length > KEPT_PARTS) {\n this.dropOldest();\n }\n }\n\n const last = this.parts.length - 1;\n this.parts[last].push(text);\n this.sizes[last] += text.length;\n this.total += text.length;\n\n const limit = this.maxBytes();\n while (this.total > limit && this.parts.length > 0) {\n // Nothing with a snapshot comes after the last part, so once it goes the events that\n // follow can't be played.\n this.starved = this.parts.length === 1;\n this.lost += this.dropOldest();\n }\n\n return this.starved;\n }\n\n /**\n * Returns every event in order with the dropped count, and empties the buffer. A starved\n * buffer stays starved, because the events after a take still have no snapshot in front.\n * @returns The events as JSON text, and how many events the size limit dropped.\n */\n take(): { texts: string[]; lost: number } {\n const taken = { texts: this.parts.flat(), lost: this.lost };\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.lost = 0;\n return taken;\n }\n\n /** Empties the buffer and its dropped count, so the next upload doesn't report old drops. */\n clear(): void {\n this.parts = [];\n this.sizes = [];\n this.total = 0;\n this.starved = false;\n this.lost = 0;\n }\n\n /**\n * Removes the oldest part.\n * @returns The number of events in that part.\n */\n private dropOldest(): number {\n const [part] = this.parts.splice(0, 1);\n const [size] = this.sizes.splice(0, 1);\n this.total -= size;\n return part.length;\n }\n}\n","// src/capture/replay-upload.ts\n//\n// Cuts session replay events into segments and sends them. A segment closes on an event count,\n// on a size, or after a wait. Only one segment is in flight at a time, which keeps them in\n// order. Segments live in memory only, and the exit flush doesn't send them.\n\nimport {\n COMPRESSION_THRESHOLD_BYTES,\n CONTENT_TYPE_JSON,\n ENCODING_GZIP,\n HEADER_ATTEMPT,\n HEADER_BATCH_ID,\n HEADER_CONTENT_ENCODING,\n HEADER_CONTENT_TYPE,\n} from \"../constants\";\nimport type { Diagnostics } from \"../core/diagnostics\";\nimport type { ResolvedConfig } from \"../models/config\";\nimport type { ReplaySegment } from \"../models/replay\";\nimport { gzip } from \"../transport/compression\";\nimport { withDeadline } from \"../utils/deadline\";\nimport { runAsLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\n\n/** The ids stamped on every segment of a recording. */\nexport interface ReplayIds {\n /** Recording id. */\n replayId: string;\n /** Session id from the record that triggered the upload. */\n sessionId: string;\n /** Tab id from the record that triggered the upload. */\n tabId: string;\n}\n\n/** Outcome of one send. `retry` means a later attempt might work. */\ntype SendResult = \"sent\" | \"retry\" | \"drop\";\n\n/** Statuses that mean our credentials were rejected. The next attempt re-reads the headers. */\nconst CREDENTIAL_STATUSES = [401, 403];\n\n/** Name used for a thrown value that isn't an Error. Reports only ever show the error name. */\nconst UNKNOWN_ERROR = \"Error\";\n\n/** The server is asking us to slow down. */\nconst STATUS_TOO_MANY = 429;\n\n/** Server faults start here. */\nconst STATUS_SERVER_FAULT = 500;\n\n/** Cuts replay events into segments and sends them in order. */\nexport class ReplayUploader {\n /** Events in the open segment, as JSON text. */\n private open: string[] = [];\n\n /** Size of the open segment. */\n private openBytes = 0;\n\n /** Closes a segment that didn't fill up in time. */\n private flushTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Closed segments waiting to be sent. The one in flight isn't in here. */\n private queue: ReplaySegment[] = [];\n\n /** Total size of the queued segments. */\n private queueBytes = 0;\n\n /** True while a segment is in flight or waiting for its next attempt. */\n private busy = false;\n\n /** Timer for the in-flight segment's next attempt. */\n private retryTimer: ReturnType<typeof setTimeout> | undefined;\n\n /** Ids for the segments we cut next. */\n private ids: ReplayIds | undefined;\n\n /** Sequence number for the recording's next segment. */\n private sequence = 0;\n\n /** Bumped on every stop, so a send that finishes after a stop changes nothing. */\n private generation = 0;\n\n /** Aborts the request in flight. Once stopped, the uploader must not send anything else. */\n private inFlight: AbortController | undefined;\n\n /**\n * @param config Returns the current configuration.\n * @param diagnostics Diagnostics reporter.\n */\n constructor(\n private readonly config: () => ResolvedConfig,\n private readonly diagnostics: Diagnostics,\n ) {}\n\n /**\n * Sets the ids for the segments that follow. A new recording restarts the sequence at 0.\n * @param ids Ids of the recording and of the record that triggered the upload.\n */\n begin(ids: ReplayIds): void {\n if (ids.replayId !== this.ids?.replayId) {\n this.sequence = 0;\n }\n\n this.ids = ids;\n }\n\n /**\n * Adds events. A full segment closes right away, a partial one closes after the wait.\n * @param texts The events as JSON text, in order.\n */\n push(texts: readonly string[]): void {\n const { maxSegmentEvents, maxSegmentBytes, flushIntervalMs } = this.config().replay;\n\n for (const text of texts) {\n // If this event doesn't fit, close the segment first. A huge event ends up in its own.\n if (this.open.length > 0 && this.openBytes + text.length > maxSegmentBytes) {\n this.flush();\n }\n\n this.open.push(text);\n this.openBytes += text.length;\n\n if (this.open.length >= maxSegmentEvents || this.openBytes >= maxSegmentBytes) {\n this.flush();\n }\n }\n\n if (this.open.length > 0 && this.flushTimer === undefined) {\n this.flushTimer = setTimeout(() => {\n this.flushTimer = undefined;\n this.flush();\n }, flushIntervalMs);\n unrefTimer(this.flushTimer);\n }\n }\n\n /** Closes the open segment and gets it sent. */\n flush(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n\n const { ids } = this;\n if (this.open.length === 0 || !ids) {\n return;\n }\n\n const payload = `[${this.open.join(\",\")}]`;\n const segment: ReplaySegment = {\n \"replay.id\": ids.replayId,\n \"session.id\": ids.sessionId,\n \"tab.id\": ids.tabId,\n \"service.name\": this.config().serviceName,\n sequence: this.sequence++,\n events: this.open.length,\n bytes: payload.length,\n payload,\n };\n this.open = [];\n this.openBytes = 0;\n this.queue.push(segment);\n this.queueBytes += segment.bytes;\n\n let dropped = 0;\n while (this.queueBytes > this.config().replay.maxQueueBytes && this.queue.length > 1) {\n const [oldest] = this.queue.splice(0, 1);\n this.queueBytes -= oldest.bytes;\n dropped++;\n }\n\n if (dropped > 0) {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The replay queue is above replay.maxQueueBytes. The library dropped ${String(dropped)} segments.`,\n );\n }\n\n this.drain();\n }\n\n /**\n * Drops the events of the open segment and keeps the closed ones. A snapshot that fails\n * halfway leaves its first events here, and a lone meta event is useless to a player.\n */\n discardOpen(): void {\n clearTimeout(this.flushTimer);\n this.flushTimer = undefined;\n this.open = [];\n this.openBytes = 0;\n }\n\n /** Drops everything that is waiting. A send still in flight no longer changes any state. */\n stop(): void {\n this.generation++;\n this.inFlight?.abort();\n this.inFlight = undefined;\n clearTimeout(this.retryTimer);\n this.retryTimer = undefined;\n this.discardOpen();\n this.queue = [];\n this.queueBytes = 0;\n this.busy = false;\n }\n\n /** Sends the next segment, unless one is already in flight. */\n private drain(): void {\n if (this.busy || this.queue.length === 0) {\n return;\n }\n\n const [segment] = this.queue.splice(0, 1);\n this.queueBytes -= segment.bytes;\n this.busy = true;\n void this.deliver(segment, 1, this.generation);\n }\n\n /**\n * Sends one segment, backing off before each retry.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n */\n private async deliver(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<void> {\n const result = await this.send(segment, attempt, generation);\n\n if (generation !== this.generation) {\n return;\n }\n\n const { replay, delivery } = this.config();\n if (result === \"retry\" && attempt < replay.maxAttempts) {\n const wait = Math.min(\n delivery.retryBaseDelayMs * 2 ** (attempt - 1),\n delivery.retryMaxDelayMs,\n );\n this.retryTimer = setTimeout(() => {\n this.retryTimer = undefined;\n void this.deliver(segment, attempt + 1, generation);\n }, wait);\n unrefTimer(this.retryTimer);\n return;\n }\n\n if (result !== \"sent\") {\n this.diagnostics.report(\n \"transport.dropped_permanent\",\n `The library dropped the replay segment ${String(segment.sequence)} after ${String(attempt)} attempts.`,\n { \"replay.id\": segment[\"replay.id\"], sequence: segment.sequence },\n );\n }\n\n this.busy = false;\n this.drain();\n }\n\n /**\n * Hands a segment to the app's onSegment function, or posts it to the endpoint. Never throws.\n * @param segment The segment to send.\n * @param attempt Attempt number, starting at 1.\n * @param generation The uploader's generation when the send started.\n * @returns How the send went.\n */\n private async send(\n segment: ReplaySegment,\n attempt: number,\n generation: number,\n ): Promise<SendResult> {\n const config = this.config();\n const { onSegment, endpoint, headers: source } = config.replay;\n const timeoutMs = config.delivery.requestTimeoutMs;\n\n if (onSegment) {\n try {\n // Don't let a callback that never settles block the uploader forever.\n await withDeadline(Promise.resolve(onSegment(segment)), timeoutMs);\n return \"sent\";\n } catch (error) {\n this.diagnostics.report(\n \"capture.record_failed\",\n `The replay.onSegment function threw an error, or it did not end in ${String(timeoutMs)} ms.`,\n undefined,\n error,\n );\n return \"drop\";\n }\n }\n\n // The capture starts only with an endpoint or onSegment, but a later configure() can remove\n // both while a segment waits.\n if (endpoint === null) {\n return \"drop\";\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => {\n controller.abort();\n }, timeoutMs);\n unrefTimer(timer);\n\n try {\n // The replay endpoint only gets replay.headers. The log endpoint's headers may carry a\n // token meant for a different host.\n const given =\n typeof source === \"function\"\n ? await withDeadline(Promise.resolve(source()), timeoutMs)\n : source;\n const headers = new Headers(given ?? {});\n headers.set(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON);\n headers.set(HEADER_BATCH_ID, `${segment[\"replay.id\"]}-${String(segment.sequence)}`);\n headers.set(HEADER_ATTEMPT, String(attempt - 1));\n\n // In the body \"events\" is the event list itself. Its length is the count.\n const { payload, events: _count, ...head } = segment;\n const text = `${JSON.stringify(head).slice(0, -1)},\"events\":${payload}}`;\n let body: string | Uint8Array<ArrayBuffer> = text;\n\n if (config.compression === ENCODING_GZIP && text.length >= COMPRESSION_THRESHOLD_BYTES) {\n const zipped = await gzip(text);\n\n if (zipped) {\n body = zipped;\n headers.set(HEADER_CONTENT_ENCODING, ENCODING_GZIP);\n }\n }\n\n // If we were stopped during the awaits above, send nothing.\n if (generation !== this.generation) {\n return \"drop\";\n }\n\n this.inFlight = controller;\n\n // Network capture skips requests started in this scope. The replay endpoint is also in\n // capture.ignoreUrls, in case some wrapper starts the request later.\n const response = await runAsLibraryRequest(() =>\n fetch(endpoint, {\n method: \"POST\",\n headers,\n body,\n credentials: config.credentials,\n cache: \"no-store\",\n signal: controller.signal,\n }),\n );\n\n if (response.ok) {\n return \"sent\";\n }\n\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay endpoint returned ${String(response.status)}.`,\n );\n\n return CREDENTIAL_STATUSES.includes(response.status) ||\n response.status === STATUS_TOO_MANY ||\n response.status >= STATUS_SERVER_FAULT\n ? \"retry\"\n : \"drop\";\n } catch (error) {\n // A request error's message can contain the URL, and a URL can contain a credential.\n this.diagnostics.report(\n \"transport.http_error\",\n `The replay request failed with ${error instanceof Error ? error.name : UNKNOWN_ERROR}.`,\n );\n return \"retry\";\n } finally {\n clearTimeout(timer);\n this.inFlight = undefined;\n }\n }\n}\n","// src/capture/replay.ts\n//\n// Session replay. The app's recorder package records the DOM, and this capture keeps the recent\n// events in memory. When an ERROR or FATAL record comes through, it uploads the buffer plus a\n// few seconds of what happens next. All text and input values are masked by default.\n\nimport { IGNORE_SELECTOR, REPLAY_ID_KEY, REPLAY_UNMASK_ATTRIBUTE } from \"../constants\";\nimport type { LogRecord } from \"../models/log-record\";\nimport type { ReplayEvent, ReplayPluginTools, ReplayRecord } from \"../models/replay\";\nimport { newId } from \"../utils/identity\";\nimport { isLibraryRequest } from \"../utils/library-request\";\nimport { unrefTimer } from \"../utils/unref\";\nimport { ReplayBuffer } from \"./replay-buffer\";\nimport { ReplayUploader } from \"./replay-upload\";\nimport { allowInWindow, type StormWindow } from \"./storm\";\nimport { type Capture, type CaptureContext, matchesAny } from \"./types\";\n\n/** Resource attribute for the session id. */\nconst SESSION_ID = \"session.id\";\n\n/** Resource attribute for the tab id. */\nconst TAB_ID = \"tab.id\";\n\n/** Every non-space character of masked text becomes this. */\nconst MASK_CHARACTER = \"*\";\n\n/**\n * The replay.recordOptions keys we pass through to the recorder. Everything else the recorder\n * accepts is a mask, block, canvas, plugin or event option, and those are ours to set.\n */\nconst RECORD_OPTION_KEYS = [\n \"sampling\",\n \"slimDOMOptions\",\n \"ignoreClass\",\n \"ignoreSelector\",\n \"ignoreCSSAttributes\",\n \"userTriggeredOnInput\",\n \"recordAfter\",\n \"inlineStylesheet\",\n \"dataURLOptions\",\n];\n\n/**\n * Per-element input mask for the recorder. We don't use its \"mask all inputs\" switch because\n * that list leaves out hidden and file inputs.\n */\nconst MASK_EACH_INPUT = { input: true, textarea: true, select: true };\n\n/** What every masked input value turns into. Fixed length, so it doesn't give away a PIN's. */\nconst MASKED_INPUT = \"********\";\n\n/** Event type of the meta event, which carries the page URL. */\nconst META_EVENT = 4;\n\n/** Event type of an incremental snapshot. */\nconst INCREMENTAL_EVENT = 3;\n\n/** Incremental snapshot source for DOM mutations. */\nconst MUTATION_SOURCE = 0;\n\n/** Node type of a text node in the recorder's serialized nodes. */\nconst TEXT_NODE = 3;\n\n/** The bits of a recorder event we rewrite before keeping it. */\ninterface ScrubData {\n /** Page URL, on a meta event. */\n href?: unknown;\n /** Source of an incremental snapshot. */\n source?: unknown;\n /** Text changes in a mutation. */\n texts?: { id: number; value: unknown }[];\n /** Nodes added by a mutation. */\n adds?: { node?: { id: number; type: number; textContent?: unknown } }[];\n}\n\n/** Records the DOM and uploads the recent events after an error. */\nexport class ReplayCapture implements Capture {\n /** Capture module identifier. */\n readonly name = \"replay\";\n\n /** Recent events. An upload empties it. */\n private readonly buffer: ReplayBuffer;\n\n /** Cuts the events into segments and sends them. */\n private readonly uploader: ReplayUploader;\n\n /** Upload rate limit, so an error storm doesn't upload the page over and over. */\n private readonly window: StormWindow = { start: 0, count: 0 };\n\n /** The recorder's record function. Undefined while the recorder isn't running. */\n private record: ReplayRecord | undefined;\n\n /** Stops the recorder. */\n private stopRecorder: (() => void) | undefined;\n\n /** Id of the current recording. */\n private replayId = \"\";\n\n /** True between install() and uninstall(). */\n private installed = false;\n\n /** True while start() is loading the recorder. */\n private starting = false;\n\n /** Bumped on every stop, so a start that finishes after a stop records nothing. */\n private generation = 0;\n\n /** True right after an error, while new events go straight to the uploader. */\n private live = false;\n\n /** True once we've reported a full snapshot that doesn't fit in the buffer. */\n private starvedReported = false;\n\n /** Ends the live period after an error. */\n private liveTimer: ReturnType<typeof setTimeout> | undefined;\n\n /**\n * @param ctx Capture context: configuration, diagnostics and the runtime hooks.\n */\n constructor(private readonly ctx: CaptureContext) {\n this.buffer = new ReplayBuffer(() => this.ctx.config.replay.maxBufferBytes);\n this.uploader = new ReplayUploader(() => this.ctx.config, this.ctx.diagnostics);\n }\n\n /** Starts listening for error records, and starts the recorder unless consent is still needed. */\n install(): void {\n if (this.installed) {\n return;\n }\n\n this.installed = true;\n this.ctx.onError?.(this.onError);\n\n // If the app called stopReplay(), that still holds after the captures are reinstalled.\n if (this.ctx.replayConsent?.() ?? !this.ctx.config.replay.requireConsent) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n uninstall(): void {\n this.installed = false;\n this.ctx.onError?.(undefined);\n this.stop();\n }\n\n /**\n * Loads the recorder and starts it. Never rejects.\n * @returns A promise that resolves once the recorder is running, or can't run.\n */\n async start(): Promise<void> {\n const { diagnostics } = this.ctx;\n const { loader, endpoint, onSegment, plugins } = this.ctx.config.replay;\n\n if (!this.installed || this.record || this.starting) {\n return;\n }\n\n if (typeof document === \"undefined\") {\n this.reportOnce(\"This context has no document. The session replay is off.\");\n return;\n }\n\n if (!loader || (endpoint === null && !onSegment)) {\n diagnostics.report(\n \"config.invalid\",\n \"The session replay needs replay.loader, and replay.endpoint or replay.onSegment. The session replay is off.\",\n );\n return;\n }\n\n const selectors = this.selectors();\n if (!selectors) {\n return;\n }\n\n const { generation } = this;\n this.starting = true;\n const loaded = await diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load the replay recorder.\",\n loader,\n );\n const tools: ReplayPluginTools = { transformRequest: this.transformRequest };\n const made = await Promise.all(\n plugins.map((make) =>\n diagnostics.guardAsync(\n \"capture.install_failed\",\n \"The library could not load a replay plugin.\",\n () => Promise.resolve(make(tools)),\n ),\n ),\n );\n\n // A stop or an uninstall while we were loading cancels this start.\n if (generation !== this.generation) {\n return;\n }\n\n this.starting = false;\n\n // The loader failed, and the guard has already reported it.\n if (!loaded) {\n return;\n }\n\n const { record } = loaded;\n if (typeof record !== \"function\") {\n diagnostics.report(\n \"capture.install_failed\",\n \"The replay loader gave no record function. The session replay is off.\",\n );\n return;\n }\n\n const config = this.ctx.config.replay;\n diagnostics.guard(\"capture.install_failed\", \"The replay recorder did not start.\", () => {\n const extra: Record<string, unknown> = {};\n const ignored: string[] = [];\n\n for (const [key, value] of Object.entries(config.recordOptions)) {\n if (RECORD_OPTION_KEYS.includes(key)) {\n extra[key] = value;\n } else {\n ignored.push(key);\n }\n }\n\n if (ignored.length > 0) {\n diagnostics.report(\n \"config.invalid\",\n `The library ignores these keys of replay.recordOptions: ${ignored.join(\", \")}. It sets the mask, block, canvas, plugin and event options itself.`,\n );\n }\n\n // The real recorder takes its first snapshot inside record(), so a starve report can come\n // before record() returns.\n this.starvedReported = false;\n\n const stopRecorder = record({\n ...extra,\n emit: this.emit,\n // Take a full snapshot every half window, so the buffer always begins with one.\n checkoutEveryNms: config.bufferMs / 2,\n // The per-element list covers every input type. Passwords are masked no matter what.\n maskAllInputs: false,\n maskInputOptions: config.maskInputs ? MASK_EACH_INPUT : { password: true },\n maskInputFn: this.maskInput,\n maskTextSelector: selectors.mask,\n maskTextFn: this.maskText,\n blockSelector: selectors.block,\n recordCanvas: config.recordCanvas,\n errorHandler: this.onFault,\n plugins: made.filter((plugin) => plugin !== undefined),\n });\n\n // The recorder swallows errors from its own startup and just returns no stop function.\n if (typeof stopRecorder !== \"function\") {\n diagnostics.report(\"capture.install_failed\", \"The replay recorder did not start.\");\n return;\n }\n\n this.stopRecorder = stopRecorder;\n this.record = record;\n this.replayId = newId(this.ctx.diagnostics);\n this.ctx.setContext?.(REPLAY_ID_KEY, this.replayId);\n });\n }\n\n /**\n * Drops the buffer and, if the recorder was running, starts a fresh recording. The runtime\n * calls this on a new session, so the next user never gets the previous user's page.\n */\n reset(): void {\n const running = this.record !== undefined || this.starting;\n\n this.stop();\n if (running) {\n void this.start();\n }\n }\n\n /** Stops the recorder and drops whatever hasn't been sent. */\n stop(): void {\n const { stopRecorder } = this;\n\n this.generation++;\n this.starting = false;\n this.record = undefined;\n this.stopRecorder = undefined;\n this.live = false;\n clearTimeout(this.liveTimer);\n this.liveTimer = undefined;\n this.buffer.clear();\n this.uploader.stop();\n\n if (stopRecorder) {\n this.ctx.setContext?.(REPLAY_ID_KEY, undefined);\n this.ctx.diagnostics.guard(\n \"capture.install_failed\",\n \"The replay recorder did not stop.\",\n stopRecorder,\n );\n }\n }\n\n /**\n * Reads the mask and block selectors. An invalid selector aborts the start: a replay with a\n * missing mask would show text the app meant to hide.\n * @returns The selectors for the recorder, or undefined if one of them is invalid.\n */\n private selectors(): { mask: string | undefined; block: string } | undefined {\n const { maskText, maskSelectors, blockSelectors } = this.ctx.config.replay;\n\n for (const selector of [...maskSelectors, ...blockSelectors]) {\n try {\n document.createDocumentFragment().querySelector(selector);\n } catch (error) {\n this.ctx.diagnostics.report(\n \"config.invalid\",\n `The replay selector ${selector} is not a valid CSS selector. The session replay is off.`,\n undefined,\n error,\n );\n return undefined;\n }\n }\n\n const join = (list: string[]): string | undefined =>\n list.length > 0 ? list.join(\",\") : undefined;\n\n // Click capture skips the ignored regions, so a replay must not show them either. The app\n // can't turn this off.\n return {\n mask: maskText ? \"*\" : join(maskSelectors),\n block: [IGNORE_SELECTOR, ...blockSelectors].join(\",\"),\n };\n }\n\n /**\n * Masks one piece of page text. The recorder calls this for every text the mask selector\n * matches.\n * @param text The node's text.\n * @param element The element that holds the text, or null.\n * @returns The text to record.\n */\n private readonly maskText = (text: string, element: Element | null): string => {\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const forced = maskSelectors.length > 0 && element?.closest(maskSelectors.join(\",\"));\n\n // With maskText off, the recorder only calls us for text under a mask selector.\n if (maskText && !forced && element?.closest(`[${REPLAY_UNMASK_ATTRIBUTE}]`)) {\n return text;\n }\n\n return text.replace(/\\S/g, MASK_CHARACTER);\n };\n\n /**\n * Masks an input value. The result always has the same length.\n * @param text The input's value.\n * @returns The text to record.\n */\n private readonly maskInput = (text: string): string => (text === \"\" ? \"\" : MASKED_INPUT);\n\n /**\n * Strips what the recorder's own masking misses: the query string of the page URL, and text\n * sitting directly in a shadow root that changed after the snapshot.\n * @param event Recorder event.\n */\n private scrub(event: ReplayEvent): void {\n const { data } = event as { data?: ScrubData };\n\n if (!data) {\n return;\n }\n\n if (event.type === META_EVENT) {\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n if (typeof data.href === \"string\" && !this.ctx.config.capture.fullUrls) {\n data.href = data.href.split(/[?#]/)[0];\n }\n return;\n }\n\n if (event.type !== INCREMENTAL_EVENT || data.source !== MUTATION_SOURCE) {\n return;\n }\n\n for (const change of data.texts ?? []) {\n change.value = this.shadowText(change.value, change.id);\n }\n\n for (const add of data.adds ?? []) {\n if (add.node?.type === TEXT_NODE) {\n // The recorder holds on to this node object, so change a copy.\n add.node = {\n ...add.node,\n textContent: this.shadowText(add.node.textContent, add.node.id),\n };\n }\n }\n }\n\n /**\n * Masks text that sits directly in a shadow root. The recorder masks it in a full snapshot\n * but not in later mutations.\n * @param text Text from the mutation.\n * @param id The recorder's id for the text node.\n * @returns The text to record.\n */\n private shadowText(text: unknown, id: number): unknown {\n const node = this.record?.mirror?.getNode(id) as Node | null | undefined;\n\n // Text with an element parent has already been through the recorder's mask function.\n if (typeof text !== \"string\" || !node || node.parentElement) {\n return text;\n }\n\n const { maskText, maskSelectors } = this.ctx.config.replay;\n const host = (node.parentNode as ShadowRoot | null)?.host ?? null;\n\n if (maskText) {\n return this.maskText(text, host);\n }\n\n return maskSelectors.length > 0 && host?.closest(maskSelectors.join(\",\"))\n ? text.replace(/\\S/g, MASK_CHARACTER)\n : text;\n }\n\n /**\n * Vets a request from the recorder's network plugin.\n * @param request The plugin's request.\n * @returns The request to record, or undefined to skip it.\n */\n private readonly transformRequest: ReplayPluginTools[\"transformRequest\"] = (request) => {\n // The plugin calls this from inside its fetch wrapper, so a throw here could reach the\n // app's request.\n try {\n const { capture } = this.ctx.config;\n const url = request.name;\n\n // The plugin calls us after the request, outside the library-request scope, so also check\n // the ignore list. It has every library endpoint, including the replay one. Otherwise a\n // recorded upload becomes a new event, which becomes a new upload.\n if (isLibraryRequest() || matchesAny(url, capture.ignoreUrls)) {\n return undefined;\n }\n\n // A signed URL is a credential. Only keep the query when fullUrls is on.\n return capture.fullUrls ? request : { ...request, name: url.split(/[?#]/)[0] };\n } catch (error) {\n this.onFault(error);\n return undefined;\n }\n };\n\n /**\n * Receives one event from the recorder, which calls this from its observers.\n * @param event Recorder event.\n * @param isCheckout True for the events of a new full snapshot.\n */\n private readonly emit = (event: ReplayEvent, isCheckout?: boolean): void => {\n try {\n this.scrub(event);\n\n // Stringify once: we need the text for the upload and for the size limit anyway.\n const text = JSON.stringify(event);\n\n if (this.live) {\n this.uploader.push([text]);\n return;\n }\n\n if (this.buffer.add(text, event.type, isCheckout === true) && !this.starvedReported) {\n this.starvedReported = true;\n this.ctx.diagnostics.report(\n \"capture.rate_limited\",\n \"One part of the replay is above replay.maxBufferBytes. The buffer is empty until the next full snapshot. The replay of an error in that time starts at the error, with no events from before it. Raise the limit, or block a large element with replay.blockSelectors.\",\n );\n }\n } catch (error) {\n this.onFault(error);\n }\n };\n\n /**\n * Reports an error from the recorder, or from serializing an event.\n * @param error What the recorder caught.\n */\n private readonly onFault = (error: unknown): void => {\n this.ctx.diagnostics.report(\n \"capture.record_failed\",\n \"The replay recorder had an error.\",\n undefined,\n error,\n );\n };\n\n /**\n * Starts an upload when an ERROR or FATAL record comes through.\n * @param record The record the runtime emitted.\n */\n private readonly onError = (record: LogRecord): void => {\n const { diagnostics, config } = this.ctx;\n\n diagnostics.guard(\"capture.record_failed\", \"The replay upload did not start.\", () => {\n if (!this.record) {\n return;\n }\n\n const { afterErrorMs, uploadsPerWindow } = config.replay;\n\n // An error during the live period rides along in the same upload and doesn't extend it.\n // That way a stream of errors can't hold the upload open, and the upload limit still bites.\n if (\n this.live ||\n !allowInWindow(\n this.window,\n uploadsPerWindow,\n diagnostics,\n \"replay uploads\",\n config.replay.uploadWindowMs,\n )\n ) {\n return;\n }\n\n const { texts, lost } = this.buffer.take();\n if (lost > 0) {\n diagnostics.report(\n \"capture.rate_limited\",\n `The replay buffer was above replay.maxBufferBytes. The library dropped ${String(lost)} events.`,\n );\n }\n\n const { takeFullSnapshot } = this.record;\n\n // An empty buffer has no full snapshot, and a player can't do anything without one.\n if (texts.length === 0 && !takeFullSnapshot) {\n return;\n }\n\n this.uploader.begin({\n replayId: this.replayId,\n sessionId: String(record.resource[SESSION_ID]),\n tabId: String(record.resource[TAB_ID]),\n });\n this.live = true;\n\n if (texts.length === 0) {\n // We're live, so this snapshot goes straight to the uploader. The real recorder throws\n // here before its start, and without the reset the live period would never end.\n const taken = diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot. The library sends no replay for this error.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n return true;\n },\n );\n\n // Nothing went out, so drop what a half-done snapshot left and give the slot back.\n // The uploader's open segment was empty, because live was off until begin().\n if (!taken) {\n this.live = false;\n this.uploader.discardOpen();\n this.window.count = Math.max(0, this.window.count - 1);\n return;\n }\n } else {\n this.uploader.push(texts);\n }\n\n this.liveTimer = setTimeout(this.endLive, afterErrorMs);\n unrefTimer(this.liveTimer);\n });\n };\n\n /** Ends the live period. The buffer starts over with a full snapshot. */\n private readonly endLive = (): void => {\n this.liveTimer = undefined;\n this.live = false;\n this.uploader.flush();\n this.ctx.diagnostics.guard(\n \"capture.record_failed\",\n \"The replay recorder did not take a full snapshot.\",\n () => {\n this.record?.takeFullSnapshot?.(true);\n },\n );\n };\n\n /**\n * Reports why the replay is off, once per document.\n * @param message Report text.\n */\n private reportOnce(message: string): void {\n const { once } = this.ctx;\n\n if (!once.replay) {\n once.replay = true;\n this.ctx.diagnostics.report(\"capture.install_failed\", message);\n }\n }\n}\n"],"mappings":"A,2VAMA,IAAMA,EAAa,EAGb0B,EAAa,EAGNC,EAAb,KAA0B,CAsBxB,YAAY,EAAyC,CAAxBP,EAAA,EAAA,KAAA,WAAA,IAAA,EAAA,EApB7BA,EAAA,EAAA,KAAA,QAA4B,CAAC,CAAA,EAG7BA,EAAA,EAAA,KAAA,QAA0B,CAAC,CAAA,EAG3BA,EAAA,EAAA,KAAA,QAAgB,CAAA,EAMhBA,EAAA,EAAA,KAAA,UAAkB,EAAA,EAGlBA,EAAA,EAAA,KAAA,OAAe,CAAA,EAKc,KAAA,SAAAQ,CAAyB,CAStD,IAAI,EAAc,EAAc,EAA8B,CAE5D,IAAMC,EAAQC,GAAcC,IAAS/B,EAErC,GAAI,KAAK,SAAW,CAAC6B,EAEnB,MADA,MAAK,OACE,IAGLA,GAAS,KAAK,MAAM,SAAW,KACjC,KAAK,QAAU,GACf,KAAK,MAAM,KAAK,CAAC,CAAC,EAClB,KAAK,MAAM,KAAK,CAA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";
2
+ import { t } from "./storm-DKlpv0FL.js";
3
3
  import { t as n } from "./defineProperty-s2S8BXUc.js";
4
4
  // src/capture/reports.ts
5
5
  var r = class {
@@ -62,4 +62,4 @@ var r = class {
62
62
  };
63
63
  export { r as ReportCapture };
64
64
 
65
- //# sourceMappingURL=reports-C-thq-bk.js.map
65
+ //# sourceMappingURL=reports--8APRLa-.js.map