@himetrica/replaykit 0.0.0-stage → 0.2.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.
- package/LICENSE +201 -0
- package/README.md +91 -2
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +46 -0
- package/dist/index.d.ts +46 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/replaykit.global.js +79 -0
- package/dist/replaykit.global.js.map +1 -0
- package/package.json +45 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may accept and charge a
|
|
167
|
+
fee for acceptance of support, warranty, indemnity, or other
|
|
168
|
+
liability obligations and/or rights consistent with this License.
|
|
169
|
+
However, in accepting such obligations, You may act only on Your
|
|
170
|
+
own behalf and on Your sole responsibility, not on behalf of any
|
|
171
|
+
other Contributor, and only if You agree to indemnify, defend,
|
|
172
|
+
and hold each Contributor harmless for any liability incurred by,
|
|
173
|
+
or claims asserted against, such Contributor by reason of your
|
|
174
|
+
accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed" page as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Himetrica
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,92 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @himetrica/replaykit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Session replay and friction signals for the web, by [Himetrica](https://himetrica.com).
|
|
4
|
+
|
|
5
|
+
ReplayKit records what happened on the page in the sessions that matter (an error, a rage click, a checkout, a paying customer) and flags friction in every session: rage clicks, dead clicks, JavaScript errors, back navigation and abandoned forms. Every recording belongs to the visitor and session the Himetrica tracker already knows, so you can go from a customer, a campaign or a revenue number straight to what they saw.
|
|
6
|
+
|
|
7
|
+
ReplayKit is a separate, optional SDK. It needs the Himetrica tracker on the same page.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @himetrica/replaykit
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import * as ReplayKit from "@himetrica/replaykit";
|
|
17
|
+
|
|
18
|
+
ReplayKit.init({ apiKey: "hm_..." }); // the same public key the tracker uses
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Or with a script tag, after the tracker:
|
|
22
|
+
|
|
23
|
+
```html
|
|
24
|
+
<script src="https://unpkg.com/@himetrica/replaykit/dist/replaykit.global.js" data-api-key="hm_..."></script>
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
What gets recorded, and when, is configured per project in the dashboard (Settings → ReplayKit). The SDK reads it on every page, so changes apply without a deploy.
|
|
28
|
+
|
|
29
|
+
## When a session is recorded
|
|
30
|
+
|
|
31
|
+
By default ReplayKit does not record everything. It keeps the last ~30 seconds of the page in memory and only uploads a recording when one of these happens:
|
|
32
|
+
|
|
33
|
+
| Trigger | When |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| Error | A JavaScript error or unhandled promise rejection |
|
|
36
|
+
| Rage click | 3 or more clicks on the same spot within a second |
|
|
37
|
+
| Checkout | The visitor reaches a checkout path (configurable globs, e.g. `/checkout*`) |
|
|
38
|
+
| Paying customer | The visitor is a paying customer (decided by Himetrica) |
|
|
39
|
+
| Sample | A share of all sessions (5% by default) |
|
|
40
|
+
| Manual | You call `ReplayKit.start()` or `ReplayKit.trigger()` |
|
|
41
|
+
|
|
42
|
+
Because the last seconds are kept, the recording shows what led up to the trigger, including the previous page of the same session.
|
|
43
|
+
|
|
44
|
+
Signals are sent for every session (they are tiny and do not count against your recordings quota), even when recordings are turned off for the project.
|
|
45
|
+
|
|
46
|
+
## API
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
ReplayKit.init({ apiKey, apiUrl?, allowLocalhost?, debug? });
|
|
50
|
+
|
|
51
|
+
ReplayKit.start(); // record this session from now on
|
|
52
|
+
ReplayKit.trigger("refund"); // this moment matters: record it (reason is only logged with debug)
|
|
53
|
+
ReplayKit.stop(); // stop recording for the rest of the session
|
|
54
|
+
ReplayKit.consent(true); // the visitor accepted your banner (see "Consent")
|
|
55
|
+
ReplayKit.getRecordingId(); // id of the recording running on this page, or null
|
|
56
|
+
ReplayKit.shutdown(); // remove every listener
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Privacy
|
|
60
|
+
|
|
61
|
+
These are on for every project and cannot be turned off:
|
|
62
|
+
|
|
63
|
+
- **Every input is masked.** Typed values are replaced by `*` before anything leaves the browser, passwords and card fields included.
|
|
64
|
+
- **Card fields and blocked elements never leave the page.** `input[type=password]`, `[autocomplete^="cc-"]`, `[data-hm-block]` and `.hm-block` are replaced by an empty box of the same size.
|
|
65
|
+
- **Query strings are never sent** with signals or page URLs.
|
|
66
|
+
- Canvas, cross-origin iframes and images inlined as data are not recorded.
|
|
67
|
+
|
|
68
|
+
You can go further:
|
|
69
|
+
|
|
70
|
+
- Mark any text with `class="hm-mask"` or `data-hm-mask` to mask it.
|
|
71
|
+
- Turn on "Mask all text" in the project to mask every text node.
|
|
72
|
+
- Add your own selectors to block, and paths never to record.
|
|
73
|
+
|
|
74
|
+
### Consent
|
|
75
|
+
|
|
76
|
+
With "Require consent" on in the project, nothing is recorded until your consent banner calls:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
ReplayKit.consent(true); // or false to stop and drop anything not uploaded yet
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The answer is remembered on the device. `consent(false)` stops recording even when the project does not require consent.
|
|
83
|
+
|
|
84
|
+
## How it works
|
|
85
|
+
|
|
86
|
+
- Chunks of the recording are compressed in the browser (gzip) and uploaded straight to storage with a short-lived signed URL. They never pass through Himetrica's servers.
|
|
87
|
+
- Recordings are deleted after 30 days.
|
|
88
|
+
- rrweb is only downloaded on pages that may record; a page that only sends signals stays light.
|
|
89
|
+
|
|
90
|
+
## License
|
|
91
|
+
|
|
92
|
+
Apache-2.0
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var q="hm_rk_state",p=class{constructor(e){this.env=e;this.cache=null}load(e){if(_optionalChain([this, 'access', _2 => _2.cache, 'optionalAccess', _3 => _3.sid])===e)return this.cache;let t=null;try{let s=this.env.getSession(q);s&&(t=JSON.parse(s))}catch (e2){t=null}return(!t||t.sid!==e||typeof t.seq!="number")&&(t={sid:e,seq:0}),this.cache=t,t}save(e){this.cache=e;try{this.env.setSession(q,JSON.stringify(e))}catch (e3){}}};function E(i,e){return{startedAt:i,endedAt:i,activeMs:0,clicks:0,rageClicks:0,deadClicks:0,errors:0,pages:1,entryUrl:e}}var F=typeof window<"u"&&typeof document<"u";function Q(){let i=globalThis.crypto;if(i&&typeof i.randomUUID=="function")try{return i.randomUUID()}catch (e4){}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function L(i,e){try{return i().getItem(e)}catch (e5){return null}}function B(i,e,t){try{t===null?i().removeItem(e):i().setItem(e,t)}catch (e6){}}function Z(){if(typeof indexedDB>"u")return;let i=null,e=()=>_nullishCoalesce(i, () => ((i=new Promise((s,r)=>{let n=indexedDB.open("himetrica-replaykit",1);n.onupgradeneeded=()=>n.result.createObjectStore("kv"),n.onsuccess=()=>s(n.result),n.onerror=()=>r(n.error)})))),t=(s,r)=>e().then(n=>new Promise(a=>{let o=n.transaction("kv",s),l=r(o.objectStore("kv"));o.oncomplete=()=>a(l?l.result:void 0),o.onerror=o.onabort=()=>a(void 0)})).catch(()=>{});return{get:s=>t("readonly",r=>r.get(s)),set:(s,r)=>t("readwrite",n=>{n.put(r,s)}).then(()=>{}),del:s=>t("readwrite",r=>{r.delete(s)}).then(()=>{})}}function ee(){if(!(typeof CompressionStream>"u"||typeof Blob>"u"||typeof Response>"u"))return i=>new Response(new Blob([i]).stream().pipeThrough(new CompressionStream("gzip"))).blob()}function N(){let i=typeof fetch=="function"?fetch.bind(globalThis):void 0,e=typeof navigator<"u"?navigator:void 0;return{now:()=>Date.now(),uuid:()=>Q(),fetch:i,sendBeacon:e&&typeof e.sendBeacon=="function"?(t,s)=>{try{return e.sendBeacon(t,new Blob([s],{type:"text/plain"}))}catch (e7){return!1}}:void 0,getLocal:t=>L(()=>localStorage,t),setLocal:(t,s)=>B(()=>localStorage,t,s),getSession:t=>L(()=>sessionStorage,t),setSession:(t,s)=>B(()=>sessionStorage,t,s),getCookie:t=>{try{let s=document.cookie.match(new RegExp("(?:^|; )"+t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return s?decodeURIComponent(s[1]):null}catch (e8){return null}},store:Z(),gzip:ee(),setTimer:(t,s)=>setTimeout(t,s),clearTimer:t=>clearTimeout(t)}}function O(i){let e=i.getCookie("hm_vid")||i.getLocal("hm_visitor_id")||void 0,t=i.getCookie("hm_sid")||i.getSession("hm_session_id")||void 0;return{visitorId:e,sessionId:t}}function te(i,e){let t=i.trim().toLowerCase();if(!t)return!1;let s=(e||"/").toLowerCase();if(!t.includes("*")){let n=t.endsWith("/")&&t.length>1?t.slice(0,-1):t;return s===n||s.startsWith(n.endsWith("/")?n:n+"/")}return new RegExp("^"+t.split("*").map(ie).join(".*")+"$").test(s)}function x(i,e){for(let t of i)if(te(t,e))return!0;return!1}function ie(i){return i.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}function se(i){let e=3735928559,t=1103547991;for(let r=0;r<i.length;r++){let n=i.charCodeAt(r);e=Math.imul(e^n,2654435761),t=Math.imul(t^n,1597334677)}return e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),(4294967296*(2097151&t)+(e>>>0))/9007199254740992}function D(i,e){return e>0?e>=1?!0:se(i)<e:!1}function u(i){let e=i.search(/[?#]/);return e===-1?i:i.slice(0,e)}var w="replaykit:page";function U(i,e,t){let s=[],r=e;for(let n of i){let a;if(n.type===4)a=_optionalChain([n, 'access', _4 => _4.data, 'optionalAccess', _5 => _5.href]);else if(n.type===5){let c=n.data;_optionalChain([c, 'optionalAccess', _6 => _6.tag])===w&&(a=_optionalChain([c, 'access', _7 => _7.payload, 'optionalAccess', _8 => _8.href]))}if(typeof a!="string"||!a)continue;let o=a.search(/[?#]/),l=(o===-1?a:a.slice(0,o)).slice(0,500);if(l!==r&&(r=l,s.push({url:l,ts:n.timestamp}),s.length>=t))break}return s}var _=3e4,f=3e4;function re(i,e){return e>0&&i[e-1].type===4?e-1:e}function C(i,e,t=_){let s=e-t,r=-1,n=-1;for(let o=0;o<i.length;o++)if(i[o].type===2)if(n===-1&&(n=o),i[o].timestamp<=s)r=o;else break;if(r===-1&&(r=n),r===-1)return[];let a=re(i,r);return a===0?i:i.slice(a)}function I(i){try{return JSON.stringify(i).length}catch (e9){return 0}}var g=class{constructor(){this.burst=null}onClick(e){let t=this.burst;if(t&&e.ts-t.lastTs<=1e3&&ne(t.first,e))return t.count++,t.lastTs=e.ts,{trigger:t.count===3,finished:null};let s=t&&t.count>=3?t:null;return this.burst={first:e,count:1,lastTs:e.ts},{trigger:!1,finished:s}}flush(e){let t=this.burst;return!t||e-t.lastTs<=1e3?null:(this.burst=null,t.count>=3?t:null)}currentCount(){return _nullishCoalesce(_optionalChain([this, 'access', _9 => _9.burst, 'optionalAccess', _10 => _10.count]), () => (0))}};function ne(i,e){return i.target&&i.target===e.target?!0:Math.abs(i.x-e.x)<=30&&Math.abs(i.y-e.y)<=30}var H=500;function G(i){return i.isFormField||i.hasSelection||i.tag==="html"||i.tag==="body"?!1:i.insideInteractive||i.pointerCursor}function W(i){return i.mutations===0&&!i.urlChanged&&!i.scrolled&&!i.focusChanged&&!i.unloading}var oe=5e3;function A(i,e){if(!i)return 0;let t=e-i;return t>0&&t<=oe?t:0}var ae=["error","rage_click","manual"];function M(i,e,t){return t<=0||ae.includes(i)?0:Math.max(0,t-e)}function V(i){return!i.record||!i.canGzip||i.state.stopped||i.excluded||i.consent===!1?{kind:"off"}:i.requireConsent&&i.consent!==!0?{kind:"wait_consent"}:i.state.rid?{kind:"continue"}:i.forceTrigger?{kind:"start",trigger:i.forceTrigger}:i.checkout?{kind:"start",trigger:"checkout"}:i.sampled?{kind:"start",trigger:"sample"}:{kind:"buffer"}}function le(i){return i>=200&&i<300?"ok":i===401?"stop":i===403?"off":i===429?"quota":i===400||i===413||i===404||i===422?"drop":"retry"}var m=class{constructor(e,t,s){this.env=e;this.apiUrl=t;this.apiKey=s}url(e){return`${this.apiUrl}/api/t/r/${e}?apiKey=${encodeURIComponent(this.apiKey)}`}init(e){return this.post("init",e,!0)}chunk(e){return this.post("chunk",e,!0)}signals(e){return this.post("signals",e,!1)}beaconSignals(e){return!!_optionalChain([this, 'access', _11 => _11.env, 'access', _12 => _12.sendBeacon, 'optionalCall', _13 => _13(this.url("signals"),JSON.stringify(e))])}async put(e,t){if(!this.env.fetch)return"retry";try{let s=await this.env.fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"application/gzip"}});return s.status>=200&&s.status<300?"ok":s.status===400||s.status===413?"drop":"retry"}catch (e10){return"retry"}}async post(e,t,s){if(!this.env.fetch)return{outcome:"retry"};try{let r=await this.env.fetch(this.url(e),{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"text/plain"},keepalive:!1,credentials:"omit"}),n=le(r.status);if(n!=="ok"||!s)return{outcome:n};try{return{outcome:n,data:await r.json()}}catch (e11){return{outcome:"retry"}}}catch (e12){return{outcome:"retry"}}}},ue=2e3,he=6e4;function d(i){return Math.min(he,ue*2**Math.max(0,i-1))}var ce=5e3,de=200,pe=500,fe=2e3,v=class{constructor(e,t,s){this.env=e;this.api=t;this.ids=s;this.queue=[];this.timer=null;this.sentThisPage=0;this.failures=0;this.busy=!1;this.last=new Map;this.disabled=!1;this.held=!0}add(e){if(this.disabled||this.sentThisPage+this.queue.length>=de)return;let t=`${e.type}|${e.url}|${e.selector||""}|${e.detail||""}`,s=this.last.get(t);s!==void 0&&e.ts-s<fe||(this.last.set(t,e.ts),this.queue.push(e),this.queue.length>pe&&this.queue.shift(),!this.held&&(this.queue.length>=50?this.schedule(0):this.timer||this.schedule(ce)))}release(e){if(this.held=!1,!e){this.disable();return}this.queue.length&&this.schedule(0)}disable(){this.disabled=!0,this.queue=[],this.timer&&this.env.clearTimer(this.timer),this.timer=null}schedule(e){this.timer&&this.env.clearTimer(this.timer),this.timer=this.env.setTimer(()=>{this.timer=null,this.flush()},e)}async flush(){if(!(this.busy||this.held||this.disabled)){this.busy=!0;try{for(;this.queue.length&&!this.disabled;){let e=this.queue.slice(0,50),t=await this.api.signals({...this.ids(),signals:e});if(t.outcome==="ok"||t.outcome==="drop"||t.outcome==="quota"){this.queue.splice(0,e.length),this.sentThisPage+=e.length,this.failures=0;continue}if(t.outcome==="off"||t.outcome==="stop"){this.disable();return}this.failures++,this.schedule(d(this.failures));return}}finally{this.busy=!1}}}beacon(){if(!(this.held||this.disabled||!this.queue.length))for(;this.queue.length;){let e=this.queue.slice(0,50);if(!this.api.beaconSignals({...this.ids(),signals:e}))return;this.queue.splice(0,e.length),this.sentThisPage+=e.length}}get size(){return this.queue.length}};var Y='a[href],button,summary,[role="button"],[role="link"],[role="tab"],[role="menuitem"],[role="checkbox"],[role="switch"],[role="option"],[onclick]',j="input,textarea,select,label,option,[contenteditable],[contenteditable=true]",me=".hm-mask,[data-hm-mask],[data-hm-block],.hm-block",z=80,ve=200;function y(i){let e=[],t=i;for(let s=0;t&&s<3&&t.nodeType===1;s++){let r=t.tagName.toLowerCase();if(r==="html"||r==="body")break;if(t.id&&/^[A-Za-z][\w-]{0,40}$/.test(t.id)&&!/\d{3,}/.test(t.id)){e.unshift(`${r}#${t.id}`);break}let n=(typeof t.className=="string"?t.className:"").split(/\s+/).filter(a=>a&&a.length<30&&!/\d{3,}|^css-|^sc-|__/.test(a)).slice(0,2);e.unshift(r+n.map(a=>"."+a).join("")),t=t.parentElement}return e.join(" > ")}function X(i,e){if(e||i.closest(me)||i.closest(j))return;let t=(_nullishCoalesce(_nullishCoalesce(i.innerText, () => (i.textContent)), () => (""))).replace(/\s+/g," ").trim();return t?t.slice(0,z):_optionalChain([(i.getAttribute("aria-label")||i.getAttribute("title")||void 0), 'optionalAccess', _14 => _14.slice, 'call', _15 => _15(0,z)])}function ye(i){let e=!1;try{e=getComputedStyle(i).cursor==="pointer"}catch (e13){e=!1}let t=typeof getSelection=="function"?getSelection():null;return{tag:i.tagName.toLowerCase(),insideInteractive:!!i.closest(Y),isFormField:!!i.closest(j),pointerCursor:e,hasSelection:!!t&&!t.isCollapsed&&t.toString().trim().length>0}}function be(i){let e=i instanceof Element?i:i instanceof Node?i.parentElement:null;return e?e.closest(Y)||e:null}var b=class{constructor(e){this.h=e;this.rage=new g;this.rageEl=null;this.rageTimer=null;this.lastHref="";this.hrefTimer=null;this.unloading=!1;this.lastScrollInput=0;this.forms=new Map;this.errorsSeen=new Set;this.off=[]}start(){this.lastHref=location.href;let e=(t,s,r=window)=>{let n={capture:!0,passive:!0};r.addEventListener(t,s,n),this.off.push(()=>r.removeEventListener(t,s,n))};e("click",t=>this.onClick(t)),e("keydown",()=>this.h.input("key",this.h.now())),e("scroll",()=>{let t=this.h.now();t-this.lastScrollInput>250&&(this.lastScrollInput=t,this.h.input("scroll",t))}),e("error",t=>this.onError(t.message||_optionalChain([t, 'access', _16 => _16.error, 'optionalAccess', _17 => _17.message])||"")),e("unhandledrejection",t=>{let s=t.reason;this.onError(typeof s=="string"?s:_optionalChain([s, 'optionalAccess', _18 => _18.message])||"Unhandled promise rejection")}),e("popstate",()=>this.backNav()),e("input",t=>this.onField(t.target)),e("change",t=>this.onField(t.target)),e("submit",t=>{t.target instanceof HTMLFormElement&&this.forms.delete(t.target)}),e("pageshow",()=>{this.unloading=!1}),this.hrefTimer=setInterval(()=>this.checkHref(),1e3);try{_optionalChain([performance, 'access', _19 => _19.getEntriesByType, 'call', _20 => _20("navigation"), 'access', _21 => _21[0], 'optionalAccess', _22 => _22.type])==="back_forward"&&this.emit({type:"back_nav",detail:u(location.href)})}catch (e14){}}stop(){for(let e of this.off)e();this.off=[],this.hrefTimer&&clearInterval(this.hrefTimer),this.rageTimer&&clearTimeout(this.rageTimer),this.hrefTimer=this.rageTimer=null}pageHide(){this.unloading=!0,this.flushForms(),this.flushRage(!0)}emit(e){this.h.signal({ts:_nullishCoalesce(e.ts, () => (this.h.now())),url:u(location.href),...e})}checkHref(){let e=location.href;if(e===this.lastHref)return;let t=this.lastHref;this.lastHref=e,u(e)!==u(t)&&this.h.navigated(u(e))}onClick(e){let t=this.h.now();this.h.input("click",t);let s=be(e.target);if(!s)return;let r=y(s),n=this.rage.onClick({x:e.clientX,y:e.clientY,ts:t,target:r});n.finished&&this.reportRage(n.finished.count,n.finished.first.ts),n.trigger&&this.h.trigger("rage_click"),this.rageEl=this.rage.currentCount()===1?s:this.rageEl,this.rageTimer&&clearTimeout(this.rageTimer),this.rageTimer=setTimeout(()=>this.flushRage(!1),1050),this.rage.currentCount()===1&&this.watchDeadClick(s,r,t)}flushRage(e){let t=this.rage.flush(e?Number.MAX_SAFE_INTEGER:this.h.now());t&&this.reportRage(t.count,t.first.ts)}reportRage(e,t){let s=this.rageEl;this.emit({type:"rage_click",ts:t,count:e,selector:s?y(s):void 0,text:s?X(s,this.h.maskAllText()):void 0})}watchDeadClick(e,t,s){if(!G(ye(e)))return;let r=location.href,n=`${scrollX},${scrollY}`,a=document.activeElement,o=0,l=null;try{l=new MutationObserver(c=>{o+=c.length}),l.observe(document.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0})}catch (e15){return}setTimeout(()=>{if(_optionalChain([l, 'optionalAccess', _23 => _23.disconnect, 'call', _24 => _24()]),this.rage.currentCount()>1)return;W({mutations:o,urlChanged:location.href!==r,scrolled:`${scrollX},${scrollY}`!==n,focusChanged:document.activeElement!==a&&document.activeElement!==e,unloading:this.unloading})&&this.emit({type:"dead_click",ts:s,selector:t,text:X(e,this.h.maskAllText())})},H)}onError(e){let t=(e||"Error").slice(0,ve);this.errorsSeen.has(t)||(this.errorsSeen.add(t),this.emit({type:"error",detail:t}),this.h.trigger("error"))}backNav(){this.emit({type:"back_nav",detail:u(location.href)}),this.checkHref()}onField(e){if(!(e instanceof Element))return;let t=e.closest("form");if(!t)return;let s=e.getAttribute("name")||e.id||y(e),r=this.forms.get(t);r||this.forms.set(t,r=new Set),r.add(s)}flushForms(){for(let[e,t]of this.forms)!e.isConnected&&t.size===0||this.emit({type:"form_abandon",selector:y(e),count:t.size});this.forms.clear()}};var ke=["[data-hm-block]",".hm-block",'[autocomplete^="cc-"]','input[type="password"]'],Se=".hm-mask,[data-hm-mask]",Re=null;function Te(){return _nullishCoalesce(Re, () => ((Re=Promise.resolve().then(() => _interopRequireWildcard(require("@rrweb/record"))).then(i=>i.record))))}function Ee(i){return i.filter(e=>{if(!e||typeof e!="string")return!1;try{return document.createDocumentFragment().querySelector(e),!0}catch (e16){return!1}})}var k=class{constructor(){this.record=null;this.stopped=!1}async start(e){try{this.record=await Te()}catch (e17){return!1}if(this.stopped)return!1;try{return this.stopFn=_nullishCoalesce(this.record({emit:t=>e.emit(t),checkoutEveryNms:f,maskAllInputs:!0,maskInputOptions:{password:!0},maskTextSelector:e.maskAllText?"*":Se,blockSelector:Ee([...ke,...e.blockSelectors]).join(","),recordCanvas:!1,recordCrossOriginIframes:!1,inlineImages:!1,collectFonts:!1,slimDOMOptions:{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:!0},sampling:{mousemove:50,scroll:150,input:"last"}}), () => (void 0)),!!this.stopFn}catch (e18){return!1}}snapshot(){try{_optionalChain([this, 'access', _25 => _25.record, 'optionalAccess', _26 => _26.takeFullSnapshot, 'call', _27 => _27(!0)])}catch (e19){}}page(e){try{_optionalChain([this, 'access', _28 => _28.record, 'optionalAccess', _29 => _29.addCustomEvent, 'call', _30 => _30(w,{href:e})])}catch (e20){}}stop(){this.stopped=!0;try{_optionalChain([this, 'access', _31 => _31.stopFn, 'optionalCall', _32 => _32()])}catch (e21){}this.stopFn=void 0}};var xe=3e4,we=256*1024,S=i=>`rk:pending:${i}`,R=class{constructor(e,t,s,r,n){this.env=e;this.api=t;this.states=s;this.ids=r;this.hooks=n;this.queue=[];this.inflight=[];this.queuedBytes=0;this.timer=null;this.retryTimer=null;this.failures=0;this.busy=!1;this.stopped=!1;this.epoch=0;this.parked=!1;this.lastPage="";this.lastPageRid=""}state(){return this.states.load(this.ids.sid)}async restorePending(){let e=this.env.store;if(!e)return;let t=await e.get(S(this.ids.sid));if(!t)return;await e.del(S(this.ids.sid));let s=this.state();!s.rid||t.rid!==s.rid||!Array.isArray(t.events)||t.events.length===0||(this.queue=t.events.concat(this.queue),this.queuedBytes+=t.events.reduce((r,n)=>r+I(n),0),this.schedule(0))}add(e){this.stopped||(this.queue.push(e),this.queuedBytes+=I(e),this.queuedBytes>=we?this.schedule(0):this.timer||this.schedule(xe))}addMany(e){for(let t of e)this.add(t)}schedule(e){this.timer&&this.env.clearTimer(this.timer),this.timer=this.env.setTimer(()=>{this.timer=null,this.flush()},e)}async flush(){if(this.busy||this.stopped)return;let e=this.epoch;this.busy=!0;try{for(;!this.stopped&&e===this.epoch&&(this.inflight.length>0||this.queue.length>0);)if(this.inflight.length===0&&(this.inflight=this.queue,this.queue=[],this.queuedBytes=0),!await this.sendInflight())return}finally{this.busy=!1}}async sendInflight(){_optionalChain([this, 'access', _33 => _33.hooks, 'access', _34 => _34.beforeChunk, 'optionalCall', _35 => _35()]);let e=this.state();if(!e.rid||!e.trigger||!e.stats)return!1;if(e.seq>=600)return this.stop("limit"),!1;let t=this.env.gzip;if(!t)return this.stop("off"),!1;let s={v:1,rid:e.rid,seq:e.seq,events:this.inflight},r=await t(JSON.stringify(s));if(r.size>2097152){if(this.inflight.length>1){let P=Math.ceil(this.inflight.length/2);return this.queue=this.inflight.slice(P).concat(this.queue),this.inflight=this.inflight.slice(0,P),!0}return this.stop("limit"),!1}let n=this.lastPageRid===e.rid?this.lastPage:"",a=U(this.inflight,n,50),o=await this.api.chunk({rid:e.rid,sid:this.ids.sid,vid:this.ids.vid,seq:e.seq,bytes:r.size,trigger:e.trigger,stats:e.stats,pages:a});if(o.outcome==="drop")return this.inflight=[],!0;if(o.outcome==="quota")return this.stop("quota"),!1;if(o.outcome==="off"||o.outcome==="stop")return this.stop("off"),!1;if(o.outcome!=="ok"||!_optionalChain([o, 'access', _36 => _36.data, 'optionalAccess', _37 => _37.url]))return this.retryLater(),!1;let l=await this.api.put(o.data.url,r);if(l==="drop")return this.inflight=[],!0;if(l!=="ok")return this.retryLater(),!1;this.failures=0,this.inflight=[],a.length&&(this.lastPage=a[a.length-1].url,this.lastPageRid=e.rid);let c=this.state();return c.rid===e.rid&&this.states.save({...c,seq:e.seq+1}),this.parked&&(this.queue.length?this.persist():this.unpersist()),!0}retryLater(){this.failures++,this.retryTimer&&this.env.clearTimer(this.retryTimer),this.retryTimer=this.env.setTimer(()=>{this.retryTimer=null,this.flush()},d(this.failures))}stop(e){this.stopped=!0,this.queue=[],this.inflight=[],this.queuedBytes=0,this.clearTimers(),this.hooks.onStop(e)}clearTimers(){this.timer&&this.env.clearTimer(this.timer),this.retryTimer&&this.env.clearTimer(this.retryTimer),this.timer=this.retryTimer=null}persist(){let e=this.env.store,t=this.state(),s=this.inflight.concat(this.queue);!e||!t.rid||s.length===0||this.stopped||(this.parked=!0,e.set(S(this.ids.sid),{rid:t.rid,events:s}))}unpersist(){this.parked&&(this.parked=!1,_optionalChain([this, 'access', _38 => _38.env, 'access', _39 => _39.store, 'optionalAccess', _40 => _40.del, 'call', _41 => _41(S(this.ids.sid))]))}discard(){this.epoch++,this.stopped=!0,this.queue=[],this.inflight=[],this.queuedBytes=0,this.clearTimers(),this.unpersist()}get pendingEvents(){return this.queue.length+this.inflight.length}};var J="hm_rk_consent",K=i=>`rk:buf:${i}`,Ce=500,Ie=15e3,Ae=3,T=class{constructor(e,t=N()){this.options=e;this.ids=null;this.queue=null;this.collector=null;this.recorder=null;this.uploader=null;this.init=null;this.config=null;this.mode="idle";this.buffer=[];this.recent=[];this.stats=null;this.lastInputTs=0;this.earlyTrigger=null;this.pending=null;this.pendingGen=0;this.baseVisibleMs=0;this.pageVisibleMs=0;this.visibleSince=null;this.destroyed=!1;this.offWindow=[];this.env=t;let s=(e.apiUrl||"https://app.himetrica.com").replace(/\/+$/,"");this.api=new m(t,s,e.apiKey),this.states=new p(t)}log(...e){this.options.debug&&console.debug("[ReplayKit]",...e)}start(){if(!F||!this.options.apiKey)return;let e=location.hostname;if(!this.options.allowLocalhost&&(e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e.endsWith(".localhost"))){this.log("localhost: idle (allowLocalhost to enable)");return}this.trackVisibility();let t=this.env.now(),s=()=>{if(this.destroyed)return;let r=O(this.env);r.sessionId&&r.visitorId?(this.ids={sid:r.sessionId,vid:r.visitorId},this.boot()):this.env.now()-t<Ie?this.env.setTimer(s,Ce):this.log("no tracker ids on this page: idle")};s()}boot(){let e=this.ids;this.baseVisibleMs=_nullishCoalesce(this.states.load(e.sid).visibleMs, () => (0)),this.queue=new v(this.env,this.api,()=>({...e,rid:this.mode==="live"?this.state().rid:void 0})),this.collector=new b({now:()=>this.env.now(),maskAllText:()=>_nullishCoalesce(_optionalChain([this, 'access', _42 => _42.config, 'optionalAccess', _43 => _43.maskAllText]), () => (!0)),signal:t=>this.onSignal(t),trigger:t=>this.trigger(t),input:(t,s)=>this.onInput(t,s),navigated:t=>this.onNavigate(t)}),this.collector.start(),this.listenPage(),this.callInit(1)}state(){return this.states.load(this.ids.sid)}async callInit(e){let t=this.ids,s=await this.api.init({sid:t.sid,vid:t.vid,url:u(location.href)});if(!this.destroyed){if(s.outcome==="ok"&&s.data)return this.applyInit(s.data);if(s.outcome==="retry"&&e<Ae){this.env.setTimer(()=>{this.callInit(e+1)},d(e));return}if(this.log("init refused:",s.outcome),s.outcome==="quota"){_optionalChain([this, 'access', _44 => _44.queue, 'optionalAccess', _45 => _45.release, 'call', _46 => _46(!0)]),this.mode="off";return}this.shutdown()}}applyInit(e){if(this.init=e,this.config=e.config,this.queue.release(e.signals),!e.signals&&!e.record){this.shutdown();return}this.decide()}consentValue(){let e=this.env.getLocal(J);return e==="1"?!0:e==="0"?!1:null}triggerEnabled(e){return e==="manual"||e==="sample"?!0:!!_optionalChain([this, 'access', _47 => _47.config, 'optionalAccess', _48 => _48.triggers, 'access', _49 => _49.includes, 'call', _50 => _50(e)])}pathExcluded(){return x(_nullishCoalesce(_optionalChain([this, 'access', _51 => _51.config, 'optionalAccess', _52 => _52.excludePaths]), () => ([])),location.pathname)}onCheckoutPath(){return this.triggerEnabled("checkout")&&x(_nullishCoalesce(_optionalChain([this, 'access', _53 => _53.config, 'optionalAccess', _54 => _54.checkoutPaths]), () => ([])),location.pathname)}decide(){if(!this.init||!this.config)return;let e=this.state(),t=V({record:this.init.record,canGzip:!!this.env.gzip,state:e,excluded:this.pathExcluded(),requireConsent:this.config.requireConsent,consent:this.consentValue(),forceTrigger:this.init.forceTrigger,sampled:D(this.ids.sid,this.config.sampleRate),checkout:this.onCheckoutPath()});if(this.log("page:",t.kind,t.kind==="start"?t.trigger:""),t.kind==="off"||t.kind==="wait_consent"){this.mode=t.kind;return}if(t.kind==="continue"){this.mode="live";let s=_nullishCoalesce(e.stats, () => (E(this.env.now(),u(location.href))));this.stats={...s,pages:s.pages+1},this.makeUploader(),this.uploader.restorePending(),this.startRecorder();return}this.mode="buffer",this.restoreParkedBuffer().then(async()=>{if(this.mode!=="buffer"||(await this.startRecorder(),this.mode!=="buffer"))return;let s=t.kind==="start"?t.trigger:this.earlyTrigger;this.earlyTrigger=null,s&&this.triggerEnabled(s)&&this.requestPromote(s)})}async restoreParkedBuffer(){let e=this.env.store;if(!e)return;let t=K(this.ids.sid),s=await e.get(t);if(!s)return;e.del(t),this.env.now()-s.at<_+f&&Array.isArray(s.events)&&s.events.length&&(this.buffer=s.events.concat(this.buffer))}async startRecorder(){if(this.recorder)return;let e=this.recorder=new k;!await e.start({blockSelectors:_nullishCoalesce(_optionalChain([this, 'access', _55 => _55.config, 'optionalAccess', _56 => _56.blockSelectors]), () => ([])),maskAllText:_nullishCoalesce(_optionalChain([this, 'access', _57 => _57.config, 'optionalAccess', _58 => _58.maskAllText]), () => (!1)),emit:s=>this.onEvent(s)})&&this.recorder===e&&(this.log("rrweb failed to start"),this.recorder=null,this.mode="off")}onEvent(e){if(this.mode==="buffer"){this.buffer.push(e),e.type===2&&(this.buffer=C(this.buffer,this.env.now()));return}this.mode==="live"&&this.uploader&&(this.stats&&(this.stats.endedAt=Math.max(this.stats.endedAt,e.timestamp)),this.uploader.add(e))}makeUploader(){this.uploader=new R(this.env,this.api,this.states,this.ids,{onStop:e=>this.stopRecording(e),beforeChunk:()=>this.saveStats()})}saveStats(){if(!this.stats||this.mode!=="live")return;let e=this.state();e.rid&&this.states.save({...e,stats:this.stats})}trigger(e){if(!(this.destroyed||!this.ids)){if(!this.init){this.earlyTrigger||(this.earlyTrigger=e);return}if(!(this.mode!=="buffer"||!this.triggerEnabled(e))){if(!this.recorder){_nullishCoalesce(this.earlyTrigger, () => ((this.earlyTrigger=e)));return}this.requestPromote(e)}}}trackVisibility(){document.visibilityState==="visible"&&(this.visibleSince=this.env.now());let e=()=>{let t=this.env.now();document.visibilityState==="hidden"?(this.visibleSince!==null&&(this.pageVisibleMs+=t-this.visibleSince),this.visibleSince=null):this.visibleSince===null&&(this.visibleSince=t,this.pending&&this.schedulePending())};document.addEventListener("visibilitychange",e),this.offWindow.push(()=>document.removeEventListener("visibilitychange",e))}visibleMs(){let e=this.visibleSince!==null?this.env.now()-this.visibleSince:0;return this.baseVisibleMs+this.pageVisibleMs+e}requestPromote(e){let t=M(e,this.visibleMs(),_nullishCoalesce(_optionalChain([this, 'access', _59 => _59.config, 'optionalAccess', _60 => _60.minDurationMs]), () => (0)));if(t===0){this.pending=null,this.promote(e);return}_nullishCoalesce(this.pending, () => ((this.pending=e))),this.log("waiting for the minimum duration:",e,t,"ms"),this.schedulePending()}schedulePending(){let e=this.pending;if(!e)return;let t=++this.pendingGen,s=M(e,this.visibleMs(),_nullishCoalesce(_optionalChain([this, 'access', _61 => _61.config, 'optionalAccess', _62 => _62.minDurationMs]), () => (0)));this.env.setTimer(()=>{t!==this.pendingGen||this.pending!==e||this.mode!=="buffer"||this.destroyed||this.visibleSince!==null&&this.requestPromote(e)},Math.max(s,50))}promote(e){let t=this.env.now(),s=this.buffer;this.buffer=[];let r=s.length?s[0].timestamp:t,n=E(r,u(location.href));n.endedAt=Math.max(s.length?s[s.length-1].timestamp:t,t),this.pending=null;let a=0;for(let o of this.recent)o.ts<r||(o.k==="click"?n.clicks++:o.k==="rage"?n.rageClicks++:o.k==="dead"?n.deadClicks++:o.k==="error"&&n.errors++,(o.k==="click"||o.k==="input")&&(n.activeMs+=A(a,o.ts),a=o.ts));this.recent=[],this.stats=n,this.states.save({...this.state(),rid:this.env.uuid(),seq:0,trigger:e,stats:n,stopped:void 0}),this.mode="live",this.log("recording:",e),this.makeUploader(),this.uploader.addMany(s),s.length||_optionalChain([this, 'access', _63 => _63.recorder, 'optionalAccess', _64 => _64.snapshot, 'call', _65 => _65()]),this.uploader.flush()}stopRecording(e){this.log("recording stopped:",e),_optionalChain([this, 'access', _66 => _66.recorder, 'optionalAccess', _67 => _67.stop, 'call', _68 => _68()]),this.recorder=null,this.mode="off",this.buffer=[];let t=this.state();this.states.save({...t,stopped:e})}onSignal(e){if(this.mode==="live"&&this.stats)e.type==="rage_click"?this.stats.rageClicks++:e.type==="dead_click"?this.stats.deadClicks++:e.type==="error"&&this.stats.errors++;else if(this.mode==="buffer"||this.mode==="idle"){let t=e.type==="rage_click"?"rage":e.type==="dead_click"?"dead":e.type==="error"?"error":null;t&&this.pushRecent(t,e.ts)}_optionalChain([this, 'access', _69 => _69.queue, 'optionalAccess', _70 => _70.add, 'call', _71 => _71(e)])}onInput(e,t){this.mode==="live"&&this.stats?(this.stats.activeMs+=A(this.lastInputTs,t),e==="click"&&this.stats.clicks++):(this.mode==="buffer"||this.mode==="idle")&&this.pushRecent(e==="click"?"click":"input",t),this.lastInputTs=t}pushRecent(e,t){this.recent.push({k:e,ts:t}),this.recent.length>1e3&&this.recent.splice(0,this.recent.length-1e3)}onNavigate(e){if(!this.init||!this.config)return;this.mode==="live"&&this.stats&&this.stats.pages++;let t=this.pathExcluded();if(t&&(this.mode==="live"||this.mode==="buffer")){_optionalChain([this, 'access', _72 => _72.recorder, 'optionalAccess', _73 => _73.stop, 'call', _74 => _74()]),this.recorder=null,this.mode==="buffer"&&(this.buffer=[]),_optionalChain([this, 'access', _75 => _75.uploader, 'optionalAccess', _76 => _76.flush, 'call', _77 => _77()]),this.mode="off";return}if(!t&&this.mode==="off"&&!this.state().stopped){this.uploader=null,this.decide();return}_optionalChain([this, 'access', _78 => _78.recorder, 'optionalAccess', _79 => _79.page, 'call', _80 => _80(e)]),this.onCheckoutPath()&&this.trigger("checkout")}listenPage(){let e=r=>{if(r&&_optionalChain([this, 'access', _81 => _81.collector, 'optionalAccess', _82 => _82.pageHide, 'call', _83 => _83()]),this.states.save({...this.state(),visibleMs:this.visibleMs()}),_optionalChain([this, 'access', _84 => _84.queue, 'optionalAccess', _85 => _85.beacon, 'call', _86 => _86()]),this.mode==="live")this.saveStats(),_optionalChain([this, 'access', _87 => _87.uploader, 'optionalAccess', _88 => _88.persist, 'call', _89 => _89()]);else if(this.mode==="buffer"&&this.buffer.length&&this.env.store){let n=C(this.buffer,this.env.now());this.env.store.set(K(this.ids.sid),{at:this.env.now(),events:n})}},t=()=>{document.visibilityState==="hidden"?e(!1):_optionalChain([this, 'access', _90 => _90.uploader, 'optionalAccess', _91 => _91.unpersist, 'call', _92 => _92()])},s=()=>e(!0);document.addEventListener("visibilitychange",t),window.addEventListener("pagehide",s),this.offWindow.push(()=>document.removeEventListener("visibilitychange",t),()=>window.removeEventListener("pagehide",s))}manualStart(e){if(this.ids){if(e&&this.log("manual trigger:",e),this.state().stopped==="manual"){this.states.save({...this.state(),stopped:void 0,rid:void 0,seq:0,trigger:void 0,stats:void 0}),this.uploader=null,this.earlyTrigger="manual",this.decide();return}this.trigger("manual")}}manualStop(){this.ids&&(_optionalChain([this, 'access', _93 => _93.recorder, 'optionalAccess', _94 => _94.stop, 'call', _95 => _95()]),this.recorder=null,this.buffer=[],this.mode==="live"&&(this.saveStats(),_optionalChain([this, 'access', _96 => _96.uploader, 'optionalAccess', _97 => _97.flush, 'call', _98 => _98()])),this.mode="off",this.states.save({...this.state(),stopped:"manual"}))}consent(e){if(this.env.setLocal(J,e?"1":"0"),!!this.ids){if(e){this.mode==="wait_consent"&&this.decide();return}_optionalChain([this, 'access', _99 => _99.recorder, 'optionalAccess', _100 => _100.stop, 'call', _101 => _101()]),this.recorder=null,this.buffer=[],_optionalChain([this, 'access', _102 => _102.uploader, 'optionalAccess', _103 => _103.discard, 'call', _104 => _104()]),_optionalChain([this, 'access', _105 => _105.env, 'access', _106 => _106.store, 'optionalAccess', _107 => _107.del, 'call', _108 => _108(K(this.ids.sid))]),this.mode="off"}}recordingId(){return this.mode==="live"&&this.ids?_nullishCoalesce(this.state().rid, () => (null)):null}shutdown(){_optionalChain([this, 'access', _109 => _109.collector, 'optionalAccess', _110 => _110.stop, 'call', _111 => _111()]),_optionalChain([this, 'access', _112 => _112.queue, 'optionalAccess', _113 => _113.disable, 'call', _114 => _114()]),_optionalChain([this, 'access', _115 => _115.recorder, 'optionalAccess', _116 => _116.stop, 'call', _117 => _117()]),this.recorder=null,this.mode="off"}destroy(){this.destroyed=!0,this.shutdown();for(let e of this.offWindow)e();this.offWindow=[]}};var h=null;function dt(i){h||(h=new T(i),h.start())}function pt(){_optionalChain([h, 'optionalAccess', _118 => _118.manualStart, 'call', _119 => _119()])}function ft(i){_optionalChain([h, 'optionalAccess', _120 => _120.manualStart, 'call', _121 => _121(i)])}function gt(){_optionalChain([h, 'optionalAccess', _122 => _122.manualStop, 'call', _123 => _123()])}function mt(i){if(h)h.consent(i);else try{localStorage.setItem("hm_rk_consent",i?"1":"0")}catch (e22){}}function vt(){return _nullishCoalesce(_optionalChain([h, 'optionalAccess', _124 => _124.recordingId, 'call', _125 => _125()]), () => (null))}function yt(){_optionalChain([h, 'optionalAccess', _126 => _126.destroy, 'call', _127 => _127()]),h=null}exports.consent = mt; exports.getRecordingId = vt; exports.init = dt; exports.shutdown = yt; exports.start = pt; exports.stop = gt; exports.trigger = ft;
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/state.ts","../src/env.ts","../src/identity.ts","../src/match.ts","../src/buffer.ts","../src/detect.ts","../src/decide.ts","../src/transport.ts"],"names":["KEY","StateStore","env","sid","s","raw","emptyStats","now","entryUrl","isBrowser","uuidV4","c","ch","r","safeGet","storage","key","safeSet","value","indexedDbStore","dbp","open","resolve","reject","req","run","mode","fn","db","tx","gzipFn","text","browserEnv","originalFetch","nav","url","body","name","match","ms","h","readIdentity","visitorId","sessionId","matchPath","pattern","pathname","p","path","base","escapeRegExp","matchAny","patterns","sampleDraw","h1","h2","i","inSample","rate","stripUrl","href","cut","PAGE_TAG","pagesOf","events","prev","max","out","last","e","d","BUFFER_WINDOW_MS","CHECKOUT_MS","snapshotStart","trimBuffer","windowMs","cutoff","keepFrom","firstSnapshot","start","approxBytes","RageDetector","b","near","finished","a","DEAD_CLICK_WAIT_MS","isDeadClickCandidate","f","isDeadClick","ACTIVE_GAP_MS","activeIncrement","lastInputTs","ts","gap","MIN_DURATION_EXEMPT","waitBeforeRecording","t","visibleMs","minDurationMs","decidePage","outcomeOf","status","Api","apiUrl","apiKey","op"],"mappings":"AAyBA,u8BAAMA,CAAAA,CAAM,aAAA,CAECC,CAAAA,CAAN,KAAiB,CAGtB,WAAA,CAA6BC,CAAAA,CAAU,CAAV,IAAA,CAAA,GAAA,CAAAA,CAAAA,CAF7B,IAAA,CAAQ,KAAA,CAA6B,IAEG,CAExC,IAAA,CAAKC,CAAAA,CAA2B,CAC9B,EAAA,iBAAI,IAAA,qBAAK,KAAA,6BAAO,KAAA,GAAQA,CAAAA,CAAK,OAAO,IAAA,CAAK,KAAA,CACzC,IAAIC,CAAAA,CAAyB,IAAA,CAC7B,GAAI,CACF,IAAMC,CAAAA,CAAM,IAAA,CAAK,GAAA,CAAI,UAAA,CAAWL,CAAG,CAAA,CAC/BK,CAAAA,EAAAA,CAAKD,CAAAA,CAAI,IAAA,CAAK,KAAA,CAAMC,CAAG,CAAA,CAC7B,CAAA,UAAQ,CACND,CAAAA,CAAI,IACN,CACA,MAAA,CAAI,CAACA,CAAAA,EAAKA,CAAAA,CAAE,GAAA,GAAQD,CAAAA,EAAO,OAAOC,CAAAA,CAAE,GAAA,EAAQ,QAAA,CAAA,EAAA,CAAUA,CAAAA,CAAI,CAAE,GAAA,CAAAD,CAAAA,CAAK,GAAA,CAAK,CAAE,CAAA,CAAA,CACxE,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACNA,CACT,CAEA,IAAA,CAAKA,CAAAA,CAAuB,CAC1B,IAAA,CAAK,KAAA,CAAQA,CAAAA,CACb,GAAI,CACF,IAAA,CAAK,GAAA,CAAI,UAAA,CAAWJ,CAAAA,CAAK,IAAA,CAAK,SAAA,CAAUI,CAAC,CAAC,CAC5C,CA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AAA,CAAE,cAAA,EAAkB,CAAA,CAAE,OAAA,GAAY,CAAA,CAAA,CAAa,CAAE,IAAA,CAAM,cAAe,CAAA,CACtE,CAAA,CAAE,KAAA,CAAM,GAAA,CAAY,CAAE,IAAA,CAAM,UAAW,CAAA,CACvC,CAAA,CAAE,YAAA,CAAqB,CAAE,IAAA,CAAM,OAAA,CAAS,OAAA,CAAS,CAAA,CAAE,YAAa,CAAA,CAChE,CAAA,CAAE,QAAA,CAAiB,CAAE,IAAA,CAAM,OAAA,CAAS,OAAA,CAAS,UAAW,CAAA,CACxD,CAAA,CAAE,OAAA,CAAgB,CAAE,IAAA,CAAM,OAAA,CAAS,OAAA,CAAS,QAAS,CAAA,CAClD,CAAE,IAAA,CAAM,QAAS,CAC1B,CClCO,SAASC,EAAAA,CAAUC,CAAAA,CAAyB,CACjD,OAAIA,CAAAA,EAAU,GAAA,EAAOA,CAAAA,CAAS,GAAA,CAAY,IAAA,CACtCA,CAAAA,GAAW,GAAA,CAAY,MAAA,CACvBA,CAAAA,GAAW,GAAA,CAAY,KAAA,CACvBA,CAAAA,GAAW,GAAA,CAAY,OAAA,CACvBA,CAAAA,GAAW,GAAA,EAAOA,CAAAA,GAAW,GAAA,EAAOA,CAAAA,GAAW,GAAA,EAAOA,CAAAA,GAAW,GAAA,CAAY,MAAA,CAC1E,OACT,CAOO,IAAMC,CAAAA,CAAN,KAAU,CACf,WAAA,CACmBrG,CAAAA,CACAsG,CAAAA,CACAC,CAAAA,CACjB,CAHiB,IAAA,CAAA,GAAA,CAAAvG,CAAAA,CACA,IAAA,CAAA,MAAA,CAAAsG,CAAAA,CACA,IAAA,CAAA,MAAA,CAAAC,CAChB,CAEH,GAAA,CAAIC,CAAAA,CAA0C,CAC5C,MAAO,CAAA,EAAA","file":"/home/runner/work/himetrica-replaykit/himetrica-replaykit/dist/index.cjs","sourcesContent":["// Per-session recording state, in sessionStorage so it follows the session across the\n// pages of a multi-page site (each page load is a new SDK instance).\n//\n// Keyed to the tracker session id: when the tracker rolls a new session (30 min idle,\n// new UTM...), the stored state belongs to the old one and is discarded.\n\nimport type { Env } from \"./env\";\nimport type { ReplayKitRecordingStats, ReplayKitTrigger } from \"./protocol\";\n\nexport type StopReason = \"quota\" | \"manual\" | \"limit\" | \"off\";\n\nexport interface SessionState {\n sid: string;\n /** Recording id, set once a trigger fired; absent while only buffering. */\n rid?: string;\n /** Next chunk sequence number to upload. */\n seq: number;\n trigger?: ReplayKitTrigger;\n /** Set when recording must not (re)start for the rest of the session. */\n stopped?: StopReason;\n stats?: ReplayKitRecordingStats;\n /** Visible tab time of the session's earlier pages, for the minimum duration. */\n visibleMs?: number;\n}\n\nconst KEY = \"hm_rk_state\";\n\nexport class StateStore {\n private cache: SessionState | null = null;\n\n constructor(private readonly env: Env) {}\n\n load(sid: string): SessionState {\n if (this.cache?.sid === sid) return this.cache;\n let s: SessionState | null = null;\n try {\n const raw = this.env.getSession(KEY);\n if (raw) s = JSON.parse(raw) as SessionState;\n } catch {\n s = null;\n }\n if (!s || s.sid !== sid || typeof s.seq !== \"number\") s = { sid, seq: 0 };\n this.cache = s;\n return s;\n }\n\n save(s: SessionState): void {\n this.cache = s;\n try {\n this.env.setSession(KEY, JSON.stringify(s));\n } catch {\n // In-memory copy still drives this page.\n }\n }\n}\n\nexport function emptyStats(now: number, entryUrl: string): ReplayKitRecordingStats {\n return { startedAt: now, endedAt: now, activeMs: 0, clicks: 0, rageClicks: 0, deadClicks: 0, errors: 0, pages: 1, entryUrl };\n}\n","// Browser globals behind one interface, like ErrorKit's env.ts.\n//\n// Network, storage, timers and the clock go through an Env, so the transport, the\n// uploader and the client run in plain Node under node:test with fakes. DOM wiring\n// (listeners, rrweb) stays in signals-dom.ts / recorder.ts and is not unit-tested.\n\nexport interface FetchResult {\n status: number;\n headers: { get(name: string): string | null };\n json(): Promise<unknown>;\n}\n\nexport interface Env {\n now(): number;\n uuid(): string;\n fetch?: (url: string, init: RequestInit) => Promise<FetchResult>;\n sendBeacon?: (url: string, body: string) => boolean;\n getLocal(key: string): string | null;\n setLocal(key: string, value: string | null): void;\n getSession(key: string): string | null;\n setSession(key: string, value: string | null): void;\n getCookie(name: string): string | null;\n /** Async key/value store that survives a page load (IndexedDB). Missing = nothing carried across pages. */\n store?: KvStore;\n /** gzip; undefined when CompressionStream is unavailable (recording is then skipped). */\n gzip?: (text: string) => Promise<Blob>;\n setTimer(fn: () => void, ms: number): unknown;\n clearTimer(handle: unknown): void;\n}\n\nexport interface KvStore {\n get<T>(key: string): Promise<T | undefined>;\n set(key: string, value: unknown): Promise<void>;\n del(key: string): Promise<void>;\n}\n\nexport const isBrowser = typeof window !== \"undefined\" && typeof document !== \"undefined\";\n\nexport function uuidV4(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c && typeof c.randomUUID === \"function\") {\n try {\n return c.randomUUID();\n } catch {\n // randomUUID throws on insecure origins in some browsers; fall through.\n }\n }\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (ch) => {\n const r = (Math.random() * 16) | 0;\n return (ch === \"x\" ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\n// Storage throws in Safari private mode, sandboxed iframes and under storage policies.\nfunction safeGet(storage: () => Storage, key: string): string | null {\n try {\n return storage().getItem(key);\n } catch {\n return null;\n }\n}\n\nfunction safeSet(storage: () => Storage, key: string, value: string | null): void {\n try {\n if (value === null) storage().removeItem(key);\n else storage().setItem(key, value);\n } catch {\n // Unavailable or full: in-memory state still works for this page.\n }\n}\n\n/** One IndexedDB object store used as a key/value map. Every failure degrades to \"nothing stored\". */\nfunction indexedDbStore(): KvStore | undefined {\n if (typeof indexedDB === \"undefined\") return undefined;\n let dbp: Promise<IDBDatabase> | null = null;\n const open = () =>\n (dbp ??= new Promise<IDBDatabase>((resolve, reject) => {\n const req = indexedDB.open(\"himetrica-replaykit\", 1);\n req.onupgradeneeded = () => req.result.createObjectStore(\"kv\");\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n }));\n const run = <T>(mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest | void): Promise<T | undefined> =>\n open()\n .then(\n (db) =>\n new Promise<T | undefined>((resolve) => {\n const tx = db.transaction(\"kv\", mode);\n const req = fn(tx.objectStore(\"kv\"));\n tx.oncomplete = () => resolve(req ? (req.result as T) : undefined);\n tx.onerror = tx.onabort = () => resolve(undefined);\n }),\n )\n .catch(() => undefined);\n return {\n get: <T>(key: string) => run<T>(\"readonly\", (s) => s.get(key)),\n set: (key, value) => run<void>(\"readwrite\", (s) => void s.put(value, key)).then(() => undefined),\n del: (key) => run<void>(\"readwrite\", (s) => void s.delete(key)).then(() => undefined),\n };\n}\n\nfunction gzipFn(): Env[\"gzip\"] {\n if (typeof CompressionStream === \"undefined\" || typeof Blob === \"undefined\" || typeof Response === \"undefined\") return undefined;\n return (text) => new Response(new Blob([text]).stream().pipeThrough(new CompressionStream(\"gzip\"))).blob();\n}\n\nexport function browserEnv(): Env {\n const originalFetch = typeof fetch === \"function\" ? fetch.bind(globalThis) : undefined;\n const nav = typeof navigator !== \"undefined\" ? navigator : undefined;\n return {\n now: () => Date.now(),\n uuid: () => uuidV4(),\n fetch: originalFetch as Env[\"fetch\"],\n sendBeacon:\n nav && typeof nav.sendBeacon === \"function\"\n ? (url, body) => {\n try {\n return nav.sendBeacon(url, new Blob([body], { type: \"text/plain\" }));\n } catch {\n return false;\n }\n }\n : undefined,\n getLocal: (key) => safeGet(() => localStorage, key),\n setLocal: (key, value) => safeSet(() => localStorage, key, value),\n getSession: (key) => safeGet(() => sessionStorage, key),\n setSession: (key, value) => safeSet(() => sessionStorage, key, value),\n getCookie: (name) => {\n try {\n const match = document.cookie.match(new RegExp(\"(?:^|; )\" + name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\") + \"=([^;]*)\"));\n return match ? decodeURIComponent(match[1]) : null;\n } catch {\n return null;\n }\n },\n store: indexedDbStore(),\n gzip: gzipFn(),\n setTimer: (fn, ms) => setTimeout(fn, ms),\n clearTimer: (h) => clearTimeout(h as ReturnType<typeof setTimeout>),\n };\n}\n","// Identity bridge with the analytics tracker, strictly READ-ONLY (same approach as\n// ErrorKit's browser/identity.ts).\n//\n// The tracker (tracker-js / tracker.js) stores the ids in:\n// visitor cookie hm_vid (cookieDomain mode) or localStorage hm_visitor_id\n// session cookie hm_sid (cookieDomain mode) or sessionStorage hm_session_id\n// We read those keys and never write them. window.himetrica.getSessionId() is NOT\n// called: in the tracker it refreshes the session timestamp.\n//\n// A recording or a signal is only worth something tied to the tracker's visitor and\n// session, so without the tracker on the page ReplayKit stays idle.\n\nimport type { Env } from \"./env\";\n\nexport interface Identity {\n visitorId?: string;\n sessionId?: string;\n}\n\nexport function readIdentity(env: Env): Identity {\n const visitorId = env.getCookie(\"hm_vid\") || env.getLocal(\"hm_visitor_id\") || undefined;\n const sessionId = env.getCookie(\"hm_sid\") || env.getSession(\"hm_session_id\") || undefined;\n return { visitorId, sessionId };\n}\n","// Pure helpers the recording decision is made of: path globs and the session sample.\n\n/**\n * Path glob, as the project config writes them: `*` matches any run of characters\n * (slashes included), everything else is literal. A pattern without `*` is a prefix\n * on a segment boundary: `/checkout` matches `/checkout` and `/checkout/step-2`, not\n * `/checkouts`. Matched against the pathname only, case-insensitive.\n */\nexport function matchPath(pattern: string, pathname: string): boolean {\n const p = pattern.trim().toLowerCase();\n if (!p) return false;\n const path = (pathname || \"/\").toLowerCase();\n if (!p.includes(\"*\")) {\n const base = p.endsWith(\"/\") && p.length > 1 ? p.slice(0, -1) : p;\n return path === base || path.startsWith(base.endsWith(\"/\") ? base : base + \"/\");\n }\n const re = new RegExp(\"^\" + p.split(\"*\").map(escapeRegExp).join(\".*\") + \"$\");\n return re.test(path);\n}\n\nexport function matchAny(patterns: readonly string[], pathname: string): boolean {\n for (const p of patterns) if (matchPath(p, pathname)) return true;\n return false;\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Deterministic [0, 1) from the session id (cyrb53). Every page of a session gets the\n * same draw, so a sampled session is recorded across all its pages, and the server\n * could recompute it.\n */\nexport function sampleDraw(sessionId: string): number {\n let h1 = 0xdeadbeef;\n let h2 = 0x41c6ce57;\n for (let i = 0; i < sessionId.length; i++) {\n const ch = sessionId.charCodeAt(i);\n h1 = Math.imul(h1 ^ ch, 2654435761);\n h2 = Math.imul(h2 ^ ch, 1597334677);\n }\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n const n = 4294967296 * (2097151 & h2) + (h1 >>> 0);\n return n / 9007199254740992;\n}\n\nexport function inSample(sessionId: string, rate: number): boolean {\n if (!(rate > 0)) return false;\n if (rate >= 1) return true;\n return sampleDraw(sessionId) < rate;\n}\n\n/** URL without query and hash: queries carry tokens and emails, never sent. */\nexport function stripUrl(href: string): string {\n const cut = href.search(/[?#]/);\n return cut === -1 ? href : href.slice(0, cut);\n}\n","// The pre-trigger ring buffer.\n//\n// rrweb can only replay from a full snapshot: a Meta event (type 4) followed by a\n// FullSnapshot (type 2). The recorder takes one every CHECKOUT_MS, so the buffer can\n// always be cut at the last checkout that is older than the window and still start\n// with a replayable page. The cut keeps BUFFER_WINDOW_MS..BUFFER_WINDOW_MS+CHECKOUT_MS\n// of history before the trigger.\n\nexport interface RrEvent {\n type: number;\n timestamp: number;\n data?: unknown;\n}\n\nexport const EVENT_FULL_SNAPSHOT = 2;\nexport const EVENT_META = 4;\nexport const EVENT_CUSTOM = 5;\n/** rrweb custom event the SDK adds on SPA URL changes (rrweb only emits Meta on page loads/checkouts). */\nexport const PAGE_TAG = \"replaykit:page\";\n\n/**\n * Pages shown in a run of events, in order: Meta hrefs (page loads, and every\n * checkout repeats the current one) plus PAGE_TAG custom events. Query/fragment\n * stripped, back-to-back repeats folded, `prev` = last page already reported for\n * this recording (so a checkout's repeated Meta is not a new page). Capped at `max`.\n */\nexport function pagesOf(events: RrEvent[], prev: string, max: number): Array<{ url: string; ts: number }> {\n const out: Array<{ url: string; ts: number }> = [];\n let last = prev;\n for (const e of events) {\n let href: unknown;\n if (e.type === EVENT_META) href = (e.data as { href?: unknown } | undefined)?.href;\n else if (e.type === EVENT_CUSTOM) {\n const d = e.data as { tag?: unknown; payload?: { href?: unknown } } | undefined;\n if (d?.tag === PAGE_TAG) href = d.payload?.href;\n }\n if (typeof href !== \"string\" || !href) continue;\n const cut = href.search(/[?#]/);\n const url = (cut === -1 ? href : href.slice(0, cut)).slice(0, 500);\n if (url === last) continue;\n last = url;\n out.push({ url, ts: e.timestamp });\n if (out.length >= max) break;\n }\n return out;\n}\n\nexport const BUFFER_WINDOW_MS = 30_000;\nexport const CHECKOUT_MS = 30_000;\n\n/** Index of the Meta event that opens the snapshot the event list may start from. */\nfunction snapshotStart(events: RrEvent[], i: number): number {\n // rrweb emits Meta right before FullSnapshot; keep the Meta so the player knows the viewport.\n return i > 0 && events[i - 1].type === EVENT_META ? i - 1 : i;\n}\n\n/**\n * Drops everything before the most recent full snapshot whose timestamp is at or\n * before `now - windowMs`. If no snapshot is that old, nothing is dropped (the buffer\n * is still shorter than the window). A list that does not start with a snapshot (the\n * head was lost) is cut at its first snapshot, since nothing before it can replay.\n */\nexport function trimBuffer(events: RrEvent[], now: number, windowMs = BUFFER_WINDOW_MS): RrEvent[] {\n const cutoff = now - windowMs;\n let keepFrom = -1;\n let firstSnapshot = -1;\n for (let i = 0; i < events.length; i++) {\n if (events[i].type !== EVENT_FULL_SNAPSHOT) continue;\n if (firstSnapshot === -1) firstSnapshot = i;\n if (events[i].timestamp <= cutoff) keepFrom = i;\n else break;\n }\n if (keepFrom === -1) keepFrom = firstSnapshot;\n if (keepFrom === -1) return [];\n const start = snapshotStart(events, keepFrom);\n return start === 0 ? events : events.slice(start);\n}\n\n/** Rough serialized size, to cut chunks without stringifying on every event. */\nexport function approxBytes(e: RrEvent): number {\n // Mutations and snapshots dominate; JSON.stringify per event is acceptable: events\n // are stringified once here and the chunk is re-stringified once at flush.\n try {\n return JSON.stringify(e).length;\n } catch {\n return 0;\n }\n}\n","// Friction detectors, DOM-free so node:test can drive them with plain numbers.\n// signals-dom.ts feeds them real clicks and reports what they decide.\n\nexport interface ClickPoint {\n x: number;\n y: number;\n ts: number;\n /** Stable key of the clicked element (its selector), so a burst on one button counts even if the mouse drifts. */\n target: string;\n}\n\n/** 3+ clicks within RAGE_WINDOW_MS, on the same element or within RAGE_RADIUS_PX of the first. */\nexport const RAGE_MIN_CLICKS = 3;\nexport const RAGE_WINDOW_MS = 1000;\nexport const RAGE_RADIUS_PX = 30;\n\nexport interface RageBurst {\n first: ClickPoint;\n count: number;\n lastTs: number;\n}\n\n/**\n * Feeds clicks in order. `onClick` returns \"trigger\" on the click that turns a burst\n * into a rage click (the 3rd), so recording starts right away; the finished burst\n * (with its final count) comes out of `onClick` of the next unrelated click or of\n * `flush(now)` once the window has passed.\n */\nexport class RageDetector {\n private burst: RageBurst | null = null;\n\n onClick(c: ClickPoint): { trigger: boolean; finished: RageBurst | null } {\n const b = this.burst;\n if (b && c.ts - b.lastTs <= RAGE_WINDOW_MS && near(b.first, c)) {\n b.count++;\n b.lastTs = c.ts;\n return { trigger: b.count === RAGE_MIN_CLICKS, finished: null };\n }\n const finished = b && b.count >= RAGE_MIN_CLICKS ? b : null;\n this.burst = { first: c, count: 1, lastTs: c.ts };\n return { trigger: false, finished };\n }\n\n /** The burst that ended (quiet for the window) before `now`, if it was a rage click. */\n flush(now: number): RageBurst | null {\n const b = this.burst;\n if (!b || now - b.lastTs <= RAGE_WINDOW_MS) return null;\n this.burst = null;\n return b.count >= RAGE_MIN_CLICKS ? b : null;\n }\n\n /** Clicks of the current burst so far (a rage burst is not also a dead click). */\n currentCount(): number {\n return this.burst?.count ?? 0;\n }\n}\n\nfunction near(a: ClickPoint, b: ClickPoint): boolean {\n if (a.target && a.target === b.target) return true;\n return Math.abs(a.x - b.x) <= RAGE_RADIUS_PX && Math.abs(a.y - b.y) <= RAGE_RADIUS_PX;\n}\n\n/** How long after a click something must happen for the click not to be \"dead\". */\nexport const DEAD_CLICK_WAIT_MS = 500;\n\nexport interface ClickTargetFacts {\n /** Lowercase tag name of the clicked element. */\n tag: string;\n /** The element or an ancestor is a link/button/[role=button…]/[onclick]/summary. */\n insideInteractive: boolean;\n /** Text fields, selects, labels, contenteditable: a click there focuses, nothing else to expect. */\n isFormField: boolean;\n /** Computed cursor is \"pointer\": the page tells the user it is clickable. */\n pointerCursor: boolean;\n /** Text is selected after the click (the user was selecting, not clicking). */\n hasSelection: boolean;\n}\n\n/**\n * A click can only be dead when the element promised something: it is (inside) an\n * interactive element or shows a pointer cursor. A click on plain text or on a\n * background is not friction, whatever happens after it.\n */\nexport function isDeadClickCandidate(f: ClickTargetFacts): boolean {\n if (f.isFormField || f.hasSelection) return false;\n if (f.tag === \"html\" || f.tag === \"body\") return false;\n return f.insideInteractive || f.pointerCursor;\n}\n\nexport interface AfterClickReaction {\n /** DOM mutations observed in the wait window. */\n mutations: number;\n urlChanged: boolean;\n scrolled: boolean;\n focusChanged: boolean;\n /** The page is unloading (a navigation or a download started). */\n unloading: boolean;\n}\n\n/** Nothing reacted within DEAD_CLICK_WAIT_MS: the click was dead. */\nexport function isDeadClick(r: AfterClickReaction): boolean {\n return r.mutations === 0 && !r.urlChanged && !r.scrolled && !r.focusChanged && !r.unloading;\n}\n\n/** Active time: input gaps up to ACTIVE_GAP_MS count, longer gaps are idle. */\nexport const ACTIVE_GAP_MS = 5000;\n\nexport function activeIncrement(lastInputTs: number, ts: number): number {\n if (!lastInputTs) return 0;\n const gap = ts - lastInputTs;\n return gap > 0 && gap <= ACTIVE_GAP_MS ? gap : 0;\n}\n","// What this page does about recording, from what /init said and the session state.\n// Pure, so the whole decision table is unit-tested.\n\nimport type { ReplayKitTrigger } from \"./protocol\";\nimport type { SessionState } from \"./state\";\n\nexport type PageMode =\n /** Nothing is recorded on this page (signals may still flow). */\n | { kind: \"off\" }\n /** requireConsent and the banner has not said yes yet. */\n | { kind: \"wait_consent\" }\n /** A recording of this session is already running: continue it. */\n | { kind: \"continue\" }\n /** Start a recording now, for this reason. */\n | { kind: \"start\"; trigger: ReplayKitTrigger }\n /** Keep the pre-trigger buffer and wait for a trigger. */\n | { kind: \"buffer\" };\n\nexport interface DecideInput {\n /** /init answered record: true. */\n record: boolean;\n /** CompressionStream exists (chunks are gzip'd in the browser). */\n canGzip: boolean;\n state: SessionState;\n /** Path is in excludePaths. */\n excluded: boolean;\n requireConsent: boolean;\n /** Consent stored by ReplayKit.consent(): true, false, or never given. */\n consent: boolean | null;\n forceTrigger: ReplayKitTrigger | null;\n sampled: boolean;\n /** Path matched checkoutPaths and \"checkout\" is an enabled trigger. */\n checkout: boolean;\n}\n\n/** Triggers that open a recording however short the visit is (same list as the API's). */\nexport const MIN_DURATION_EXEMPT: readonly ReplayKitTrigger[] = [\"error\", \"rage_click\", \"manual\"];\n\n/**\n * How long trigger `t` still has to wait before it may open a recording, given how long the\n * session has been on screen. 0 = open it now. A bounce never reaches the minimum, so it never\n * opens a recording nor costs quota; an error or a rage click does not wait.\n */\nexport function waitBeforeRecording(t: ReplayKitTrigger, visibleMs: number, minDurationMs: number): number {\n if (minDurationMs <= 0 || MIN_DURATION_EXEMPT.includes(t)) return 0;\n return Math.max(0, minDurationMs - visibleMs);\n}\n\nexport function decidePage(i: DecideInput): PageMode {\n // An explicit ReplayKit.consent(false) wins even when the project does not require consent.\n if (!i.record || !i.canGzip || i.state.stopped || i.excluded || i.consent === false) return { kind: \"off\" };\n if (i.requireConsent && i.consent !== true) return { kind: \"wait_consent\" };\n if (i.state.rid) return { kind: \"continue\" };\n if (i.forceTrigger) return { kind: \"start\", trigger: i.forceTrigger };\n if (i.checkout) return { kind: \"start\", trigger: \"checkout\" };\n if (i.sampled) return { kind: \"start\", trigger: \"sample\" };\n return { kind: \"buffer\" };\n}\n","// Calls to the ingest (POST {apiUrl}/api/t/r/<op>?apiKey=...), text/plain JSON so\n// they are \"simple\" CORS requests with no preflight, plus the PUT of a chunk to R2.\n//\n// Every response is reduced to an outcome the client acts on (see the contract in\n// packages/shared/src/replaykit.ts):\n// ok 2xx\n// drop 400/413: this body is unusable, forget it\n// stop 401: bad key / origin not allowed, ReplayKit stops for this page\n// off 403: rollout, plan or this op is off for the project\n// quota 429: no more recordings this session (signals continue)\n// retry 5xx, network error, or no fetch at all\n\nimport type { Env } from \"./env\";\nimport type {\n ReplayKitChunkRequest,\n ReplayKitChunkResponse,\n ReplayKitInitRequest,\n ReplayKitInitResponse,\n ReplayKitSignalsRequest,\n} from \"./protocol\";\n\nexport type Outcome = \"ok\" | \"drop\" | \"stop\" | \"off\" | \"quota\" | \"retry\";\n\nexport function outcomeOf(status: number): Outcome {\n if (status >= 200 && status < 300) return \"ok\";\n if (status === 401) return \"stop\";\n if (status === 403) return \"off\";\n if (status === 429) return \"quota\";\n if (status === 400 || status === 413 || status === 404 || status === 422) return \"drop\";\n return \"retry\";\n}\n\nexport interface Result<T> {\n outcome: Outcome;\n data?: T;\n}\n\nexport class Api {\n constructor(\n private readonly env: Env,\n private readonly apiUrl: string,\n private readonly apiKey: string,\n ) {}\n\n url(op: \"init\" | \"chunk\" | \"signals\"): string {\n return `${this.apiUrl}/api/t/r/${op}?apiKey=${encodeURIComponent(this.apiKey)}`;\n }\n\n init(body: ReplayKitInitRequest): Promise<Result<ReplayKitInitResponse>> {\n return this.post<ReplayKitInitResponse>(\"init\", body, true);\n }\n\n chunk(body: ReplayKitChunkRequest): Promise<Result<ReplayKitChunkResponse>> {\n return this.post<ReplayKitChunkResponse>(\"chunk\", body, true);\n }\n\n signals(body: ReplayKitSignalsRequest): Promise<Result<void>> {\n return this.post<void>(\"signals\", body, false);\n }\n\n /** On page hide: fire-and-forget. False when the beacon could not be queued. */\n beaconSignals(body: ReplayKitSignalsRequest): boolean {\n return !!this.env.sendBeacon?.(this.url(\"signals\"), JSON.stringify(body));\n }\n\n /** PUT the gzip'd chunk to the presigned R2 URL. R2 answers 200; 403 = URL expired or bad signature. */\n async put(url: string, blob: Blob): Promise<Outcome> {\n if (!this.env.fetch) return \"retry\";\n try {\n const res = await this.env.fetch(url, { method: \"PUT\", body: blob, headers: { \"Content-Type\": \"application/gzip\" } });\n if (res.status >= 200 && res.status < 300) return \"ok\";\n // An expired/rejected signature is fixed by asking for a new URL, not by dropping the chunk.\n return res.status === 400 || res.status === 413 ? \"drop\" : \"retry\";\n } catch {\n return \"retry\";\n }\n }\n\n private async post<T>(op: \"init\" | \"chunk\" | \"signals\", body: unknown, wantJson: boolean): Promise<Result<T>> {\n if (!this.env.fetch) return { outcome: \"retry\" };\n try {\n const res = await this.env.fetch(this.url(op), {\n method: \"POST\",\n body: JSON.stringify(body),\n headers: { \"Content-Type\": \"text/plain\" },\n keepalive: false,\n credentials: \"omit\",\n });\n const outcome = outcomeOf(res.status);\n if (outcome !== \"ok\" || !wantJson) return { outcome };\n try {\n return { outcome, data: (await res.json()) as T };\n } catch {\n return { outcome: \"retry\" };\n }\n } catch {\n return { outcome: \"retry\" };\n }\n }\n}\n\nexport const BASE_BACKOFF_MS = 2_000;\nexport const MAX_BACKOFF_MS = 60_000;\n\nexport function backoff(failures: number): number {\n return Math.min(MAX_BACKOFF_MS, BASE_BACKOFF_MS * 2 ** Math.max(0, failures - 1));\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
type ReplayKitTrigger = "error" | "rage_click" | "checkout" | "paying" | "sample" | "manual";
|
|
2
|
+
type ReplayKitSignalType = "rage_click" | "dead_click" | "error" | "back_nav" | "form_abandon";
|
|
3
|
+
interface ReplayKitSignal {
|
|
4
|
+
type: ReplayKitSignalType;
|
|
5
|
+
ts: number;
|
|
6
|
+
url: string;
|
|
7
|
+
selector?: string;
|
|
8
|
+
text?: string;
|
|
9
|
+
count?: number;
|
|
10
|
+
detail?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface ReplayKitOptions {
|
|
14
|
+
/** Your project's public API key (the same one the tracker uses). */
|
|
15
|
+
apiKey: string;
|
|
16
|
+
/** Defaults to https://app.himetrica.com. */
|
|
17
|
+
apiUrl?: string;
|
|
18
|
+
/** Run on localhost (off by default, like the tracker). */
|
|
19
|
+
allowLocalhost?: boolean;
|
|
20
|
+
/** Log decisions to the console. */
|
|
21
|
+
debug?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Starts ReplayKit. A second call is ignored. */
|
|
25
|
+
declare function init(options: ReplayKitOptions): void;
|
|
26
|
+
/** Record this session from now on (and keep the pre-trigger buffer). */
|
|
27
|
+
declare function start(): void;
|
|
28
|
+
/**
|
|
29
|
+
* Mark this moment as worth a recording, like an error would. `reason` is for your
|
|
30
|
+
* own debugging (logged with `debug: true`); the recording is tagged "manual".
|
|
31
|
+
*/
|
|
32
|
+
declare function trigger(reason?: string): void;
|
|
33
|
+
/** Stop recording for the rest of the session. What was captured is still uploaded. */
|
|
34
|
+
declare function stop(): void;
|
|
35
|
+
/**
|
|
36
|
+
* The visitor's answer to your consent banner. With "require consent" on in the
|
|
37
|
+
* project, nothing is recorded until consent(true). consent(false) stops and drops
|
|
38
|
+
* what was not uploaded yet. Remembered on this device.
|
|
39
|
+
*/
|
|
40
|
+
declare function consent(granted: boolean): void;
|
|
41
|
+
/** Id of the recording running on this page, if any. */
|
|
42
|
+
declare function getRecordingId(): string | null;
|
|
43
|
+
/** Stops everything and removes the listeners (tests, SPA teardown). */
|
|
44
|
+
declare function shutdown(): void;
|
|
45
|
+
|
|
46
|
+
export { type ReplayKitOptions, type ReplayKitSignal, type ReplayKitSignalType, type ReplayKitTrigger, consent, getRecordingId, init, shutdown, start, stop, trigger };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
type ReplayKitTrigger = "error" | "rage_click" | "checkout" | "paying" | "sample" | "manual";
|
|
2
|
+
type ReplayKitSignalType = "rage_click" | "dead_click" | "error" | "back_nav" | "form_abandon";
|
|
3
|
+
interface ReplayKitSignal {
|
|
4
|
+
type: ReplayKitSignalType;
|
|
5
|
+
ts: number;
|
|
6
|
+
url: string;
|
|
7
|
+
selector?: string;
|
|
8
|
+
text?: string;
|
|
9
|
+
count?: number;
|
|
10
|
+
detail?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface ReplayKitOptions {
|
|
14
|
+
/** Your project's public API key (the same one the tracker uses). */
|
|
15
|
+
apiKey: string;
|
|
16
|
+
/** Defaults to https://app.himetrica.com. */
|
|
17
|
+
apiUrl?: string;
|
|
18
|
+
/** Run on localhost (off by default, like the tracker). */
|
|
19
|
+
allowLocalhost?: boolean;
|
|
20
|
+
/** Log decisions to the console. */
|
|
21
|
+
debug?: boolean;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Starts ReplayKit. A second call is ignored. */
|
|
25
|
+
declare function init(options: ReplayKitOptions): void;
|
|
26
|
+
/** Record this session from now on (and keep the pre-trigger buffer). */
|
|
27
|
+
declare function start(): void;
|
|
28
|
+
/**
|
|
29
|
+
* Mark this moment as worth a recording, like an error would. `reason` is for your
|
|
30
|
+
* own debugging (logged with `debug: true`); the recording is tagged "manual".
|
|
31
|
+
*/
|
|
32
|
+
declare function trigger(reason?: string): void;
|
|
33
|
+
/** Stop recording for the rest of the session. What was captured is still uploaded. */
|
|
34
|
+
declare function stop(): void;
|
|
35
|
+
/**
|
|
36
|
+
* The visitor's answer to your consent banner. With "require consent" on in the
|
|
37
|
+
* project, nothing is recorded until consent(true). consent(false) stops and drops
|
|
38
|
+
* what was not uploaded yet. Remembered on this device.
|
|
39
|
+
*/
|
|
40
|
+
declare function consent(granted: boolean): void;
|
|
41
|
+
/** Id of the recording running on this page, if any. */
|
|
42
|
+
declare function getRecordingId(): string | null;
|
|
43
|
+
/** Stops everything and removes the listeners (tests, SPA teardown). */
|
|
44
|
+
declare function shutdown(): void;
|
|
45
|
+
|
|
46
|
+
export { type ReplayKitOptions, type ReplayKitSignal, type ReplayKitSignalType, type ReplayKitTrigger, consent, getRecordingId, init, shutdown, start, stop, trigger };
|