@openreplay/tracker 14.0.10-beta.1 → 14.0.10

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 (273) hide show
  1. package/{cjs → dist/cjs}/index.js +27 -49
  2. package/dist/cjs/index.js.map +1 -0
  3. package/{cjs → dist/cjs/main}/app/index.d.ts +38 -6
  4. package/{lib → dist/cjs/main}/app/messages.gen.d.ts +2 -2
  5. package/{lib/app/nodes.d.ts → dist/cjs/main/app/nodes/index.d.ts} +15 -7
  6. package/dist/cjs/main/app/nodes/maintainer.d.ts +28 -0
  7. package/{cjs → dist/cjs/main}/app/observer/iframe_observer.d.ts +1 -1
  8. package/{lib → dist/cjs/main}/app/observer/iframe_offsets.d.ts +1 -1
  9. package/{lib → dist/cjs/main}/app/observer/observer.d.ts +6 -0
  10. package/{lib → dist/cjs/main}/app/observer/top_observer.d.ts +6 -2
  11. package/{cjs → dist/cjs/main}/app/sanitizer.d.ts +5 -2
  12. package/{cjs → dist/cjs/main}/app/session.d.ts +6 -3
  13. package/{lib → dist/cjs/main}/index.d.ts +2 -2
  14. package/{lib → dist/cjs/main}/modules/attributeSender.d.ts +5 -2
  15. package/{cjs → dist/cjs/main}/modules/conditionsManager.d.ts +1 -1
  16. package/{cjs → dist/cjs/main}/modules/tagWatcher.d.ts +8 -4
  17. package/{lib → dist/cjs/main}/modules/userTesting/SignalManager.d.ts +2 -2
  18. package/{lib → dist/cjs/main}/utils.d.ts +4 -3
  19. package/dist/lib/index.js +9323 -0
  20. package/dist/lib/index.js.map +1 -0
  21. package/{lib → dist/lib/main}/app/index.d.ts +38 -6
  22. package/{cjs → dist/lib/main}/app/messages.gen.d.ts +2 -2
  23. package/{cjs/app/nodes.d.ts → dist/lib/main/app/nodes/index.d.ts} +15 -7
  24. package/dist/lib/main/app/nodes/maintainer.d.ts +28 -0
  25. package/{lib → dist/lib/main}/app/observer/iframe_observer.d.ts +1 -1
  26. package/{cjs → dist/lib/main}/app/observer/iframe_offsets.d.ts +1 -1
  27. package/{cjs → dist/lib/main}/app/observer/observer.d.ts +6 -0
  28. package/{cjs → dist/lib/main}/app/observer/top_observer.d.ts +6 -2
  29. package/{lib → dist/lib/main}/app/sanitizer.d.ts +5 -2
  30. package/{lib → dist/lib/main}/app/session.d.ts +6 -3
  31. package/{cjs → dist/lib/main}/index.d.ts +2 -2
  32. package/{cjs → dist/lib/main}/modules/attributeSender.d.ts +5 -2
  33. package/{lib → dist/lib/main}/modules/conditionsManager.d.ts +1 -1
  34. package/{lib → dist/lib/main}/modules/tagWatcher.d.ts +8 -4
  35. package/{cjs → dist/lib/main}/modules/userTesting/SignalManager.d.ts +2 -2
  36. package/{cjs → dist/lib/main}/utils.d.ts +4 -3
  37. package/package.json +29 -10
  38. package/.eslintignore +0 -11
  39. package/.nvmrc +0 -1
  40. package/.prettierignore +0 -1
  41. package/CHANGELOG.md +0 -297
  42. package/bun.lockb +0 -0
  43. package/cjs/app/canvas.js +0 -204
  44. package/cjs/app/guards.js +0 -37
  45. package/cjs/app/index.js +0 -1366
  46. package/cjs/app/logger.js +0 -37
  47. package/cjs/app/messages.gen.js +0 -702
  48. package/cjs/app/nodes.js +0 -110
  49. package/cjs/app/observer/iframe_observer.js +0 -35
  50. package/cjs/app/observer/iframe_offsets.js +0 -56
  51. package/cjs/app/observer/observer.js +0 -352
  52. package/cjs/app/observer/shadow_root_observer.js +0 -24
  53. package/cjs/app/observer/top_observer.js +0 -134
  54. package/cjs/app/sanitizer.js +0 -82
  55. package/cjs/app/session.js +0 -140
  56. package/cjs/app/ticker.js +0 -48
  57. package/cjs/common/interaction.js +0 -2
  58. package/cjs/common/messages.gen.js +0 -4
  59. package/cjs/modules/attributeSender.js +0 -51
  60. package/cjs/modules/axiosSpy.js +0 -122
  61. package/cjs/modules/conditionsManager.js +0 -343
  62. package/cjs/modules/connection.js +0 -15
  63. package/cjs/modules/console.js +0 -127
  64. package/cjs/modules/constructedStyleSheets.js +0 -138
  65. package/cjs/modules/cssrules.js +0 -99
  66. package/cjs/modules/exception.js +0 -85
  67. package/cjs/modules/featureFlags.js +0 -89
  68. package/cjs/modules/focus.js +0 -45
  69. package/cjs/modules/fonts.js +0 -57
  70. package/cjs/modules/img.js +0 -110
  71. package/cjs/modules/input.js +0 -203
  72. package/cjs/modules/mouse.js +0 -195
  73. package/cjs/modules/network.js +0 -244
  74. package/cjs/modules/performance.js +0 -53
  75. package/cjs/modules/scroll.js +0 -84
  76. package/cjs/modules/selection.js +0 -37
  77. package/cjs/modules/tabs.js +0 -13
  78. package/cjs/modules/tagWatcher.js +0 -76
  79. package/cjs/modules/timing.js +0 -173
  80. package/cjs/modules/userTesting/SignalManager.js +0 -83
  81. package/cjs/modules/userTesting/dnd.js +0 -40
  82. package/cjs/modules/userTesting/index.js +0 -464
  83. package/cjs/modules/userTesting/recorder.js +0 -101
  84. package/cjs/modules/userTesting/styles.js +0 -266
  85. package/cjs/modules/userTesting/utils.js +0 -87
  86. package/cjs/modules/viewport.js +0 -43
  87. package/cjs/package.json +0 -1
  88. package/cjs/utils.js +0 -230
  89. package/coverage/clover.xml +0 -4304
  90. package/coverage/coverage-final.json +0 -55
  91. package/coverage/lcov-report/base.css +0 -224
  92. package/coverage/lcov-report/block-navigation.js +0 -87
  93. package/coverage/lcov-report/favicon.png +0 -0
  94. package/coverage/lcov-report/index.html +0 -206
  95. package/coverage/lcov-report/main/app/canvas.ts.html +0 -712
  96. package/coverage/lcov-report/main/app/guards.ts.html +0 -232
  97. package/coverage/lcov-report/main/app/index.html +0 -236
  98. package/coverage/lcov-report/main/app/index.ts.html +0 -3955
  99. package/coverage/lcov-report/main/app/logger.ts.html +0 -211
  100. package/coverage/lcov-report/main/app/messages.gen.ts.html +0 -3034
  101. package/coverage/lcov-report/main/app/nodes.ts.html +0 -406
  102. package/coverage/lcov-report/main/app/observer/iframe_observer.ts.html +0 -148
  103. package/coverage/lcov-report/main/app/observer/iframe_offsets.ts.html +0 -289
  104. package/coverage/lcov-report/main/app/observer/index.html +0 -161
  105. package/coverage/lcov-report/main/app/observer/shadow_root_observer.ts.html +0 -142
  106. package/coverage/lcov-report/main/app/observer/top_observer.ts.html +0 -541
  107. package/coverage/lcov-report/main/app/sanitizer.ts.html +0 -403
  108. package/coverage/lcov-report/main/app/session.ts.html +0 -622
  109. package/coverage/lcov-report/main/app/ticker.ts.html +0 -250
  110. package/coverage/lcov-report/main/index.html +0 -131
  111. package/coverage/lcov-report/main/index.ts.html +0 -1597
  112. package/coverage/lcov-report/main/modules/Network/beaconProxy.ts.html +0 -400
  113. package/coverage/lcov-report/main/modules/Network/fetchProxy.ts.html +0 -1075
  114. package/coverage/lcov-report/main/modules/Network/index.html +0 -191
  115. package/coverage/lcov-report/main/modules/Network/index.ts.html +0 -244
  116. package/coverage/lcov-report/main/modules/Network/networkMessage.ts.html +0 -400
  117. package/coverage/lcov-report/main/modules/Network/utils.ts.html +0 -709
  118. package/coverage/lcov-report/main/modules/Network/xhrProxy.ts.html +0 -877
  119. package/coverage/lcov-report/main/modules/attributeSender.ts.html +0 -241
  120. package/coverage/lcov-report/main/modules/axiosSpy.ts.html +0 -709
  121. package/coverage/lcov-report/main/modules/conditionsManager.ts.html +0 -1381
  122. package/coverage/lcov-report/main/modules/connection.ts.html +0 -160
  123. package/coverage/lcov-report/main/modules/console.ts.html +0 -541
  124. package/coverage/lcov-report/main/modules/constructedStyleSheets.ts.html +0 -571
  125. package/coverage/lcov-report/main/modules/cssrules.ts.html +0 -418
  126. package/coverage/lcov-report/main/modules/exception.ts.html +0 -385
  127. package/coverage/lcov-report/main/modules/featureFlags.ts.html +0 -415
  128. package/coverage/lcov-report/main/modules/focus.ts.html +0 -220
  129. package/coverage/lcov-report/main/modules/fonts.ts.html +0 -289
  130. package/coverage/lcov-report/main/modules/img.ts.html +0 -436
  131. package/coverage/lcov-report/main/modules/index.html +0 -431
  132. package/coverage/lcov-report/main/modules/input.ts.html +0 -826
  133. package/coverage/lcov-report/main/modules/mouse.ts.html +0 -826
  134. package/coverage/lcov-report/main/modules/network.ts.html +0 -1123
  135. package/coverage/lcov-report/main/modules/performance.ts.html +0 -367
  136. package/coverage/lcov-report/main/modules/scroll.ts.html +0 -364
  137. package/coverage/lcov-report/main/modules/selection.ts.html +0 -202
  138. package/coverage/lcov-report/main/modules/tabs.ts.html +0 -124
  139. package/coverage/lcov-report/main/modules/tagWatcher.ts.html +0 -337
  140. package/coverage/lcov-report/main/modules/timing.ts.html +0 -877
  141. package/coverage/lcov-report/main/modules/userTesting/SignalManager.ts.html +0 -370
  142. package/coverage/lcov-report/main/modules/userTesting/dnd.ts.html +0 -220
  143. package/coverage/lcov-report/main/modules/userTesting/index.html +0 -191
  144. package/coverage/lcov-report/main/modules/userTesting/index.ts.html +0 -1909
  145. package/coverage/lcov-report/main/modules/userTesting/recorder.ts.html +0 -430
  146. package/coverage/lcov-report/main/modules/userTesting/styles.ts.html +0 -937
  147. package/coverage/lcov-report/main/modules/userTesting/utils.ts.html +0 -364
  148. package/coverage/lcov-report/main/modules/viewport.ts.html +0 -250
  149. package/coverage/lcov-report/main/utils.ts.html +0 -814
  150. package/coverage/lcov-report/prettify.css +0 -1
  151. package/coverage/lcov-report/prettify.js +0 -2
  152. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  153. package/coverage/lcov-report/sorter.js +0 -196
  154. package/coverage/lcov-report/webworker/BatchWriter.ts.html +0 -499
  155. package/coverage/lcov-report/webworker/MessageEncoder.gen.ts.html +0 -1021
  156. package/coverage/lcov-report/webworker/PrimitiveEncoder.ts.html +0 -436
  157. package/coverage/lcov-report/webworker/QueueSender.ts.html +0 -547
  158. package/coverage/lcov-report/webworker/index.html +0 -176
  159. package/coverage/lcov-report/webworker/index.ts.html +0 -667
  160. package/coverage/lcov.info +0 -8425
  161. package/jest.config.js +0 -13
  162. package/lib/app/canvas.js +0 -202
  163. package/lib/app/guards.js +0 -26
  164. package/lib/app/index.js +0 -1336
  165. package/lib/app/logger.js +0 -33
  166. package/lib/app/messages.gen.js +0 -622
  167. package/lib/app/nodes.js +0 -107
  168. package/lib/app/observer/iframe_observer.js +0 -29
  169. package/lib/app/observer/iframe_offsets.js +0 -53
  170. package/lib/app/observer/observer.js +0 -349
  171. package/lib/app/observer/shadow_root_observer.js +0 -18
  172. package/lib/app/observer/top_observer.js +0 -128
  173. package/lib/app/sanitizer.js +0 -77
  174. package/lib/app/session.js +0 -137
  175. package/lib/app/ticker.js +0 -45
  176. package/lib/common/interaction.js +0 -1
  177. package/lib/common/messages.gen.js +0 -3
  178. package/lib/common/tsconfig.tsbuildinfo +0 -1
  179. package/lib/index.js +0 -423
  180. package/lib/modules/attributeSender.js +0 -46
  181. package/lib/modules/axiosSpy.js +0 -119
  182. package/lib/modules/conditionsManager.js +0 -340
  183. package/lib/modules/connection.js +0 -12
  184. package/lib/modules/console.js +0 -124
  185. package/lib/modules/constructedStyleSheets.js +0 -133
  186. package/lib/modules/cssrules.js +0 -97
  187. package/lib/modules/exception.js +0 -76
  188. package/lib/modules/featureFlags.js +0 -86
  189. package/lib/modules/focus.js +0 -42
  190. package/lib/modules/fonts.js +0 -54
  191. package/lib/modules/img.js +0 -107
  192. package/lib/modules/input.js +0 -198
  193. package/lib/modules/mouse.js +0 -192
  194. package/lib/modules/network.js +0 -238
  195. package/lib/modules/performance.js +0 -49
  196. package/lib/modules/scroll.js +0 -81
  197. package/lib/modules/selection.js +0 -35
  198. package/lib/modules/tabs.js +0 -10
  199. package/lib/modules/tagWatcher.js +0 -73
  200. package/lib/modules/timing.js +0 -170
  201. package/lib/modules/userTesting/SignalManager.js +0 -80
  202. package/lib/modules/userTesting/dnd.js +0 -37
  203. package/lib/modules/userTesting/index.js +0 -435
  204. package/lib/modules/userTesting/recorder.js +0 -97
  205. package/lib/modules/userTesting/styles.js +0 -263
  206. package/lib/modules/userTesting/utils.js +0 -79
  207. package/lib/modules/viewport.js +0 -40
  208. package/lib/utils.js +0 -211
  209. package/rollup.config.js +0 -12
  210. package/scripts/checkver.cjs +0 -7
  211. package/tsconfig-base.json +0 -16
  212. /package/{cjs → dist/cjs}/common/interaction.d.ts +0 -0
  213. /package/{cjs → dist/cjs}/common/messages.gen.d.ts +0 -0
  214. /package/{cjs → dist/cjs/main}/app/canvas.d.ts +0 -0
  215. /package/{cjs → dist/cjs/main}/app/guards.d.ts +0 -0
  216. /package/{cjs → dist/cjs/main}/app/logger.d.ts +0 -0
  217. /package/{cjs → dist/cjs/main}/app/observer/shadow_root_observer.d.ts +0 -0
  218. /package/{cjs → dist/cjs/main}/app/ticker.d.ts +0 -0
  219. /package/{cjs → dist/cjs/main}/modules/axiosSpy.d.ts +0 -0
  220. /package/{cjs → dist/cjs/main}/modules/connection.d.ts +0 -0
  221. /package/{cjs → dist/cjs/main}/modules/console.d.ts +0 -0
  222. /package/{cjs → dist/cjs/main}/modules/constructedStyleSheets.d.ts +0 -0
  223. /package/{cjs → dist/cjs/main}/modules/cssrules.d.ts +0 -0
  224. /package/{cjs → dist/cjs/main}/modules/exception.d.ts +0 -0
  225. /package/{cjs → dist/cjs/main}/modules/featureFlags.d.ts +0 -0
  226. /package/{cjs → dist/cjs/main}/modules/focus.d.ts +0 -0
  227. /package/{cjs → dist/cjs/main}/modules/fonts.d.ts +0 -0
  228. /package/{cjs → dist/cjs/main}/modules/img.d.ts +0 -0
  229. /package/{cjs → dist/cjs/main}/modules/input.d.ts +0 -0
  230. /package/{cjs → dist/cjs/main}/modules/mouse.d.ts +0 -0
  231. /package/{cjs → dist/cjs/main}/modules/network.d.ts +0 -0
  232. /package/{cjs → dist/cjs/main}/modules/performance.d.ts +0 -0
  233. /package/{cjs → dist/cjs/main}/modules/scroll.d.ts +0 -0
  234. /package/{cjs → dist/cjs/main}/modules/selection.d.ts +0 -0
  235. /package/{cjs → dist/cjs/main}/modules/tabs.d.ts +0 -0
  236. /package/{cjs → dist/cjs/main}/modules/timing.d.ts +0 -0
  237. /package/{cjs → dist/cjs/main}/modules/userTesting/dnd.d.ts +0 -0
  238. /package/{cjs → dist/cjs/main}/modules/userTesting/index.d.ts +0 -0
  239. /package/{cjs → dist/cjs/main}/modules/userTesting/recorder.d.ts +0 -0
  240. /package/{cjs → dist/cjs/main}/modules/userTesting/styles.d.ts +0 -0
  241. /package/{cjs → dist/cjs/main}/modules/userTesting/utils.d.ts +0 -0
  242. /package/{cjs → dist/cjs/main}/modules/viewport.d.ts +0 -0
  243. /package/{lib → dist/lib}/common/interaction.d.ts +0 -0
  244. /package/{lib → dist/lib}/common/messages.gen.d.ts +0 -0
  245. /package/{lib → dist/lib/main}/app/canvas.d.ts +0 -0
  246. /package/{lib → dist/lib/main}/app/guards.d.ts +0 -0
  247. /package/{lib → dist/lib/main}/app/logger.d.ts +0 -0
  248. /package/{lib → dist/lib/main}/app/observer/shadow_root_observer.d.ts +0 -0
  249. /package/{lib → dist/lib/main}/app/ticker.d.ts +0 -0
  250. /package/{lib → dist/lib/main}/modules/axiosSpy.d.ts +0 -0
  251. /package/{lib → dist/lib/main}/modules/connection.d.ts +0 -0
  252. /package/{lib → dist/lib/main}/modules/console.d.ts +0 -0
  253. /package/{lib → dist/lib/main}/modules/constructedStyleSheets.d.ts +0 -0
  254. /package/{lib → dist/lib/main}/modules/cssrules.d.ts +0 -0
  255. /package/{lib → dist/lib/main}/modules/exception.d.ts +0 -0
  256. /package/{lib → dist/lib/main}/modules/featureFlags.d.ts +0 -0
  257. /package/{lib → dist/lib/main}/modules/focus.d.ts +0 -0
  258. /package/{lib → dist/lib/main}/modules/fonts.d.ts +0 -0
  259. /package/{lib → dist/lib/main}/modules/img.d.ts +0 -0
  260. /package/{lib → dist/lib/main}/modules/input.d.ts +0 -0
  261. /package/{lib → dist/lib/main}/modules/mouse.d.ts +0 -0
  262. /package/{lib → dist/lib/main}/modules/network.d.ts +0 -0
  263. /package/{lib → dist/lib/main}/modules/performance.d.ts +0 -0
  264. /package/{lib → dist/lib/main}/modules/scroll.d.ts +0 -0
  265. /package/{lib → dist/lib/main}/modules/selection.d.ts +0 -0
  266. /package/{lib → dist/lib/main}/modules/tabs.d.ts +0 -0
  267. /package/{lib → dist/lib/main}/modules/timing.d.ts +0 -0
  268. /package/{lib → dist/lib/main}/modules/userTesting/dnd.d.ts +0 -0
  269. /package/{lib → dist/lib/main}/modules/userTesting/index.d.ts +0 -0
  270. /package/{lib → dist/lib/main}/modules/userTesting/recorder.d.ts +0 -0
  271. /package/{lib → dist/lib/main}/modules/userTesting/styles.d.ts +0 -0
  272. /package/{lib → dist/lib/main}/modules/userTesting/utils.d.ts +0 -0
  273. /package/{lib → dist/lib/main}/modules/viewport.d.ts +0 -0
package/lib/app/index.js DELETED
@@ -1,1336 +0,0 @@
1
- import { gzip } from 'fflate';
2
- import AttributeSender from '../modules/attributeSender.js';
3
- import ConditionsManager from '../modules/conditionsManager.js';
4
- import FeatureFlags from '../modules/featureFlags.js';
5
- import { deviceMemory, jsHeapSizeLimit } from '../modules/performance.js';
6
- import TagWatcher from '../modules/tagWatcher.js';
7
- import UserTestManager from '../modules/userTesting/index.js';
8
- import { adjustTimeOrigin, createEventListener, deleteEventListener, now, requestIdleCb, simpleMerge, } from '../utils.js';
9
- import CanvasRecorder from './canvas.js';
10
- import Logger, { LogLevel } from './logger.js';
11
- import { Metadata, TabChange, TabData, TagTrigger, Timestamp, UserID, WSChannel, } from './messages.gen.js';
12
- import Nodes from './nodes.js';
13
- import Observer from './observer/top_observer.js';
14
- import Sanitizer from './sanitizer.js';
15
- import Session from './session.js';
16
- import Ticker from './ticker.js';
17
- const CANCELED = 'canceled';
18
- const uxtStorageKey = 'or_uxt_active';
19
- const bufferStorageKey = 'or_buffer_1';
20
- const UnsuccessfulStart = (reason) => ({ reason, success: false });
21
- const SuccessfulStart = (body) => ({ ...body, success: true });
22
- var ActivityState;
23
- (function (ActivityState) {
24
- ActivityState[ActivityState["NotActive"] = 0] = "NotActive";
25
- ActivityState[ActivityState["Starting"] = 1] = "Starting";
26
- ActivityState[ActivityState["Active"] = 2] = "Active";
27
- ActivityState[ActivityState["ColdStart"] = 3] = "ColdStart";
28
- })(ActivityState || (ActivityState = {}));
29
- // TODO: use backendHost only
30
- export const DEFAULT_INGEST_POINT = 'https://api.openreplay.com/ingest';
31
- function getTimezone() {
32
- const offset = new Date().getTimezoneOffset() * -1;
33
- const sign = offset >= 0 ? '+' : '-';
34
- const hours = Math.floor(Math.abs(offset) / 60);
35
- const minutes = Math.abs(offset) % 60;
36
- return `UTC${sign}${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
37
- }
38
- const delay = (ms) => new Promise((res) => setTimeout(res, ms));
39
- const proto = {
40
- // ask if there are any tabs alive
41
- ask: 'never-gonna-give-you-up',
42
- // response from another tab
43
- resp: 'never-gonna-let-you-down',
44
- // regenerating id (copied other tab)
45
- reg: 'never-gonna-run-around-and-desert-you',
46
- iframeSignal: 'tracker inside a child iframe',
47
- iframeId: 'getting node id for child iframe',
48
- iframeBatch: 'batch of messages from an iframe window',
49
- parentAlive: 'signal that parent is live',
50
- killIframe: 'stop tracker inside frame',
51
- startIframe: 'start tracker inside frame',
52
- // checking updates
53
- polling: 'hello-how-are-you-im-under-the-water-please-help-me',
54
- };
55
- export default class App {
56
- constructor(projectKey, sessionToken, options, signalError, insideIframe) {
57
- this.signalError = signalError;
58
- this.insideIframe = insideIframe;
59
- this.messages = [];
60
- /**
61
- * we need 2 buffers, so we don't lose anything
62
- * @read coldStart implementation
63
- * */
64
- this.bufferedMessages1 = [];
65
- this.bufferedMessages2 = [];
66
- this.startCallbacks = [];
67
- this.stopCallbacks = [];
68
- this.commitCallbacks = [];
69
- this.activityState = ActivityState.NotActive;
70
- this.version = '14.0.10-beta.1'; // TODO: version compatability check inside each plugin.
71
- this.socketMode = false;
72
- this.compressionThreshold = 24 * 1000;
73
- this.bc = null;
74
- this.canvasRecorder = null;
75
- this.conditionsManager = null;
76
- this.canStart = false;
77
- this.rootId = null;
78
- this.pageFrames = [];
79
- this.frameOderNumber = 0;
80
- this.initialHostName = location.hostname;
81
- this.features = {
82
- 'feature-flags': true,
83
- 'usability-test': true,
84
- };
85
- /** used by child iframes for crossdomain only */
86
- this.parentActive = false;
87
- this.checkStatus = () => {
88
- return this.parentActive;
89
- };
90
- this.parentCrossDomainFrameListener = (event) => {
91
- const { data } = event;
92
- if (!data || event.source === window)
93
- return;
94
- if (data.line === proto.startIframe) {
95
- if (this.active())
96
- return;
97
- try {
98
- this.allowAppStart();
99
- void this.start();
100
- }
101
- catch (e) {
102
- console.error('children frame restart failed:', e);
103
- }
104
- }
105
- if (data.line === proto.parentAlive) {
106
- this.parentActive = true;
107
- }
108
- if (data.line === proto.iframeId) {
109
- this.parentActive = true;
110
- this.rootId = data.id;
111
- this.session.setSessionToken(data.token);
112
- this.frameOderNumber = data.frameOrderNumber;
113
- this.debug.log('starting iframe tracking', data);
114
- this.allowAppStart();
115
- this.delay = data.frameTimeOffset;
116
- }
117
- if (data.line === proto.killIframe) {
118
- if (this.active()) {
119
- this.stop();
120
- }
121
- }
122
- };
123
- this.trackedFrames = [];
124
- this.crossDomainIframeListener = (event) => {
125
- if (!this.active() || event.source === window)
126
- return;
127
- const { data } = event;
128
- if (!data)
129
- return;
130
- if (data.line === proto.iframeSignal) {
131
- // @ts-ignore
132
- event.source?.postMessage({ ping: true, line: proto.parentAlive }, '*');
133
- const childIframeDomain = data.domain;
134
- const pageIframes = Array.from(document.querySelectorAll('iframe'));
135
- this.pageFrames = pageIframes;
136
- const signalId = async () => {
137
- const id = await this.checkNodeId(pageIframes, childIframeDomain);
138
- if (id && !this.trackedFrames.includes(id)) {
139
- try {
140
- this.trackedFrames.push(id);
141
- await this.waitStarted();
142
- const token = this.session.getSessionToken();
143
- const iframeData = {
144
- line: proto.iframeId,
145
- context: this.contextId,
146
- domain: childIframeDomain,
147
- id,
148
- token,
149
- frameOrderNumber: this.trackedFrames.length,
150
- frameTimeOffset: this.timestamp(),
151
- };
152
- // @ts-ignore
153
- event.source?.postMessage(iframeData, '*');
154
- }
155
- catch (e) {
156
- console.error(e);
157
- }
158
- }
159
- };
160
- void signalId();
161
- }
162
- /**
163
- * proxying messages from iframe to main body, so they can be in one batch (same indexes, etc)
164
- * plus we rewrite some of the messages to be relative to the main context/window
165
- * */
166
- if (data.line === proto.iframeBatch) {
167
- const msgBatch = data.messages;
168
- const mappedMessages = msgBatch.map((msg) => {
169
- if (msg[0] === 20 /* MType.MouseMove */) {
170
- let fixedMessage = msg;
171
- this.pageFrames.forEach((frame) => {
172
- if (frame.dataset.domain === event.data.domain) {
173
- const [type, x, y] = msg;
174
- const { left, top } = frame.getBoundingClientRect();
175
- fixedMessage = [type, x + left, y + top];
176
- }
177
- });
178
- return fixedMessage;
179
- }
180
- if (msg[0] === 68 /* MType.MouseClick */) {
181
- let fixedMessage = msg;
182
- this.pageFrames.forEach((frame) => {
183
- if (frame.dataset.domain === event.data.domain) {
184
- const [type, id, hesitationTime, label, selector, normX, normY] = msg;
185
- const { left, top, width, height } = frame.getBoundingClientRect();
186
- const contentWidth = document.documentElement.scrollWidth;
187
- const contentHeight = document.documentElement.scrollHeight;
188
- // (normalizedX * frameWidth + frameLeftOffset)/docSize
189
- const fullX = (normX / 100) * width + left;
190
- const fullY = (normY / 100) * height + top;
191
- const fixedX = fullX / contentWidth;
192
- const fixedY = fullY / contentHeight;
193
- fixedMessage = [
194
- type,
195
- id,
196
- hesitationTime,
197
- label,
198
- selector,
199
- Math.round(fixedX * 1e3) / 1e1,
200
- Math.round(fixedY * 1e3) / 1e1,
201
- ];
202
- }
203
- });
204
- return fixedMessage;
205
- }
206
- return msg;
207
- });
208
- this.messages.push(...mappedMessages);
209
- }
210
- if (data.line === proto.polling) {
211
- if (!this.pollingQueue.length) {
212
- return;
213
- }
214
- while (this.pollingQueue.length) {
215
- const msg = this.pollingQueue.shift();
216
- // @ts-ignore
217
- event.source?.postMessage({ line: msg }, '*');
218
- }
219
- }
220
- };
221
- this.pollingQueue = [];
222
- this.bootChildrenFrames = async () => {
223
- await this.waitStarted();
224
- this.pollingQueue.push(proto.startIframe);
225
- };
226
- this.killChildrenFrames = () => {
227
- this.pollingQueue.push(proto.killIframe);
228
- };
229
- this.signalIframeTracker = () => {
230
- const domain = this.initialHostName;
231
- const thisTab = this.session.getTabId();
232
- const signalToParent = (n) => {
233
- window.parent.postMessage({
234
- line: proto.iframeSignal,
235
- source: thisTab,
236
- context: this.contextId,
237
- domain,
238
- }, this.options.crossdomain?.parentDomain ?? '*');
239
- setTimeout(() => {
240
- if (!this.checkStatus() && n < 100) {
241
- void signalToParent(n + 1);
242
- }
243
- }, 250);
244
- };
245
- void signalToParent(1);
246
- };
247
- this.startTimeout = null;
248
- this.coldStartCommitN = 0;
249
- this.delay = 0;
250
- this.attachStartCallback = (cb, useSafe = false) => {
251
- if (useSafe) {
252
- cb = this.safe(cb);
253
- }
254
- this.startCallbacks.push(cb);
255
- };
256
- this.attachStopCallback = (cb, useSafe = false) => {
257
- if (useSafe) {
258
- cb = this.safe(cb);
259
- }
260
- this.stopCallbacks.push(cb);
261
- };
262
- this.attachEventListener = (target, type, listener, useSafe = true, useCapture = true) => {
263
- if (useSafe) {
264
- listener = this.safe(listener);
265
- }
266
- const createListener = () => target ? createEventListener(target, type, listener, useCapture) : null;
267
- const deleteListener = () => target ? deleteEventListener(target, type, listener, useCapture) : null;
268
- this.attachStartCallback(createListener, useSafe);
269
- this.attachStopCallback(deleteListener, useSafe);
270
- };
271
- this.coldInterval = null;
272
- this.orderNumber = 0;
273
- this.coldStartTs = 0;
274
- this.singleBuffer = false;
275
- this.onSessionSent = () => {
276
- return;
277
- };
278
- this.restartCanvasTracking = () => {
279
- this.canvasRecorder?.restartTracking();
280
- };
281
- this.flushBuffer = async (buffer) => {
282
- return new Promise((res) => {
283
- let ended = false;
284
- const messagesBatch = [buffer.shift()];
285
- while (!ended) {
286
- const nextMsg = buffer[0];
287
- if (!nextMsg || nextMsg[0] === 0 /* MType.Timestamp */) {
288
- ended = true;
289
- }
290
- else {
291
- messagesBatch.push(buffer.shift());
292
- }
293
- }
294
- this.postToWorker(messagesBatch);
295
- res(null);
296
- });
297
- };
298
- this.onUxtCb = [];
299
- this.contextId = Math.random().toString(36).slice(2);
300
- this.projectKey = projectKey;
301
- if (Object.keys(options).findIndex((k) => ['fixedCanvasScaling', 'disableCanvas'].includes(k)) !==
302
- -1) {
303
- console.warn('Openreplay: canvas options are moving to separate key "canvas" in next update. Please update your configuration.');
304
- options = {
305
- ...options,
306
- canvas: {
307
- __save_canvas_locally: options.__save_canvas_locally,
308
- fixedCanvasScaling: options.fixedCanvasScaling,
309
- disableCanvas: options.disableCanvas,
310
- },
311
- };
312
- }
313
- this.networkOptions = options.network;
314
- const defaultOptions = {
315
- revID: '',
316
- node_id: '__openreplay_id',
317
- session_token_key: '__openreplay_token',
318
- session_pageno_key: '__openreplay_pageno',
319
- session_reset_key: '__openreplay_reset',
320
- session_tabid_key: '__openreplay_tabid',
321
- local_uuid_key: '__openreplay_uuid',
322
- ingestPoint: DEFAULT_INGEST_POINT,
323
- resourceBaseHref: null,
324
- __is_snippet: false,
325
- __debug_report_edp: null,
326
- __debug__: LogLevel.Silent,
327
- __save_canvas_locally: false,
328
- localStorage: null,
329
- sessionStorage: null,
330
- disableStringDict: false,
331
- forceSingleTab: false,
332
- assistSocketHost: '',
333
- fixedCanvasScaling: false,
334
- disableCanvas: false,
335
- captureIFrames: true,
336
- obscureTextEmails: true,
337
- obscureTextNumbers: false,
338
- crossdomain: {
339
- parentDomain: '*',
340
- },
341
- canvas: {
342
- disableCanvas: false,
343
- fixedCanvasScaling: false,
344
- __save_canvas_locally: false,
345
- useAnimationFrame: false,
346
- },
347
- };
348
- this.options = simpleMerge(defaultOptions, options);
349
- if (!this.insideIframe &&
350
- !this.options.forceSingleTab &&
351
- globalThis &&
352
- 'BroadcastChannel' in globalThis) {
353
- const host = location.hostname.split('.').slice(-2).join('_');
354
- this.bc = new BroadcastChannel(`rick_${host}`);
355
- }
356
- this.revID = this.options.revID;
357
- this.localStorage = this.options.localStorage ?? window.localStorage;
358
- this.sessionStorage = this.options.sessionStorage ?? window.sessionStorage;
359
- this.sanitizer = new Sanitizer(this, options);
360
- this.nodes = new Nodes(this.options.node_id);
361
- this.observer = new Observer(this, options);
362
- this.ticker = new Ticker(this);
363
- this.ticker.attach(() => this.commit());
364
- this.debug = new Logger(this.options.__debug__);
365
- this.session = new Session(this, this.options);
366
- this.attributeSender = new AttributeSender(this, Boolean(this.options.disableStringDict));
367
- this.featureFlags = new FeatureFlags(this);
368
- this.tagWatcher = new TagWatcher(this.sessionStorage, this.debug.error, (tag) => {
369
- this.send(TagTrigger(tag));
370
- });
371
- this.session.attachUpdateCallback(({ userID, metadata }) => {
372
- if (userID != null) {
373
- // TODO: nullable userID
374
- this.send(UserID(userID));
375
- }
376
- if (metadata != null) {
377
- Object.entries(metadata).forEach(([key, value]) => this.send(Metadata(key, value)));
378
- }
379
- });
380
- // @deprecated (use sessionHash on start instead)
381
- if (sessionToken != null) {
382
- this.session.applySessionHash(sessionToken);
383
- }
384
- this.initWorker();
385
- const thisTab = this.session.getTabId();
386
- /**
387
- * listen for messages from parent window, so we can signal that we're alive
388
- * */
389
- if (this.insideIframe) {
390
- window.addEventListener('message', this.parentCrossDomainFrameListener);
391
- setInterval(() => {
392
- window.parent.postMessage({
393
- line: proto.polling,
394
- }, '*');
395
- }, 250);
396
- }
397
- /**
398
- * if we get a signal from child iframes, we check for their node_id and send it back,
399
- * so they can act as if it was just a same-domain iframe
400
- * */
401
- if (!this.insideIframe) {
402
- window.addEventListener('message', this.crossDomainIframeListener);
403
- }
404
- if (this.bc !== null) {
405
- this.bc.postMessage({
406
- line: proto.ask,
407
- source: thisTab,
408
- context: this.contextId,
409
- });
410
- this.startTimeout = setTimeout(() => {
411
- this.allowAppStart();
412
- }, 250);
413
- this.bc.onmessage = (ev) => {
414
- if (ev.data.context === this.contextId) {
415
- return;
416
- }
417
- if (ev.data.line === proto.resp) {
418
- const sessionToken = ev.data.token;
419
- this.session.setSessionToken(sessionToken);
420
- this.allowAppStart();
421
- }
422
- if (ev.data.line === proto.reg) {
423
- const sessionToken = ev.data.token;
424
- this.session.regenerateTabId();
425
- this.session.setSessionToken(sessionToken);
426
- this.allowAppStart();
427
- }
428
- if (ev.data.line === proto.ask) {
429
- const token = this.session.getSessionToken();
430
- if (token && this.bc) {
431
- this.bc.postMessage({
432
- line: ev.data.source === thisTab ? proto.reg : proto.resp,
433
- token,
434
- source: thisTab,
435
- context: this.contextId,
436
- });
437
- }
438
- }
439
- };
440
- }
441
- }
442
- allowAppStart() {
443
- this.canStart = true;
444
- if (this.startTimeout) {
445
- clearTimeout(this.startTimeout);
446
- this.startTimeout = null;
447
- }
448
- }
449
- async checkNodeId(iframes, domain) {
450
- for (const iframe of iframes) {
451
- if (iframe.dataset.domain === domain) {
452
- /**
453
- * Here we're trying to get node id from the iframe (which is kept in observer)
454
- * because of async nature of dom initialization, we give 100 retries with 100ms delay each
455
- * which equals to 10 seconds. This way we have a period where we give app some time to load
456
- * and tracker some time to parse the initial DOM tree even on slower devices
457
- * */
458
- let tries = 0;
459
- while (tries < 100) {
460
- // @ts-ignore
461
- const potentialId = iframe[this.options.node_id];
462
- if (potentialId !== undefined) {
463
- tries = 100;
464
- return potentialId;
465
- }
466
- else {
467
- tries++;
468
- await delay(100);
469
- }
470
- }
471
- return null;
472
- }
473
- }
474
- return null;
475
- }
476
- initWorker() {
477
- try {
478
- this.worker = new Worker(URL.createObjectURL(new Blob(['"use strict";class t{constructor(t,s,i,e=10,n=250,h,r){this.onUnauthorised=s,this.onFailure=i,this.MAX_ATTEMPTS_COUNT=e,this.ATTEMPT_TIMEOUT=n,this.onCompress=h,this.pageNo=r,this.attemptsCount=0,this.busy=!1,this.queue=[],this.token=null,this.lastBatchNum=0,this.ingestURL=t+"/v1/web/i",this.isCompressing=void 0!==h}getQueueStatus(){return 0===this.queue.length&&!this.busy}authorise(t){this.token=t,this.busy||this.sendNext()}push(t){if(this.busy||!this.token)this.queue.push(t);else if(this.busy=!0,this.isCompressing&&this.onCompress)this.onCompress(t);else{const s=++this.lastBatchNum;this.sendBatch(t,!1,s)}}sendNext(){const t=this.queue.shift();if(t)if(this.busy=!0,this.isCompressing&&this.onCompress)this.onCompress(t);else{const s=++this.lastBatchNum;this.sendBatch(t,!1,s)}else this.busy=!1}retry(t,s,i){this.attemptsCount>=this.MAX_ATTEMPTS_COUNT?this.onFailure(`Failed to send batch after ${this.attemptsCount} attempts.`):(this.attemptsCount++,setTimeout((()=>this.sendBatch(t,s,i)),this.ATTEMPT_TIMEOUT*this.attemptsCount))}sendBatch(t,s,i){const e=i?.toString().replace(/^([^_]+)_([^_]+).*/,"$1_$2_$3");this.busy=!0;const n={Authorization:`Bearer ${this.token}`};s&&(n["Content-Encoding"]="gzip"),null!==this.token?fetch(`${this.ingestURL}?batch=${this.pageNo??"noPageNum"}_${e??"noBatchNum"}`,{body:t,method:"POST",headers:n,keepalive:t.length<65536}).then((e=>{if(401===e.status)return this.busy=!1,void this.onUnauthorised();e.status>=400?this.retry(t,s,`${i??"noBatchNum"}_network:${e.status}`):(this.attemptsCount=0,this.sendNext())})).catch((e=>{console.warn("OpenReplay:",e),this.retry(t,s,`${i??"noBatchNum"}_reject:${e.message}`)})):setTimeout((()=>{this.sendBatch(t,s,`${i??"noBatchNum"}_newToken`)}),500)}sendCompressed(t){const s=++this.lastBatchNum;this.sendBatch(t,!0,s)}sendUncompressed(t){const s=++this.lastBatchNum;this.sendBatch(t,!1,s)}clean(){this.sendNext(),setTimeout((()=>{this.token=null,this.queue.length=0}),10)}}const s="function"==typeof TextEncoder?new TextEncoder:{encode(t){const s=t.length,i=new Uint8Array(3*s);let e=-1;for(let n=0,h=0,r=0;r!==s;){if(n=t.charCodeAt(r),r+=1,n>=55296&&n<=56319){if(r===s){i[e+=1]=239,i[e+=1]=191,i[e+=1]=189;break}if(h=t.charCodeAt(r),!(h>=56320&&h<=57343)){i[e+=1]=239,i[e+=1]=191,i[e+=1]=189;continue}if(n=1024*(n-55296)+h-56320+65536,r+=1,n>65535){i[e+=1]=240|n>>>18,i[e+=1]=128|n>>>12&63,i[e+=1]=128|n>>>6&63,i[e+=1]=128|63&n;continue}}n<=127?i[e+=1]=0|n:n<=2047?(i[e+=1]=192|n>>>6,i[e+=1]=128|63&n):(i[e+=1]=224|n>>>12,i[e+=1]=128|n>>>6&63,i[e+=1]=128|63&n)}return i.subarray(0,e+1)}};class i{constructor(t){this.size=t,this.offset=0,this.checkpointOffset=0,this.data=new Uint8Array(t)}getCurrentOffset(){return this.offset}checkpoint(){this.checkpointOffset=this.offset}get isEmpty(){return 0===this.offset}skip(t){return this.offset+=t,this.offset<=this.size}set(t,s){this.data.set(t,s)}boolean(t){return this.data[this.offset++]=+t,this.offset<=this.size}uint(t){for((t<0||t>Number.MAX_SAFE_INTEGER)&&(t=0);t>=128;)this.data[this.offset++]=t%256|128,t=Math.floor(t/128);return this.data[this.offset++]=t,this.offset<=this.size}int(t){return t=Math.round(t),this.uint(t>=0?2*t:-2*t-1)}string(t){const i=s.encode(t),e=i.byteLength;return!(!this.uint(e)||this.offset+e>this.size)&&(this.data.set(i,this.offset),this.offset+=e,!0)}reset(){this.offset=0,this.checkpointOffset=0}flush(){const t=this.data.slice(0,this.checkpointOffset);return this.reset(),t}}class e extends i{encode(t){switch(t[0]){case 0:case 11:case 114:case 115:return this.uint(t[1]);case 4:case 44:case 47:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3]);case 5:case 20:case 38:case 70:case 75:case 76:case 77:case 82:return this.uint(t[1])&&this.uint(t[2]);case 6:return this.int(t[1])&&this.int(t[2]);case 7:return!0;case 8:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.string(t[4])&&this.boolean(t[5]);case 9:case 10:case 24:case 51:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3]);case 12:case 61:case 71:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3]);case 13:case 14:case 17:case 50:case 54:return this.uint(t[1])&&this.string(t[2]);case 16:return this.uint(t[1])&&this.int(t[2])&&this.int(t[3]);case 18:return this.uint(t[1])&&this.string(t[2])&&this.int(t[3]);case 19:return this.uint(t[1])&&this.boolean(t[2]);case 21:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.string(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8]);case 22:case 27:case 30:case 41:case 45:case 46:case 63:case 64:case 79:return this.string(t[1])&&this.string(t[2]);case 23:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8])&&this.uint(t[9]);case 28:case 29:case 42:case 117:case 118:return this.string(t[1]);case 37:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3]);case 39:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.uint(t[7]);case 40:return this.string(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4]);case 48:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.int(t[5]);case 49:return this.int(t[1])&&this.int(t[2])&&this.uint(t[3])&&this.uint(t[4]);case 53:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.string(t[7])&&this.string(t[8]);case 55:return this.boolean(t[1]);case 57:case 60:return this.uint(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 58:case 120:return this.int(t[1]);case 59:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.string(t[5])&&this.string(t[6])&&this.string(t[7]);case 67:case 73:return this.uint(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.string(t[4]);case 68:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4])&&this.uint(t[5])&&this.uint(t[6]);case 69:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3])&&this.string(t[4]);case 78:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4]);case 81:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.int(t[4])&&this.string(t[5]);case 83:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.string(t[5])&&this.uint(t[6])&&this.uint(t[7])&&this.uint(t[8])&&this.uint(t[9]);case 84:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.uint(t[4])&&this.string(t[5])&&this.string(t[6]);case 112:return this.uint(t[1])&&this.string(t[2])&&this.boolean(t[3])&&this.string(t[4])&&this.int(t[5])&&this.int(t[6]);case 113:return this.uint(t[1])&&this.uint(t[2])&&this.string(t[3]);case 116:return this.uint(t[1])&&this.uint(t[2])&&this.uint(t[3])&&this.uint(t[4])&&this.uint(t[5])&&this.uint(t[6])&&this.string(t[7])&&this.string(t[8])&&this.uint(t[9])&&this.boolean(t[10]);case 119:return this.string(t[1])&&this.uint(t[2]);case 121:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.uint(t[4]);case 122:return this.string(t[1])&&this.string(t[2])&&this.uint(t[3])&&this.string(t[4]);case 123:return this.string(t[1])&&this.string(t[2])&&this.string(t[3])&&this.string(t[4])&&this.uint(t[5])}}}class n{constructor(t,s,i,n,h,r){this.pageNo=t,this.timestamp=s,this.url=i,this.onBatch=n,this.tabId=h,this.onOfflineEnd=r,this.nextIndex=0,this.beaconSize=2e5,this.encoder=new e(this.beaconSize),this.sizeBuffer=new Uint8Array(3),this.isEmpty=!0,this.beaconSizeLimit=1e6,this.prepare()}writeType(t){return this.encoder.uint(t[0])}writeFields(t){return this.encoder.encode(t)}writeSizeAt(t,s){for(let s=0;s<3;s++)this.sizeBuffer[s]=t>>8*s;this.encoder.set(this.sizeBuffer,s)}prepare(){if(!this.encoder.isEmpty)return;const t=[81,1,this.pageNo,this.nextIndex,this.timestamp,this.url],s=[118,this.tabId];this.writeType(t),this.writeFields(t),this.writeWithSize(s),this.isEmpty=!0}writeWithSize(t){const s=this.encoder;if(!this.writeType(t)||!s.skip(3))return!1;const i=s.getCurrentOffset(),e=this.writeFields(t);if(e){const e=s.getCurrentOffset()-i;if(e>16777215)return console.warn("OpenReplay: max message size overflow."),!1;this.writeSizeAt(e,i-3),s.checkpoint(),this.isEmpty=this.isEmpty&&0===t[0],this.nextIndex++}return e}setBeaconSizeLimit(t){this.beaconSizeLimit=t}writeMessage(t){if("q_end"===t[0])return this.finaliseBatch(),this.onOfflineEnd();0===t[0]&&(this.timestamp=t[1]),122===t[0]&&(this.url=t[1]),this.writeWithSize(t)||(this.finaliseBatch(),this.writeWithSize(t)||(this.encoder=new e(this.beaconSizeLimit),this.prepare(),this.writeWithSize(t)?this.finaliseBatch():console.warn("OpenReplay: beacon size overflow. Skipping large message.",t,this),this.encoder=new e(this.beaconSize),this.prepare()))}finaliseBatch(){if(this.isEmpty)return;const t=this.encoder.flush();this.onBatch(t),this.prepare()}clean(){this.encoder.reset()}}var h;!function(t){t[t.NotActive=0]="NotActive",t[t.Starting=1]="Starting",t[t.Stopping=2]="Stopping",t[t.Active=3]="Active",t[t.Stopped=4]="Stopped"}(h||(h={}));let r=null,a=null,u=h.NotActive;function o(){a&&a.finaliseBatch()}function c(){return new Promise((t=>{u=h.Stopping,null!==l&&(clearInterval(l),l=null),a&&(a.clean(),a=null),r&&(r.clean(),setTimeout((()=>{r=null}),20)),setTimeout((()=>{u=h.NotActive,t(null)}),100)}))}function g(){[h.Stopped,h.Stopping].includes(u)||(postMessage("a_stop"),c().then((()=>{postMessage("a_start")})))}let p,l=null;self.onmessage=({data:s})=>{if(null!=s){if("stop"===s)return o(),void c().then((()=>{u=h.Stopped}));if("forceFlushBatch"!==s){if(!Array.isArray(s)){if("compressed"===s.type){if(!r)return console.debug("OR WebWorker: sender not initialised. Compressed batch."),void g();s.batch&&r.sendCompressed(s.batch)}if("uncompressed"===s.type){if(!r)return console.debug("OR WebWorker: sender not initialised. Uncompressed batch."),void g();s.batch&&r.sendUncompressed(s.batch)}return"start"===s.type?(u=h.Starting,r=new t(s.ingestPoint,(()=>{g()}),(t=>{!function(t){postMessage({type:"failure",reason:t}),c()}(t)}),s.connAttemptCount,s.connAttemptGap,(t=>{postMessage({type:"compress",batch:t},[t.buffer])}),s.pageNo),a=new n(s.pageNo,s.timestamp,s.url,(t=>{r&&r.push(t)}),s.tabId,(()=>postMessage({type:"queue_empty"}))),null===l&&(l=setInterval(o,1e4)),u=h.Active):"auth"===s.type?r?a?(r.authorise(s.token),void(s.beaconSizeLimit&&a.setBeaconSizeLimit(s.beaconSizeLimit))):(console.debug("OR WebWorker: writer not initialised. Received auth."),void g()):(console.debug("OR WebWorker: sender not initialised. Received auth."),void g()):void 0}if(a){const t=a;s.forEach((s=>{55===s[0]&&(s[1]?p=setTimeout((()=>g()),18e5):clearTimeout(p)),t.writeMessage(s)}))}else postMessage("not_init"),g()}else o()}else o()};'], { type: 'text/javascript' })));
479
- this.worker.onerror = (e) => {
480
- this._debug('webworker_error', e);
481
- };
482
- this.worker.onmessage = ({ data }) => {
483
- this.handleWorkerMsg(data);
484
- };
485
- const alertWorker = () => {
486
- if (this.worker) {
487
- this.worker.postMessage(null);
488
- }
489
- };
490
- // keep better tactics, discard others?
491
- this.attachEventListener(window, 'beforeunload', alertWorker, false);
492
- this.attachEventListener(document.body, 'mouseleave', alertWorker, false, false);
493
- // TODO: stop session after inactivity timeout (make configurable)
494
- this.attachEventListener(document, 'visibilitychange', alertWorker, false);
495
- }
496
- catch (e) {
497
- this._debug('worker_start', e);
498
- }
499
- }
500
- handleWorkerMsg(data) {
501
- // handling 401 auth restart (new token assignment)
502
- if (data === 'a_stop') {
503
- this.stop(false);
504
- }
505
- else if (data === 'a_start') {
506
- void this.start({}, true);
507
- }
508
- else if (data === 'not_init') {
509
- this.debug.warn('OR WebWorker: writer not initialised. Restarting tracker');
510
- }
511
- else if (data.type === 'failure') {
512
- this.stop(false);
513
- this.debug.error('worker_failed', data.reason);
514
- this._debug('worker_failed', data.reason);
515
- }
516
- else if (data.type === 'compress') {
517
- const batch = data.batch;
518
- const batchSize = batch.byteLength;
519
- if (batchSize > this.compressionThreshold) {
520
- gzip(data.batch, { mtime: 0 }, (err, result) => {
521
- if (err) {
522
- this.debug.error('Openreplay compression error:', err);
523
- this.worker?.postMessage({ type: 'uncompressed', batch: batch });
524
- }
525
- else {
526
- this.worker?.postMessage({ type: 'compressed', batch: result });
527
- }
528
- });
529
- }
530
- else {
531
- this.worker?.postMessage({ type: 'uncompressed', batch: batch });
532
- }
533
- }
534
- else if (data.type === 'queue_empty') {
535
- this.onSessionSent();
536
- }
537
- }
538
- _debug(context, e) {
539
- if (this.options.__debug_report_edp !== null) {
540
- void fetch(this.options.__debug_report_edp, {
541
- method: 'POST',
542
- headers: { 'Content-Type': 'application/json' },
543
- body: JSON.stringify({
544
- context,
545
- // @ts-ignore
546
- error: `${e}`,
547
- }),
548
- });
549
- }
550
- this.debug.error('OpenReplay error: ', context, e);
551
- }
552
- send(message, urgent = false) {
553
- if (this.activityState === ActivityState.NotActive) {
554
- return;
555
- }
556
- // ====================================================
557
- if (this.activityState === ActivityState.ColdStart) {
558
- this.bufferedMessages1.push(message);
559
- if (!this.singleBuffer) {
560
- this.bufferedMessages2.push(message);
561
- }
562
- this.conditionsManager?.processMessage(message);
563
- }
564
- else {
565
- this.messages.push(message);
566
- }
567
- // TODO: commit on start if there were `urgent` sends;
568
- // Clarify where urgent can be used for;
569
- // Clarify workflow for each type of message in case it was sent before start
570
- // (like Fetch before start; maybe add an option "preCapture: boolean" or sth alike)
571
- // Careful: `this.delay` is equal to zero before start so all Timestamp-s will have to be updated on start
572
- if (this.activityState === ActivityState.Active && urgent) {
573
- this.commit();
574
- }
575
- }
576
- /**
577
- * Normal workflow: add timestamp and tab data to batch, then commit it
578
- * every ~30ms
579
- * */
580
- _nCommit() {
581
- if (this.socketMode) {
582
- this.messages.unshift(TabData(this.session.getTabId()));
583
- this.messages.unshift(Timestamp(this.timestamp()));
584
- this.commitCallbacks.forEach((cb) => cb(this.messages));
585
- this.messages.length = 0;
586
- return;
587
- }
588
- if (this.worker === undefined || !this.messages.length) {
589
- return;
590
- }
591
- if (this.insideIframe) {
592
- window.parent.postMessage({
593
- line: proto.iframeBatch,
594
- messages: this.messages,
595
- domain: this.initialHostName,
596
- }, this.options.crossdomain?.parentDomain ?? '*');
597
- this.commitCallbacks.forEach((cb) => cb(this.messages));
598
- this.messages.length = 0;
599
- return;
600
- }
601
- try {
602
- requestIdleCb(() => {
603
- this.messages.unshift(TabData(this.session.getTabId()));
604
- this.messages.unshift(Timestamp(this.timestamp()));
605
- this.worker?.postMessage(this.messages);
606
- this.commitCallbacks.forEach((cb) => cb(this.messages));
607
- this.messages.length = 0;
608
- });
609
- }
610
- catch (e) {
611
- this._debug('worker_commit', e);
612
- this.stop(true);
613
- setTimeout(() => {
614
- void this.start();
615
- }, 500);
616
- }
617
- }
618
- /**
619
- * Cold start: add timestamp and tab data to both batches
620
- * every 2nd tick, ~60ms
621
- * this will make batches a bit larger and replay will work with bigger jumps every frame
622
- * but in turn we don't overload batch writer on session start with 1000 batches
623
- * */
624
- _cStartCommit() {
625
- this.coldStartCommitN += 1;
626
- if (this.coldStartCommitN === 2) {
627
- this.bufferedMessages1.push(Timestamp(this.timestamp()));
628
- this.bufferedMessages1.push(TabData(this.session.getTabId()));
629
- this.bufferedMessages2.push(Timestamp(this.timestamp()));
630
- this.bufferedMessages2.push(TabData(this.session.getTabId()));
631
- this.coldStartCommitN = 0;
632
- }
633
- }
634
- commit() {
635
- if (this.activityState === ActivityState.ColdStart) {
636
- this._cStartCommit();
637
- }
638
- else {
639
- this._nCommit();
640
- }
641
- }
642
- postToWorker(messages) {
643
- this.worker?.postMessage(messages);
644
- this.commitCallbacks.forEach((cb) => cb(messages));
645
- messages.length = 0;
646
- }
647
- timestamp() {
648
- return now() + this.delay;
649
- }
650
- safe(fn) {
651
- const app = this;
652
- return function (...args) {
653
- try {
654
- fn.apply(this, args);
655
- }
656
- catch (e) {
657
- app._debug('safe_fn_call', e);
658
- // time: this.timestamp(),
659
- // name: e.name,
660
- // message: e.message,
661
- // stack: e.stack
662
- }
663
- }; // TODO: correct typing
664
- }
665
- attachCommitCallback(cb) {
666
- this.commitCallbacks.push(cb);
667
- }
668
- // TODO: full correct semantic
669
- checkRequiredVersion(version) {
670
- const reqVer = version.split(/[.-]/);
671
- const ver = this.version.split(/[.-]/);
672
- for (let i = 0; i < 3; i++) {
673
- if (isNaN(Number(ver[i])) || isNaN(Number(reqVer[i]))) {
674
- return false;
675
- }
676
- if (Number(ver[i]) > Number(reqVer[i])) {
677
- return true;
678
- }
679
- if (Number(ver[i]) < Number(reqVer[i])) {
680
- return false;
681
- }
682
- }
683
- return true;
684
- }
685
- getTrackerInfo() {
686
- return {
687
- userUUID: this.localStorage.getItem(this.options.local_uuid_key),
688
- projectKey: this.projectKey,
689
- revID: this.revID,
690
- trackerVersion: this.version,
691
- isSnippet: this.options.__is_snippet,
692
- };
693
- }
694
- getSessionInfo() {
695
- return {
696
- ...this.session.getInfo(),
697
- ...this.getTrackerInfo(),
698
- };
699
- }
700
- getSessionToken() {
701
- return this.session.getSessionToken();
702
- }
703
- getSessionID() {
704
- return this.session.getInfo().sessionID || undefined;
705
- }
706
- getSessionURL(options) {
707
- const { projectID, sessionID, timestamp } = this.session.getInfo();
708
- if (!projectID || !sessionID) {
709
- this.debug.error('OpenReplay error: Unable to build session URL');
710
- return undefined;
711
- }
712
- const ingest = this.options.ingestPoint;
713
- const isSaas = /api\.openreplay\.com/.test(ingest);
714
- const projectPath = isSaas ? 'https://app.openreplay.com/ingest' : ingest;
715
- const url = projectPath.replace(/ingest$/, `${projectID}/session/${sessionID}`);
716
- if (options?.withCurrentTime) {
717
- const jumpTo = now() - timestamp;
718
- return `${url}?jumpto=${jumpTo}`;
719
- }
720
- return url;
721
- }
722
- getHost() {
723
- return new URL(this.options.ingestPoint).host;
724
- }
725
- getProjectKey() {
726
- return this.projectKey;
727
- }
728
- getBaseHref() {
729
- if (typeof this.options.resourceBaseHref === 'string') {
730
- return this.options.resourceBaseHref;
731
- }
732
- else if (typeof this.options.resourceBaseHref === 'object') {
733
- //TODO: switch between types
734
- }
735
- if (document.baseURI) {
736
- return document.baseURI;
737
- }
738
- // IE only
739
- return (document.head?.getElementsByTagName('base')[0]?.getAttribute('href') ||
740
- location.origin + location.pathname);
741
- }
742
- resolveResourceURL(resourceURL) {
743
- const base = new URL(this.getBaseHref());
744
- base.pathname += '/' + new URL(resourceURL).pathname;
745
- base.pathname.replace(/\/+/g, '/');
746
- return base.toString();
747
- }
748
- isServiceURL(url) {
749
- return url.startsWith(this.options.ingestPoint);
750
- }
751
- active() {
752
- return this.activityState === ActivityState.Active;
753
- }
754
- resetNextPageSession(flag) {
755
- if (flag) {
756
- this.sessionStorage.setItem(this.options.session_reset_key, 't');
757
- }
758
- else {
759
- this.sessionStorage.removeItem(this.options.session_reset_key);
760
- }
761
- }
762
- checkSessionToken(forceNew) {
763
- const lsReset = this.sessionStorage.getItem(this.options.session_reset_key) !== null;
764
- const needNewSessionID = forceNew || lsReset;
765
- const sessionToken = this.session.getSessionToken();
766
- return needNewSessionID || !sessionToken;
767
- }
768
- /**
769
- * start buffering messages without starting the actual session, which gives
770
- * user 30 seconds to "activate" and record session by calling `start()` on conditional trigger,
771
- * and we will then send buffered batch, so it won't get lost
772
- * */
773
- async coldStart(startOpts = {}, conditional) {
774
- this.singleBuffer = false;
775
- const second = 1000;
776
- const isNewSession = this.checkSessionToken(startOpts.forceNew);
777
- if (conditional) {
778
- await this.setupConditionalStart(startOpts);
779
- }
780
- const cycle = () => {
781
- this.orderNumber += 1;
782
- adjustTimeOrigin();
783
- this.coldStartTs = now();
784
- if (this.orderNumber % 2 === 0) {
785
- this.bufferedMessages1.length = 0;
786
- this.bufferedMessages1.push(Timestamp(this.timestamp()));
787
- this.bufferedMessages1.push(TabData(this.session.getTabId()));
788
- }
789
- else {
790
- this.bufferedMessages2.length = 0;
791
- this.bufferedMessages2.push(Timestamp(this.timestamp()));
792
- this.bufferedMessages2.push(TabData(this.session.getTabId()));
793
- }
794
- this.stop(false);
795
- this.activityState = ActivityState.ColdStart;
796
- if (startOpts.sessionHash) {
797
- this.session.applySessionHash(startOpts.sessionHash);
798
- }
799
- if (startOpts.forceNew) {
800
- this.session.reset();
801
- }
802
- this.session.assign({
803
- userID: startOpts.userID,
804
- metadata: startOpts.metadata,
805
- });
806
- if (!isNewSession) {
807
- this.debug.log('continuing session on new tab', this.session.getTabId());
808
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
809
- this.send(TabChange(this.session.getTabId()));
810
- }
811
- this.observer.observe();
812
- this.ticker.start();
813
- };
814
- this.coldInterval = setInterval(() => {
815
- cycle();
816
- }, 30 * second);
817
- cycle();
818
- }
819
- async setupConditionalStart(startOpts) {
820
- this.conditionsManager = new ConditionsManager(this, startOpts);
821
- const r = await fetch(this.options.ingestPoint + '/v1/web/start', {
822
- method: 'POST',
823
- headers: {
824
- 'Content-Type': 'application/json',
825
- },
826
- body: JSON.stringify({
827
- ...this.getTrackerInfo(),
828
- timestamp: now(),
829
- doNotRecord: true,
830
- bufferDiff: 0,
831
- userID: this.session.getInfo().userID,
832
- token: undefined,
833
- deviceMemory,
834
- jsHeapSizeLimit,
835
- timezone: getTimezone(),
836
- width: window.screen.width,
837
- height: window.screen.height,
838
- }),
839
- });
840
- const {
841
- // this token is needed to fetch conditions and flags,
842
- // but it can't be used to record a session
843
- token, userBrowser, userCity, userCountry, userDevice, userOS, userState, projectID, features, } = await r.json();
844
- this.features = features ? features : this.features;
845
- this.session.assign({ projectID });
846
- this.session.setUserInfo({
847
- userBrowser,
848
- userCity,
849
- userCountry,
850
- userDevice,
851
- userOS,
852
- userState,
853
- });
854
- const onStartInfo = { sessionToken: token, userUUID: '', sessionID: '' };
855
- this.startCallbacks.forEach((cb) => cb(onStartInfo));
856
- await this.conditionsManager?.fetchConditions(projectID, token);
857
- if (this.features['feature-flags']) {
858
- await this.featureFlags.reloadFlags(token);
859
- this.conditionsManager?.processFlags(this.featureFlags.flags);
860
- }
861
- await this.tagWatcher.fetchTags(this.options.ingestPoint, token);
862
- }
863
- /**
864
- * Starts offline session recording
865
- * @param {Object} startOpts - options for session start, same as .start()
866
- * @param {Function} onSessionSent - callback that will be called once session is fully sent
867
- * */
868
- offlineRecording(startOpts = {}, onSessionSent) {
869
- this.onSessionSent = onSessionSent;
870
- this.singleBuffer = true;
871
- const isNewSession = this.checkSessionToken(startOpts.forceNew);
872
- adjustTimeOrigin();
873
- this.coldStartTs = now();
874
- const saverBuffer = this.localStorage.getItem(bufferStorageKey);
875
- if (saverBuffer) {
876
- const data = JSON.parse(saverBuffer);
877
- this.bufferedMessages1 = Array.isArray(data) ? data : this.bufferedMessages1;
878
- this.localStorage.removeItem(bufferStorageKey);
879
- }
880
- this.bufferedMessages1.push(Timestamp(this.timestamp()));
881
- this.bufferedMessages1.push(TabData(this.session.getTabId()));
882
- this.activityState = ActivityState.ColdStart;
883
- if (startOpts.sessionHash) {
884
- this.session.applySessionHash(startOpts.sessionHash);
885
- }
886
- if (startOpts.forceNew) {
887
- this.session.reset();
888
- }
889
- this.session.assign({
890
- userID: startOpts.userID,
891
- metadata: startOpts.metadata,
892
- });
893
- const onStartInfo = { sessionToken: '', userUUID: '', sessionID: '' };
894
- this.startCallbacks.forEach((cb) => cb(onStartInfo));
895
- if (!isNewSession) {
896
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
897
- this.send(TabChange(this.session.getTabId()));
898
- }
899
- this.observer.observe();
900
- this.ticker.start();
901
- return {
902
- saveBuffer: this.saveBuffer,
903
- getBuffer: this.getBuffer,
904
- setBuffer: this.setBuffer,
905
- };
906
- }
907
- /**
908
- * Saves the captured messages in localStorage (or whatever is used in its place)
909
- *
910
- * Then, when this.offlineRecording is called, it will preload this messages and clear the storage item
911
- *
912
- * Keeping the size of local storage reasonable is up to the end users of this library
913
- * */
914
- saveBuffer() {
915
- this.localStorage.setItem(bufferStorageKey, JSON.stringify(this.bufferedMessages1));
916
- }
917
- /**
918
- * @returns buffer with stored messages for offline recording
919
- * */
920
- getBuffer() {
921
- return this.bufferedMessages1;
922
- }
923
- /**
924
- * Used to set a buffer with messages array
925
- * */
926
- setBuffer(buffer) {
927
- this.bufferedMessages1 = buffer;
928
- }
929
- /**
930
- * Uploads the stored session buffer to backend
931
- * @returns promise that resolves once messages are loaded, it has to be awaited
932
- * so the session can be uploaded properly
933
- * @resolve - if messages were loaded in service worker successfully
934
- * @reject {string} - error message
935
- * */
936
- async uploadOfflineRecording() {
937
- this.stop(false);
938
- const timestamp = now();
939
- this.worker?.postMessage({
940
- type: 'start',
941
- pageNo: this.session.incPageNo(),
942
- ingestPoint: this.options.ingestPoint,
943
- timestamp: this.coldStartTs,
944
- url: document.URL,
945
- connAttemptCount: this.options.connAttemptCount,
946
- connAttemptGap: this.options.connAttemptGap,
947
- tabId: this.session.getTabId(),
948
- });
949
- const r = await fetch(this.options.ingestPoint + '/v1/web/start', {
950
- method: 'POST',
951
- headers: {
952
- 'Content-Type': 'application/json',
953
- },
954
- body: JSON.stringify({
955
- ...this.getTrackerInfo(),
956
- timestamp: timestamp,
957
- doNotRecord: false,
958
- bufferDiff: timestamp - this.coldStartTs,
959
- userID: this.session.getInfo().userID,
960
- token: undefined,
961
- deviceMemory,
962
- jsHeapSizeLimit,
963
- timezone: getTimezone(),
964
- }),
965
- });
966
- const { token, userBrowser, userCity, userCountry, userDevice, userOS, userState, beaconSizeLimit, projectID, } = await r.json();
967
- this.worker?.postMessage({
968
- type: 'auth',
969
- token,
970
- beaconSizeLimit,
971
- });
972
- this.session.assign({ projectID });
973
- this.session.setUserInfo({
974
- userBrowser,
975
- userCity,
976
- userCountry,
977
- userDevice,
978
- userOS,
979
- userState,
980
- });
981
- while (this.bufferedMessages1.length > 0) {
982
- await this.flushBuffer(this.bufferedMessages1);
983
- }
984
- this.postToWorker([['q_end']]);
985
- this.clearBuffers();
986
- }
987
- async _start(startOpts = {}, resetByWorker = false, conditionName) {
988
- const isColdStart = this.activityState === ActivityState.ColdStart;
989
- if (isColdStart && this.coldInterval) {
990
- clearInterval(this.coldInterval);
991
- }
992
- if (!this.worker) {
993
- const reason = 'No worker found: perhaps, CSP is not set.';
994
- this.signalError(reason, []);
995
- return Promise.resolve(UnsuccessfulStart(reason));
996
- }
997
- if (this.activityState === ActivityState.Active ||
998
- this.activityState === ActivityState.Starting) {
999
- const reason = 'OpenReplay: trying to call `start()` on the instance that has been started already.';
1000
- return Promise.resolve(UnsuccessfulStart(reason));
1001
- }
1002
- this.activityState = ActivityState.Starting;
1003
- if (!isColdStart) {
1004
- adjustTimeOrigin();
1005
- }
1006
- if (startOpts.sessionHash) {
1007
- this.session.applySessionHash(startOpts.sessionHash);
1008
- }
1009
- if (startOpts.forceNew) {
1010
- // Reset session metadata only if requested directly
1011
- this.session.reset();
1012
- }
1013
- this.session.assign({
1014
- // MBTODO: maybe it would make sense to `forceNew` if the `userID` was changed
1015
- userID: startOpts.userID,
1016
- metadata: startOpts.metadata,
1017
- });
1018
- const timestamp = now();
1019
- this.worker.postMessage({
1020
- type: 'start',
1021
- pageNo: this.session.incPageNo(),
1022
- ingestPoint: this.options.ingestPoint,
1023
- timestamp: isColdStart ? this.coldStartTs : timestamp,
1024
- url: document.URL,
1025
- connAttemptCount: this.options.connAttemptCount,
1026
- connAttemptGap: this.options.connAttemptGap,
1027
- tabId: this.session.getTabId(),
1028
- });
1029
- const sessionToken = this.session.getSessionToken();
1030
- const isNewSession = this.checkSessionToken(startOpts.forceNew);
1031
- this.sessionStorage.removeItem(this.options.session_reset_key);
1032
- this.debug.log('OpenReplay: starting session; need new session id?', isNewSession, 'session token: ', sessionToken);
1033
- try {
1034
- const r = await window.fetch(this.options.ingestPoint + '/v1/web/start', {
1035
- method: 'POST',
1036
- headers: {
1037
- 'Content-Type': 'application/json',
1038
- },
1039
- body: JSON.stringify({
1040
- ...this.getTrackerInfo(),
1041
- timestamp,
1042
- doNotRecord: false,
1043
- bufferDiff: timestamp - this.coldStartTs,
1044
- userID: this.session.getInfo().userID,
1045
- token: isNewSession ? undefined : sessionToken,
1046
- deviceMemory,
1047
- jsHeapSizeLimit,
1048
- timezone: getTimezone(),
1049
- condition: conditionName,
1050
- assistOnly: startOpts.assistOnly ?? this.socketMode,
1051
- width: window.screen.width,
1052
- height: window.screen.height,
1053
- }),
1054
- });
1055
- if (r.status !== 200) {
1056
- const error = await r.text();
1057
- const reason = error === CANCELED ? CANCELED : `Server error: ${r.status}. ${error}`;
1058
- return UnsuccessfulStart(reason);
1059
- }
1060
- if (!this.worker) {
1061
- const reason = 'no worker found after start request (this should not happen in real world)';
1062
- this.signalError(reason, []);
1063
- return UnsuccessfulStart(reason);
1064
- }
1065
- const { token, userUUID, projectID, beaconSizeLimit, compressionThreshold, // how big the batch should be before we decide to compress it
1066
- delay, // derived from token
1067
- sessionID, // derived from token
1068
- startTimestamp, // real startTS (server time), derived from sessionID
1069
- userBrowser, userCity, userCountry, userDevice, userOS, userState, canvasEnabled, canvasQuality, canvasFPS, assistOnly: socketOnly, features, } = await r.json();
1070
- this.features = features ? features : this.features;
1071
- if (typeof token !== 'string' ||
1072
- typeof userUUID !== 'string' ||
1073
- (typeof startTimestamp !== 'number' && typeof startTimestamp !== 'undefined') ||
1074
- typeof sessionID !== 'string' ||
1075
- typeof delay !== 'number' ||
1076
- (typeof beaconSizeLimit !== 'number' && typeof beaconSizeLimit !== 'undefined')) {
1077
- const reason = `Incorrect server response: ${JSON.stringify(r)}`;
1078
- this.signalError(reason, []);
1079
- return UnsuccessfulStart(reason);
1080
- }
1081
- this.delay = delay;
1082
- this.session.setSessionToken(token);
1083
- this.session.setUserInfo({
1084
- userBrowser,
1085
- userCity,
1086
- userCountry,
1087
- userDevice,
1088
- userOS,
1089
- userState,
1090
- });
1091
- this.session.assign({
1092
- sessionID,
1093
- timestamp: startTimestamp || timestamp,
1094
- projectID,
1095
- });
1096
- if (socketOnly) {
1097
- this.socketMode = true;
1098
- this.worker.postMessage('stop');
1099
- }
1100
- else {
1101
- this.worker.postMessage({
1102
- type: 'auth',
1103
- token,
1104
- beaconSizeLimit,
1105
- });
1106
- }
1107
- if (!isNewSession && token === sessionToken) {
1108
- this.debug.log('continuing session on new tab', this.session.getTabId());
1109
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1110
- this.send(TabChange(this.session.getTabId()));
1111
- }
1112
- // (Re)send Metadata for the case of a new session
1113
- Object.entries(this.session.getInfo().metadata).forEach(([key, value]) => this.send(Metadata(key, value)));
1114
- this.localStorage.setItem(this.options.local_uuid_key, userUUID);
1115
- this.compressionThreshold = compressionThreshold;
1116
- const onStartInfo = { sessionToken: token, userUUID, sessionID };
1117
- // TODO: start as early as possible (before receiving the token)
1118
- /** after start */
1119
- this.startCallbacks.forEach((cb) => cb(onStartInfo)); // MBTODO: callbacks after DOM "mounted" (observed)
1120
- if (this.features['feature-flags']) {
1121
- void this.featureFlags.reloadFlags();
1122
- }
1123
- await this.tagWatcher.fetchTags(this.options.ingestPoint, token);
1124
- this.activityState = ActivityState.Active;
1125
- if (this.options.crossdomain?.enabled && !this.insideIframe) {
1126
- void this.bootChildrenFrames();
1127
- }
1128
- if (canvasEnabled && !this.options.canvas.disableCanvas) {
1129
- this.canvasRecorder =
1130
- this.canvasRecorder ??
1131
- new CanvasRecorder(this, {
1132
- fps: canvasFPS,
1133
- quality: canvasQuality,
1134
- isDebug: this.options.canvas.__save_canvas_locally,
1135
- fixedScaling: this.options.canvas.fixedCanvasScaling,
1136
- useAnimationFrame: this.options.canvas.useAnimationFrame,
1137
- });
1138
- }
1139
- /** --------------- COLD START BUFFER ------------------*/
1140
- if (isColdStart) {
1141
- const biggestBuffer = this.bufferedMessages1.length > this.bufferedMessages2.length
1142
- ? this.bufferedMessages1
1143
- : this.bufferedMessages2;
1144
- while (biggestBuffer.length > 0) {
1145
- await this.flushBuffer(biggestBuffer);
1146
- }
1147
- this.clearBuffers();
1148
- this.commit();
1149
- /** --------------- COLD START BUFFER ------------------*/
1150
- }
1151
- else {
1152
- if (this.insideIframe && this.rootId) {
1153
- this.observer.crossdomainObserve(this.rootId, this.frameOderNumber);
1154
- }
1155
- else {
1156
- this.observer.observe();
1157
- }
1158
- this.ticker.start();
1159
- }
1160
- this.canvasRecorder?.startTracking();
1161
- if (this.features['usability-test']) {
1162
- this.uxtManager = this.uxtManager
1163
- ? this.uxtManager
1164
- : new UserTestManager(this, uxtStorageKey);
1165
- let uxtId;
1166
- const savedUxtTag = this.localStorage.getItem(uxtStorageKey);
1167
- if (savedUxtTag) {
1168
- uxtId = parseInt(savedUxtTag, 10);
1169
- }
1170
- if (location?.search) {
1171
- const query = new URLSearchParams(location.search);
1172
- if (query.has('oruxt')) {
1173
- const qId = query.get('oruxt');
1174
- uxtId = qId ? parseInt(qId, 10) : undefined;
1175
- }
1176
- }
1177
- if (uxtId) {
1178
- if (!this.uxtManager.isActive) {
1179
- // eslint-disable-next-line
1180
- this.uxtManager.getTest(uxtId, token, Boolean(savedUxtTag)).then((id) => {
1181
- if (id) {
1182
- this.onUxtCb.forEach((cb) => cb(id));
1183
- }
1184
- });
1185
- }
1186
- else {
1187
- // @ts-ignore
1188
- this.onUxtCb.forEach((cb) => cb(uxtId));
1189
- }
1190
- }
1191
- }
1192
- return SuccessfulStart(onStartInfo);
1193
- }
1194
- catch (reason) {
1195
- this.stop();
1196
- this.session.reset();
1197
- if (!reason) {
1198
- console.error('Unknown error during start');
1199
- this.signalError('Unknown error', []);
1200
- return UnsuccessfulStart('Unknown error');
1201
- }
1202
- if (reason === CANCELED) {
1203
- this.signalError(CANCELED, []);
1204
- return UnsuccessfulStart(CANCELED);
1205
- }
1206
- this._debug('session_start', reason);
1207
- const errorMessage = reason instanceof Error ? reason.message : reason.toString();
1208
- this.signalError(errorMessage, []);
1209
- return UnsuccessfulStart(errorMessage);
1210
- }
1211
- }
1212
- addOnUxtCb(cb) {
1213
- // @ts-ignore
1214
- this.onUxtCb.push(cb);
1215
- }
1216
- getUxtId() {
1217
- return this.uxtManager?.getTestId();
1218
- }
1219
- async waitStart() {
1220
- return new Promise((resolve) => {
1221
- const check = () => {
1222
- if (this.canStart) {
1223
- resolve(true);
1224
- }
1225
- else {
1226
- setTimeout(check, 25);
1227
- }
1228
- };
1229
- check();
1230
- });
1231
- }
1232
- async waitStarted() {
1233
- return this.waitStatus(ActivityState.Active);
1234
- }
1235
- async waitStatus(status) {
1236
- return new Promise((resolve) => {
1237
- const check = () => {
1238
- if (this.activityState === status) {
1239
- resolve(true);
1240
- }
1241
- else {
1242
- setTimeout(check, 25);
1243
- }
1244
- };
1245
- check();
1246
- });
1247
- }
1248
- /**
1249
- * basically we ask other tabs during constructor
1250
- * and here we just apply 10ms delay just in case
1251
- * */
1252
- async start(...args) {
1253
- if (this.activityState === ActivityState.Active ||
1254
- this.activityState === ActivityState.Starting) {
1255
- const reason = 'OpenReplay: trying to call `start()` on the instance that has been started already.';
1256
- return Promise.resolve(UnsuccessfulStart(reason));
1257
- }
1258
- if (this.insideIframe) {
1259
- this.signalIframeTracker();
1260
- }
1261
- if (!document.hidden) {
1262
- await this.waitStart();
1263
- return this._start(...args);
1264
- }
1265
- else {
1266
- return new Promise((resolve) => {
1267
- const onVisibilityChange = async () => {
1268
- if (!document.hidden) {
1269
- await this.waitStart();
1270
- // eslint-disable-next-line
1271
- document.removeEventListener('visibilitychange', onVisibilityChange);
1272
- resolve(this._start(...args));
1273
- }
1274
- };
1275
- // eslint-disable-next-line
1276
- document.addEventListener('visibilitychange', onVisibilityChange);
1277
- });
1278
- }
1279
- }
1280
- forceFlushBatch() {
1281
- this.worker?.postMessage('forceFlushBatch');
1282
- }
1283
- getTabId() {
1284
- return this.session.getTabId();
1285
- }
1286
- clearBuffers() {
1287
- this.bufferedMessages1.length = 0;
1288
- this.bufferedMessages2.length = 0;
1289
- }
1290
- /**
1291
- * Creates a named hook that expects event name, data string and msg direction (up/down),
1292
- * it will skip any message bigger than 5 mb or event name bigger than 255 symbols
1293
- * @returns {(msgType: string, data: string, dir: "up" | "down") => void}
1294
- * */
1295
- trackWs(channelName) {
1296
- const channel = channelName;
1297
- return (msgType, data, dir = 'down') => {
1298
- if (typeof msgType !== 'string' ||
1299
- typeof data !== 'string' ||
1300
- data.length > 5 * 1024 * 1024 ||
1301
- msgType.length > 255) {
1302
- return;
1303
- }
1304
- this.send(WSChannel('websocket', channel, data, this.timestamp(), dir, msgType));
1305
- };
1306
- }
1307
- stop(stopWorker = true) {
1308
- if (this.activityState !== ActivityState.NotActive) {
1309
- console.trace('stopped');
1310
- try {
1311
- if (!this.insideIframe && this.options.crossdomain?.enabled) {
1312
- this.killChildrenFrames();
1313
- }
1314
- this.attributeSender.clear();
1315
- this.sanitizer.clear();
1316
- this.observer.disconnect();
1317
- this.nodes.clear();
1318
- this.ticker.stop();
1319
- this.stopCallbacks.forEach((cb) => cb());
1320
- this.tagWatcher.clear();
1321
- if (this.worker && stopWorker) {
1322
- this.worker.postMessage('stop');
1323
- }
1324
- this.canvasRecorder?.clear();
1325
- this.messages.length = 0;
1326
- this.trackedFrames = [];
1327
- this.parentActive = false;
1328
- this.canStart = false;
1329
- }
1330
- finally {
1331
- this.activityState = ActivityState.NotActive;
1332
- this.debug.log('OpenReplay tracking stopped.');
1333
- }
1334
- }
1335
- }
1336
- }