@clicklore/browser 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +176 -2
- package/dist/clicklore.js +1 -0
- package/dist/index.d.ts +103 -0
- package/dist/index.js +2194 -0
- package/package.json +52 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Pawel Lisowski
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,177 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @clicklore/browser
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Framework-agnostic browser SDK for Clicklore. It records which features people click and which
|
|
4
|
+
they ignore, who they are, and where they struggle: rage and dead clicks, errors after clicks,
|
|
5
|
+
failed requests, slow responses and field errors. No runtime dependencies; the script-tag build
|
|
6
|
+
stays under 12 KB gzip.
|
|
7
|
+
|
|
8
|
+
For React and Next.js, Vue or Angular, use `@clicklore/react`, `@clicklore/vue` or
|
|
9
|
+
`@clicklore/angular`: they call this SDK and report router templates as page routes.
|
|
10
|
+
|
|
11
|
+
## Install
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm install @clicklore/browser
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { init } from '@clicklore/browser';
|
|
19
|
+
|
|
20
|
+
init({
|
|
21
|
+
projectKey: 'cl_…', // Copy the public key from your Clicklore project.
|
|
22
|
+
host: 'https://ingest.example.com', // The URL of your Clicklore deployment.
|
|
23
|
+
});
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`init()` is a no-op during server rendering. An invalid project key or host configuration logs
|
|
27
|
+
an error and leaves capture inactive. Once initialised, later calls are ignored. Calls made
|
|
28
|
+
before the first `init()` (for example `identify()` in a component that renders first) are queued
|
|
29
|
+
and replayed when capture initialises successfully.
|
|
30
|
+
|
|
31
|
+
### Script tag
|
|
32
|
+
|
|
33
|
+
```html
|
|
34
|
+
<script src="https://ingest.example.com/sdk/clicklore.js" data-key="cl_…" defer></script>
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Use a classic script tag. It initializes itself and exposes the API as `window.clicklore`. Set
|
|
38
|
+
`data-host` if the ingest URL differs from the script origin, including when ingest runs under a
|
|
39
|
+
reverse proxy path. Boolean attributes are enabled by their presence. The options are
|
|
40
|
+
`data-mask-all-text`, `data-capture-input-values`, `data-require-consent` and `data-debug`.
|
|
41
|
+
|
|
42
|
+
To use methods before the deferred script loads, put this stub before the SDK tag and before
|
|
43
|
+
your application code. The SDK initializes from the tag, then replays the queue in order.
|
|
44
|
+
|
|
45
|
+
```html
|
|
46
|
+
<script>
|
|
47
|
+
{
|
|
48
|
+
const q = [];
|
|
49
|
+
window.clicklore = { q };
|
|
50
|
+
for (const name of ['track', 'identify', 'group', 'reset', 'setRoute', 'optIn', 'optOut']) {
|
|
51
|
+
window.clicklore[name] = (...args) => q.push(sdk => sdk[name](...args));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
</script>
|
|
55
|
+
<script src="https://ingest.example.com/sdk/clicklore.js" data-key="cl_…" data-require-consent defer></script>
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
For function options such as `sanitizeUrl`, omit `data-key` and call `window.clicklore.init(config)`
|
|
59
|
+
after the script has loaded, for example in a `DOMContentLoaded` listener registered before the
|
|
60
|
+
deferred tag runs.
|
|
61
|
+
|
|
62
|
+
Load the SDK once per page. A second copy (two tags, or a tag plus the npm package) logs a
|
|
63
|
+
warning and stays inactive, so nothing is counted twice.
|
|
64
|
+
|
|
65
|
+
### Self-hosting and CSP
|
|
66
|
+
|
|
67
|
+
Set `host` to the browser-accessible base URL of your deployment. The SDK sends to
|
|
68
|
+
`{host}/v1/b`. If your project uses an origin allowlist, include the origin of the app doing
|
|
69
|
+
the capturing. Your app's CSP must permit the ingest origin in `connect-src` for fetch and
|
|
70
|
+
beacons. Use `'self'` for same-origin ingest. For a script tag, also allow the script origin in
|
|
71
|
+
`script-src` or authorize the tag with your CSP's nonce. Give the inline stub a nonce or hash if
|
|
72
|
+
your policy restricts inline scripts. Bundled SDK installs follow the policy for your app's
|
|
73
|
+
JavaScript.
|
|
74
|
+
|
|
75
|
+
## Configuration
|
|
76
|
+
|
|
77
|
+
| Option | Default | |
|
|
78
|
+
|---|---|---|
|
|
79
|
+
| `projectKey` | (required) | Public project key, `cl_…`. |
|
|
80
|
+
| `host` | (required) | Ingest host. The script tag defaults to its own origin. |
|
|
81
|
+
| `capture` | all on | `{ pages, clicks, impressions, forms, errors, network, slowInteractions, copy }`; set any to `false`. |
|
|
82
|
+
| `captureInputValues` | `false` | Record committed field values (change/blur, Enter in search boxes). |
|
|
83
|
+
| `maskAllText` | `false` | Never capture element text; labels stay empty. |
|
|
84
|
+
| `requireConsent` | `false` | Capture and store nothing until `optIn()`. |
|
|
85
|
+
| `respectDoNotTrack` | `false` | Capture nothing when the browser sends Do Not Track or Global Privacy Control. |
|
|
86
|
+
| `trackAttribute` | `data-track` | Attribute holding explicit element names. |
|
|
87
|
+
| `route` | heuristic | `(pathname) => template \| undefined`, e.g. `/projects/:id`. |
|
|
88
|
+
| `sanitizeUrl` | heuristic | `(pathname) => sanitizedPath \| undefined`. Sets the recorded page path and the fallback route. Returning `undefined` uses the built-in redaction. |
|
|
89
|
+
| `slowInteractionMs` | `500` | Minimum duration of a slow interaction. |
|
|
90
|
+
| `flushIntervalMs` | `5000` | How often batches are sent. |
|
|
91
|
+
| `flushAt` | `50` | Queue size that triggers an immediate send. |
|
|
92
|
+
| `sessionTimeoutMs` | 30 minutes | Inactivity that starts a new session. |
|
|
93
|
+
| `storagePrefix` | `cl` | Prefix of the `localStorage` keys. |
|
|
94
|
+
| `debug` | `false` | Log captured events and warn when a batch is dropped after an HTTP 4xx response. |
|
|
95
|
+
|
|
96
|
+
## Naming elements
|
|
97
|
+
|
|
98
|
+
Elements are identified, in order, by:
|
|
99
|
+
|
|
100
|
+
1. `data-track="export-csv"`: an explicit name you choose.
|
|
101
|
+
2. `data-cl`: component and source location, added at build time by `@clicklore/annotate`.
|
|
102
|
+
3. A fallback from the route, element kind, accessible label and a stable selector (ids, `name`,
|
|
103
|
+
`data-testid`; never hashed class names).
|
|
104
|
+
|
|
105
|
+
Use these attributes to control capture:
|
|
106
|
+
|
|
107
|
+
- `data-cl-mask`: suppress element labels and field values on the element and its descendants.
|
|
108
|
+
- `data-cl-ignore`: skip element interactions on the element and its descendants.
|
|
109
|
+
- `data-cl-capture`: capture this field's value even without `captureInputValues`.
|
|
110
|
+
|
|
111
|
+
`data-cl-mask` and `data-cl-ignore` also apply across shadow roots.
|
|
112
|
+
|
|
113
|
+
## Privacy defaults
|
|
114
|
+
|
|
115
|
+
- Capture includes page views and exits, time and scroll depth, quick backs, interactive element
|
|
116
|
+
impressions and clicks, rage and dead clicks, form interactions and validation, and copy
|
|
117
|
+
events attributed to elements. Clipboard contents are excluded. Capture also includes uncaught
|
|
118
|
+
errors, failures attributed to clicks (error messages or request method, templated path and
|
|
119
|
+
status), and slow interactions when the browser supports Event Timing.
|
|
120
|
+
- Sessions carry an anonymous id, an external referrer (host and templated path), UTM values,
|
|
121
|
+
screen size, language and timezone. Calls to `identify()`, `group()` or `track()` add data
|
|
122
|
+
supplied by your app.
|
|
123
|
+
- Field values are not captured unless you opt in (`captureInputValues`, or `data-cl-capture`
|
|
124
|
+
per field). Even then, passwords, hidden and file inputs, payment (`cc-*`) and one-time-code
|
|
125
|
+
fields, and fields named or labelled like secrets are never captured.
|
|
126
|
+
- Typed text is never used as a label, including in `contenteditable` editors.
|
|
127
|
+
- Clickable containers use an accessible label, a `title` or a short text-only caption.
|
|
128
|
+
- Page paths redact ID-like segments, JWTs and emails. Use `sanitizeUrl` to cover
|
|
129
|
+
application-specific patterns. The callback receives the pathname alone and controls the
|
|
130
|
+
recorded page path and fallback route. Review explicit route templates, UTM values, titles,
|
|
131
|
+
error messages and developer-supplied properties separately.
|
|
132
|
+
- Labels, titles, error messages and captured values are redacted (emails, long numbers, UUIDs,
|
|
133
|
+
tokens) and truncated. Custom event props are redacted for emails and long numbers. User traits
|
|
134
|
+
are sent as given.
|
|
135
|
+
- Clicklore stores no IP addresses in analytics rows.
|
|
136
|
+
- Set `requireConsent: true` (or `data-require-consent` on the script) and call `optIn()` from
|
|
137
|
+
your consent UI after the visitor accepts. The SDK sends no capture and writes nothing to
|
|
138
|
+
`localStorage` while it waits for consent. Consent is remembered across reloads.
|
|
139
|
+
- `optOut()` stops capture, drops queued and unsent data, and removes the stored ids. The choice
|
|
140
|
+
is remembered.
|
|
141
|
+
|
|
142
|
+
The SDK stores these `localStorage` keys (with the default prefix): `cl_a` anonymous id, `cl_u`
|
|
143
|
+
user id, `cl_g` groups, `cl_s` session, `cl_q_<projectKey>` batches waiting for a retry, and
|
|
144
|
+
`cl_c` consent choice. Old shared `cl_q` batches are discarded when capture starts. It sets no
|
|
145
|
+
cookies.
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { init, optIn, optOut } from '@clicklore/browser';
|
|
149
|
+
|
|
150
|
+
init({
|
|
151
|
+
projectKey: 'cl_…',
|
|
152
|
+
host: 'https://ingest.example.com',
|
|
153
|
+
requireConsent: true,
|
|
154
|
+
sanitizeUrl: (path) => (path.startsWith('/invite/') ? '/invite/:code' : undefined),
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
document.querySelector('#analytics-accept')?.addEventListener('click', optIn);
|
|
158
|
+
document.querySelector('#analytics-decline')?.addEventListener('click', optOut);
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## API
|
|
162
|
+
|
|
163
|
+
| Function | |
|
|
164
|
+
|---|---|
|
|
165
|
+
| `init(config)` | Start capturing. |
|
|
166
|
+
| `identify(userId, traits?)` | Associate this visitor with your user id; traits show on their profile. |
|
|
167
|
+
| `group(type, id)` | Associate this visitor with a group, e.g. `group('org', 'acme')`. |
|
|
168
|
+
| `reset()` | Forget the user (call on logout): new anonymous id and session. |
|
|
169
|
+
| `track(name, props?)` | Record a custom event. Names are trimmed and truncated. Props are strings, numbers, booleans, `null` or dates. |
|
|
170
|
+
| `setRoute(template)` | Report the route template of the current URL, e.g. `/projects/[id]`. |
|
|
171
|
+
| `optIn()` / `optOut()` | Record the visitor's consent choice. |
|
|
172
|
+
| `flush()` | Send queued events now. |
|
|
173
|
+
| `shutdown()` | Stop capturing; removes all listeners and patches. |
|
|
174
|
+
| `getAnonymousId()` | The anonymous visitor id; `null` before `init()`. |
|
|
175
|
+
| `getSessionId()` | The current session id; `null` until capture starts. Never starts a session. |
|
|
176
|
+
|
|
177
|
+
The same functions are available as one object, `clicklore` (type `ClickloreApi`).
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var clicklore=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});let t=`data-cl`,n=/^[0-9a-z]{1,16}$/;function r(e){if(!e)return null;let t=e.charCodeAt(0)===42,r=t?e.slice(1):e,i,a=r.lastIndexOf(` #`);a>0&&n.test(r.slice(a+2))&&(i=r.slice(a+2),r=r.slice(0,a));let o=r.indexOf(` `);return o<=0||o===r.length-1?null:{interactive:t,component:r.slice(0,o),source:r.slice(o+1),signature:i}}function i(e){return e.track?`t|${e.track}`:e.source&&e.signature?`a|${e.source.replace(/:\d+$/,``)}|${e.component??``}|${e.signature}|${e.kind}`:e.source?`s|${e.source}|${e.kind}`:`f|${e.route}|${e.kind}|${e.label??``}|${e.selector??``}`}function a(e){return o(i(e)).toString(36)}function o(e,t=0){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}let s=`/v1/b`,c={O:524288,j:500,S:500,C:300,w:80,b:300,o:100,T:30,E:300,D:300,_:300,f:128,A:864e5};function l(e){return(...t)=>{try{return e(...t)}catch{return}}}function u(e,t,n){let r=e[t],i=n(r);return l(()=>e[t]=i)(),l(()=>{e[t]===i&&(e[t]=r)})}function d(e,t,n,r){let i={capture:!0,passive:!0,...r},a=l(n);return l(()=>e.addEventListener(t,a,i))(),l(()=>e.removeEventListener(t,a,i))}function f(e){let t=/* @__PURE__ */ new Set,n=null,r=[],i=l(()=>{for(let e of t)e.active=!0});function a(){n||(n=new MutationObserver(i),n.observe(e.documentElement,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),r=[d(e,`focusin`,i),d(e,`scroll`,i)],e.defaultView&&r.push(d(e.defaultView,`blur`,i,{capture:!1})))}function o(){if(n){n.disconnect(),n=null;for(let e of r.splice(0))e()}}return{signal:i,watch(e,n){let r={active:!1};t.add(r),a();let i=l(()=>{t.delete(r)&&(clearTimeout(s),t.size===0&&o(),n(r.active))}),s=setTimeout(i,e);return i},dispose(){t.clear(),o()}}}let p=`0.1.1`;function m(e){let t=typeof e?.projectKey==`string`&&e.projectKey.trim();if(!t)throw Error(`init() requires a projectKey`);if(typeof e.host!=`string`||!e.host.trim())throw Error(`init() requires a host`);let n=new URL(e.host,document.baseURI);if(!/^https?:$/.test(n.protocol)||n.search||n.hash||n.username||n.password)throw Error(`invalid ingest host`);return{projectKey:t,endpoint:`${n.origin}${n.pathname.replace(/\/+$/,``)}${s}?k=${encodeURIComponent(t)}`,capture:{pages:!0,clicks:!0,impressions:!0,forms:!0,errors:!0,network:!0,slowInteractions:!0,copy:!0,...e.capture},trackAttribute:e.trackAttribute??`data-track`,maskAllText:e.maskAllText??!1,captureInputValues:e.captureInputValues??!1,requireConsent:e.requireConsent??!1,respectDoNotTrack:e.respectDoNotTrack??!1,route:e.route,sanitizeUrl:e.sanitizeUrl,slowInteractionMs:e.slowInteractionMs??500,flushIntervalMs:e.flushIntervalMs??5e3,flushAt:e.flushAt??50,sessionTimeoutMs:e.sessionTimeoutMs??18e5,storagePrefix:e.storagePrefix??`cl`,debug:e.debug??!1}}function h(e){let t=new Uint8Array(e);if(typeof crypto<`u`&&crypto.getRandomValues)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.random()*256|0;return t}function g(e){let t=``;for(let n=0;n<e.length;n++)t+=e[n].toString(16).padStart(2,`0`);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function _(){let e=h(16);return e[6]=e[6]&15|64,e[8]=e[8]&63|128,g(e)}function ee(e=Date.now()){let t=h(16),n=e;for(let e=5;e>=0;e--)t[e]=n%256,n=Math.floor(n/256);return t[6]=t[6]&15|112,t[8]=t[8]&63|128,g(t)}function te(){let e=new DataView(h(8).buffer);return e.getUint32(0).toString(36)+e.getUint32(4).toString(36).padStart(7,`0`)}let ne=`[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`,re=RegExp(`^${ne}$`,`i`);function v(e){return typeof e==`string`&&re.test(e)}var ie=class{#e=[];#t=/* @__PURE__ */ new Map;#n=/* @__PURE__ */ new Set;#r;get size(){return this.#e.length}push(e,t){this.#e.push({event:e,page:t})}define(e){this.#n.has(e.id)||this.#t.set(e.id,e)}setTraits(e){this.#r=e&&{...this.#r,...e}}rewriteRoute(e,t){for(let n of this.#e)n.page===e&&(n.event.p=t)}clear(){this.#e=[],this.#t.clear(),this.#r=void 0}take(e){if(this.#e.length===0&&!this.#r)return null;let t=this.#e.splice(0,100).map(e=>e.event),n={v:1,i:te(),sdk:`web/${p}`,at:0,a:e.anonId,s:e.sessionId,e:t};if(e.userId&&(n.u=e.userId),e.groups&&Object.keys(e.groups).length>0&&(n.g=e.groups),this.#r&&=(n.ut=this.#r,void 0),this.#t.size>0){n.el=[...this.#t.values()].slice(0,c.S);for(let e of n.el)this.#n.add(e.id),this.#t.delete(e.id)}return n}};let ae=/^\d+$/,oe=/^[0-9a-f]{12,}$/i,se=/^(?=.*\d)(?=.*[a-z])[a-z0-9_-]{16,}$/i,ce=/^ey[\w-]{6,}(?:\.[\w-]*){2,4}$/,le=/[^/@]+@[^/@]+/,ue=/^[a-z]{2,6}[_-](?=.*\d)[a-z0-9]{4,}$/i;function de(e){return ae.test(e)||v(e)||oe.test(e)||se.test(e)||ue.test(e)||ce.test(e)||le.test(e)}function y(e){if(e===``||e===`/`)return`/`;let t=``;for(let n of e.split(`/`)){if(!n)continue;let e=n;try{e=decodeURIComponent(n)}catch{}t+=`/${de(e)?`:id`:e}`}return t||`/`}let fe=/\s+/g,b=/[^\s@<>()[\]"']+@[^\s@<>()[\]"']+\.[a-z]{2,}/gi,pe=RegExp(`\\b${ne}\\b`,`gi`),me=/\b(?=[A-Za-z0-9_-]*\d)(?=[A-Za-z0-9_-]*[A-Za-z])[A-Za-z0-9_-]{24,}\b/g,x=/\+?\d(?:[\d\s().-]{6,}\d)/g,he=/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/,ge=/^(?:19|20)\d\d\s+-\s+(?:19|20)\d\d$/;function S(e,t,n){let r=n[t-1]===`Q`&&/^[1-4] /.test(e)?e.slice(2):e;return he.test(e)||ge.test(r)?e:`[number]`}function _e(e){return e.replace(b,`[email]`).replace(pe,`[id]`).replace(me,`[token]`).replace(x,S)}function ve(e){return e.replace(b,`[email]`).replace(x,S)}function C(e,t){let n=e.length>t?e.slice(0,t):e,r=n.charCodeAt(n.length-1);return n.length<e.length&&r>=55296&&r<=56319&&(n=n.slice(0,-1)),typeof n.toWellFormed==`function`?n.toWellFormed():n}function w(e,t){if(!e)return``;let n=e.replace(fe,` `).trim();if(!n)return``;let r=_e(C(n,t*4));return r.length>t?`${C(r,t-1)}…`:r}let ye=`button,link,tab,menuitem,menuitemcheckbox,menuitemradio,checkbox,radio,switch,option,combobox,treeitem`.split(`,`);function be(e){return[`a[href]`,`button`,`input:not([type=hidden])`,`select`,`textarea`,`summary`,`[contenteditable=""]`,`[contenteditable=true]`,`[${e}]`,`[${t}^="*"]`,...ye.map(e=>`[role=${e}]`)].join(`,`)}let xe={button:`button`,link:`link`,tab:`tab`,menuitem:`menuitem`,menuitemcheckbox:`menuitem`,menuitemradio:`menuitem`,checkbox:`checkbox`,radio:`radio`,switch:`switch`,option:`option`,combobox:`select`},Se={checkbox:`checkbox`,radio:`radio`,button:`button`,submit:`button`,reset:`button`,image:`button`},T=/* @__PURE__ */ new WeakSet;function E(e){let t=e.getAttribute(`role`);if(t&&xe[t])return xe[t];if(T.has(e))return`button`;switch(e.localName){case`a`:return`link`;case`button`:case`summary`:return`button`;case`select`:return`select`;case`textarea`:return`textarea`;case`form`:return`form`;case`input`:return Se[e.type]??`input`;default:return`other`}}let Ce=/* @__PURE__ */ new Set([`button`,`link`,`tab`,`menuitem`,`option`,`checkbox`,`radio`,`switch`]);function D(e){return e?.textContent??``}function O(e){let t=e.getAttribute(`aria-labelledby`);if(!t)return``;let n=e.ownerDocument;return t.split(/\s+/).map(e=>D(n.getElementById(e))).join(` `)}function k(e){let t=e.labels;return t&&t.length>0?D(t[0]):e.getAttribute(`placeholder`)||e.getAttribute(`name`)||``}function we(e){let t=e.querySelector(`img[alt],svg[aria-label],svg title,[aria-label]`);return t?t.getAttribute(`alt`)||t.getAttribute(`aria-label`)||D(t):``}function Te(e,t){let n=e.getAttribute(`aria-label`)||O(e);if(n)return n;if(e.isContentEditable||e.getAttribute(`role`)===`textbox`)return e.getAttribute(`aria-placeholder`)||``;if(t===`input`||t===`textarea`||t===`select`)return k(e);if(e.localName===`input`){let n=e;return t===`button`?n.value||n.alt||``:k(e)}if(t===`form`)return e.getAttribute(`name`)||e.id||``;if(Ce.has(t)&&!T.has(e)){let t=D(e);return t.trim()&&t.length<=200?t:we(e)||e.getAttribute(`title`)||``}let r=e.getAttribute(`title`);if(r)return r;if(!e.childElementCount&&(T.has(e)||e.hasAttribute(`data-cl`))){let t=D(e).trim();if(t.length<=32)return t}return``}let A=/\d{3,}|^:|:r[0-9a-z]+:|^radix-|^headlessui-|^react-aria|^mui-|^ember\d|^[a-f0-9-]{16,}$/i,Ee=[`data-testid`,`data-test`,`data-cy`,`data-qa`];function j(e){return e&&!A.test(e)?C(e,40):null}function De(e){let t=[],n=e;for(let e=0;n&&e<4&&n.localName!==`body`;e++){let e=n.localName;if(n.id&&n.id.length<40&&!A.test(n.id)){t.unshift(`${e}#${n.id}`);break}let r=Ee.find(e=>j(n.getAttribute(e)));if(r){t.unshift(`${e}[${r}="${j(n.getAttribute(r))}"]`);break}let i=j(n.getAttribute(`name`));i?e+=`[name="${i}"]`:n.localName===`input`&&(e+=`[type=${n.type}]`),t.unshift(e),n=n.parentElement}return t.join(`>`)}function Oe(e){let t=e.getAttribute(`href`);if(!(!t||t.startsWith(`#`)||t.startsWith(`javascript:`)))try{let n=new URL(t,e.ownerDocument.baseURI);if(n.protocol!==`http:`&&n.protocol!==`https:`)return n.protocol;let r=y(n.pathname);return n.origin===e.ownerDocument.location?.origin?r:`${n.host}${r}`}catch{return}}function M(e,t,n){return n||F(e)?``:w(Te(e,t),c.w)}function ke(e,n){let i=E(e),o=r(e.getAttribute(t)),s=e.getAttribute(n.trackAttr)||void 0,l=M(e,i,n.maskAllText),u=o||s?void 0:De(e),d=u&&e.closest(`nav,header,aside,footer,[role=navigation],[role=banner],[role=complementary],[role=contentinfo]`)?`*`:n.route,f={id:a({kind:i,track:s,source:o?.source,component:o?.component,signature:o?.signature,route:d,label:l,selector:u}),k:i,tag:e.localName};l&&(f.l=l),s&&(f.tr=C(s,c.o)),o&&(f.c=o.component,f.s=o.source),u&&(f.sel=u);let p=i===`link`?Oe(e):void 0;return p&&(f.h=p),f}function N(e,t){for(let n=e;n;n=n.getRootNode().host)if(n.closest(t))return!0;return!1}let P=e=>N(e,`[data-cl-ignore]`),F=e=>N(e,`[data-cl-mask]`);function I(e,t){let n=null;for(let r of e)if(r instanceof Element){if(r.localName===`body`||r.localName===`html`)break;if(!n&&P(r)||r.localName===`label`&&r.control)return null;if(n??=r,r.matches(t))return r}if(!n)return null;let r=n;for(let e=0;r&&e<4&&r.localName!==`body`;e++){if(getComputedStyle(r).cursor===`pointer`)return T.add(r),r;r=r.parentElement}return null}function Ae(e,t){let n=e instanceof Element?e:e?.parentElement??null;return!n||P(n)?null:n.closest(`[data-cl],[${t}]`)??n}let L=1e3;var je=class{onRage;burst=null;finish=l(()=>this.end());constructor(e){this.onRage=e}add(e,t,n,r){let i=this.burst;i&&e-i.last<=L&&Math.hypot(t-i.x,n-i.y)<=30?(clearTimeout(i.timer),i.n++,i.last=e,i.timer=setTimeout(this.finish,L)):(this.end(),this.burst={ref:r,x:t,y:n,n:1,last:e,timer:setTimeout(this.finish,L)})}end(){let e=this.burst;e&&(clearTimeout(e.timer),this.burst=null,e.n>=3&&this.onRage(e.ref,e.n))}};let Me=/* @__PURE__ */ new Set([`input`,`textarea`,`select`,`checkbox`,`radio`,`option`,`form`]);function Ne(e,t){return t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||Me.has(E(e))||e.isContentEditable||e.localName===`a`&&(e.hasAttribute(`download`)||e.getAttribute(`target`)===`_blank`)?!1:!e.disabled}let Pe=e=>{let t=new je((t,n)=>e.emit({t:`rc`,...t,n})),n=/* @__PURE__ */ new Map,r=d(document,`pointerdown`,e=>{let t=e.target instanceof Node?e.target:null;for(let e of n.values())(!t||!e.element.contains(t))&&e.finish()}),i=d(document,`click`,r=>{if(!r.isTrusted)return;let i=I(r.composedPath(),e.interactive);if(!i)return;let a=e.ref(i),o=Date.now();if(e.emit({t:`ck`,...a}),e.markClick(a),t.add(o,r.clientX,r.clientY,a),Ne(i,r)&&!n.has(a.el)){let t=e.activity.watch(1e3,t=>{n.delete(a.el),t||e.emit({t:`dc`,...a})});n.set(a.el,{element:i,finish:t})}});return()=>{i(),r(),t.end()}},Fe=e=>d(document,`copy`,()=>{let t=Ae(document.getSelection()?.anchorNode??null,e.config.trackAttribute);t&&e.emit({t:`cp`,...e.ref(t)})}),Ie=[/^Script error\.?$/,/ResizeObserver loop/,/^Non-Error promise rejection captured/];function Le(e,t){if(e)try{let n=new URL(e,location.href),r=n.origin===location.origin?n.pathname:`${n.host}${n.pathname}`;return t?`${r}:${t}`:r}catch{return}}function Re(e){return e instanceof Error?`${e.name}: ${e.message}`:typeof e==`string`?e:`Unhandled promise rejection`}let ze=e=>{let t=/* @__PURE__ */ new Set;e.onPage({start(){t=/* @__PURE__ */ new Set}});function n(n,r){let i=w(n,c.b);if(!i||Ie.some(e=>e.test(i)))return;!t.has(i)&&t.size<10&&(t.add(i),e.emit(r?{t:`er`,m:i,src:r}:{t:`er`,m:i}));let a=e.recentClick(1e3);a&&!a.errored&&(a.errored=!0,e.emit({t:`ec`,...a.ref,m:i}))}let r=d(window,`error`,e=>{e instanceof ErrorEvent&&e.message&&n(e.error instanceof Error?`${e.error.name}: ${e.error.message}`:e.message,Le(e.filename,e.lineno))}),i=d(window,`unhandledrejection`,e=>n(Re(e.reason)));return()=>{r(),i()}};function R(e){if(!(e instanceof Element))return null;let t=e.closest(`input:not([type=hidden]),textarea,select,[contenteditable=""],[contenteditable=true]`);return t&&!P(t)?t:null}let Be=e=>{let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map;function i(t){let n=r.get(t);return n||(n={ref:e.ref(t),fields:/* @__PURE__ */ new Set,last:``,submitted:!1},r.set(t,n)),n}function a(t){if(P(t))return;let r=e.ref(t);n.has(r.el)||(n.add(r.el),e.emit({t:`fe`,...r}))}function o(e){setTimeout(l(()=>{for(let t of e.querySelectorAll(`[aria-invalid="true"]`))a(t)}),400)}e.onPage({start(){t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map},end(){for(let t of r.values())t.submitted||t.fields.size===0||e.emit({t:`fb`,...t.ref,n:t.fields.size,lf:t.last})}});let s=[d(document,`input`,n=>{if(!n.isTrusted)return;let r=R(n.target);if(!r)return;let a=e.ref(r);t.has(a.el)||(t.add(a.el),e.emit({t:`fi`,...a}));let o=r.form;if(o){let e=i(o);e.fields.add(a.el),e.last=a.el}}),d(document,`invalid`,e=>{let t=R(e.target);t&&a(t)}),d(document,`focusout`,e=>{let t=R(e.target);t?.getAttribute(`aria-invalid`)===`true`&&a(t)}),d(document,`submit`,t=>{let n=t.target;if(!(n instanceof HTMLFormElement)||P(n))return;let r=i(n);r.submitted=!0,e.emit({t:`fs`,...r.ref}),o(n)})];return()=>{for(let e of s)e()}},z=.5,Ve=e=>{if(typeof IntersectionObserver>`u`||typeof MutationObserver>`u`)return()=>void 0;let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new WeakSet,i=[],a=null;function o(r){for(let i of r)!i.isIntersecting||i.intersectionRatio<z||(s.unobserve(i.target),!P(i.target)&&(t.size+n.size>=c.C||t.set(i.target,e.ref(i.target).el)))}let s=new IntersectionObserver(l(o),{threshold:z});function u(e){r.has(e)||P(e)||(r.add(e),s.observe(e))}function d(t){t instanceof Element&&t.matches(e.interactive)&&u(t);for(let n of t.querySelectorAll(e.interactive))u(n)}function f(){a=null;let e=i;i=[];for(let t of e)t.isConnected&&d(t)}function p(){o(s.takeRecords());let r=[];for(let e of t.values())n.has(e)||(n.add(e),r.push(e));t=/* @__PURE__ */ new Map,r.length>0&&e.emit({t:`im`,els:r})}let m=new MutationObserver(l(e=>{for(let t of e)for(let e of t.addedNodes)e instanceof Element&&i.push(e);i.length>0&&a===null&&(a=setTimeout(l(f),250))}));return e.onPage({start(){s.disconnect(),t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new WeakSet,d(document)},hidden:p,end:p,route(){for(let n of t.keys())t.set(n,e.ref(n).el)}}),m.observe(document.documentElement,{childList:!0,subtree:!0}),()=>{m.disconnect(),s.disconnect(),a!==null&&clearTimeout(a)}},B=2e3;function He(e){try{let t=new URL(e,location.href),n=y(t.pathname);return t.origin===location.origin?n:`${t.host}${n}`}catch{return`unknown`}}function V(e){return e.includes(`${s}?k=`)}let Ue=e=>{function t(t,n,r,i){if(t.failures>=3)return;t.failures++;let a=C(`${n.toUpperCase()} ${He(r)}`,c.b);e.emit({t:`fa`,...t.ref,st:i,m:a})}let n=l((n,r,i)=>{let a=r instanceof Request?r:void 0,o=typeof r==`string`?r:r instanceof URL?r.href:a?.url;if(o&&V(o))return;e.activity.signal();let s=e.recentClick(B);if(!s||!o)return;let c=i?.method??a?.method??`GET`;return n.then(e=>(l(()=>{let n=e.status;n>=400&&t(s,c,o,n)})(),e),e=>{throw l(()=>{!(i?.signal??a?.signal)?.aborted&&!(e instanceof DOMException&&e.name===`AbortError`)&&t(s,c,o,0)})(),e})}),r=u(window,`fetch`,e=>function(...t){let r;try{r=e.apply(this,t)}catch(e){r=Promise.reject(e)}return n(r,...t)??r}),i=/* @__PURE__ */ new WeakMap,a=l((e,t,n)=>{i.set(e,{method:t,url:String(n)})}),o=l(n=>{let r=i.get(n);if(r&&!V(r.url)){e.activity.signal();let a=e.recentClick(B);if(a){let e=()=>{(n.status===0||n.status>=400)&&t(a,r.method,r.url,n.status)};if(n.readyState===XMLHttpRequest.DONE)return e();let o=!1,s=d(n,`abort`,()=>{o=!0},{once:!0});d(n,`loadend`,()=>{s(),!o&&i.get(n)===r&&e()},{once:!0})}}});if(typeof XMLHttpRequest>`u`)return r;let s=XMLHttpRequest.prototype,f=u(s,`open`,e=>function(...t){let n=Reflect.apply(e,this,t);return a(this,t[0],t[1]),n}),p=u(s,`send`,e=>function(...t){let n=e.apply(this,t);return o(this),n});return()=>{r(),f(),p()}};function We(){let e=document.documentElement,t=Math.max(e.scrollHeight,document.body?.scrollHeight??0);return t<=0?100:Math.min(100,Math.round((window.scrollY+window.innerHeight)/t*100))}function Ge(e){return t=>{let n=0,r=0,i=0,a=!1,o=()=>{r&&(n+=Date.now()-r),r=0},s=()=>{!r&&document.visibilityState===`visible`&&(r=Date.now())},c=()=>{a||(a=!0,requestAnimationFrame(l(()=>{a=!1,i=Math.max(i,We())})))};t.onPage({start(){n=0,r=0,s(),i=0,c()},end(e,r){o(),t.emit({t:`pl`,d:n,sd:i});let a=Date.now()-e.start;r===`pop`&&a<5e3&&t.emit({t:`qb`,d:a})}});let f=t=>n=>{let r=l(()=>e.navigate(t));return function(...e){let t=n.apply(this,e);return r(),t}},p=[u(history,`pushState`,f(`push`)),u(history,`replaceState`,f(`replace`)),d(window,`popstate`,()=>e.navigate(`pop`)),d(window,`scroll`,c),d(document,`visibilitychange`,()=>{document.visibilityState===`hidden`?o():s()})];return()=>{for(let e of p)e()}}}function Ke(e){let t=[];for(let n=e;n;n=n.parentNode)t.push(n);return t}let qe=e=>{if(typeof PerformanceObserver>`u`||!PerformanceObserver.supportedEntryTypes?.includes(`event`))return()=>void 0;let t=/* @__PURE__ */ new Set,n=new PerformanceObserver(l(n=>{for(let r of n.getEntries()){let n=r.interactionId;if(!n||t.has(n)||r.duration<e.config.slowInteractionMs)continue;let i=r.target;if(!i)continue;let a=I(Ke(i),e.interactive);a&&(t.add(n),e.emit({t:`si`,...e.ref(a),d:Math.round(r.duration)}))}}));return n.observe({type:`event`,durationThreshold:104,buffered:!1}),()=>n.disconnect()},Je=/* @__PURE__ */ new Set([`password`,`hidden`,`file`]),Ye=/\b(cc-[a-z-]+|one-time-code|current-password|new-password)\b/i,Xe=/pass(word|code)?|pwd|card|cvv|cvc|ccnum|security.?code|ssn|iban|\bpin\b|otp|secret|token|api.?key/i,Ze=/search|query|filter|find/i;function H(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement}function Qe(e){if(e instanceof HTMLInputElement&&Je.has(e.type)||Ye.test(e.getAttribute(`autocomplete`)??``))return!0;let t=[e.name,e.id,e.getAttribute(`aria-label`),e.getAttribute(`placeholder`),O(e),...Array.from(e.labels??[],e=>e.textContent)].join(` `);return Xe.test(t)}function $e(e){return e instanceof HTMLInputElement&&e.type===`search`||e.getAttribute(`role`)===`searchbox`||Ze.test(`${e.name} ${e.getAttribute(`aria-label`)??``} ${e.getAttribute(`placeholder`)??``}`)}function et(e,t){if(e instanceof HTMLSelectElement)return[...e.selectedOptions].map(e=>e.label||e.text||e.value).join(`, `);if(e instanceof HTMLInputElement){if(e.type===`checkbox`)return e.checked?`checked`:`unchecked`;if(e.type===`radio`)return e.checked?M(e,`radio`,t)||e.value:``}return e.value}let tt=e=>{let t=/* @__PURE__ */ new Map;e.onPage({start(){t=/* @__PURE__ */ new Map}});function n(n){if(!(n instanceof Element)||!H(n))return;let r=n.closest(`[data-cl-capture]`)!==null;if(!e.config.captureInputValues&&!r||P(n)||F(n)||Qe(n))return;let i=w(et(n,e.config.maskAllText),c.D);if(!i)return;let a=e.ref(n);t.get(a.el)!==i&&(t.set(a.el,i),e.emit({t:`fv`,...a,v:i}))}let r=[d(document,`change`,e=>{e.isTrusted&&n(e.target)}),d(document,`keydown`,e=>{e.isTrusted&&e.key===`Enter`&&e.target instanceof Element&&H(e.target)&&$e(e.target)&&n(e.target)})];return()=>{for(let e of r)e()}};function nt(e){let t=/* @__PURE__ */ new Map,n=null;try{n=window.localStorage}catch{n=null}let r=t=>`${e}_${t}`;return{get(e){try{return n?n.getItem(r(e)):t.get(r(e))??null}catch{return t.get(r(e))??null}},set(e,i){t.set(r(e),i);try{n?.setItem(r(e),i)}catch{n=null}},remove(e){t.delete(r(e));try{n?.removeItem(r(e))}catch{n=null}}}}function U(e,t){let n=e.get(t);if(!n)return null;try{return JSON.parse(n)}catch{return null}}function rt(e){let t=e;return typeof t?.attempts==`number`&&Array.isArray(t.batch?.e)}var it=class{#e;#t;constructor(e,t){this.#t=e,this.#e=`q_${t}`}get size(){return this.#n().length}add(e,t){if(t>=6)return;let n=this.#n().filter(t=>!e.i||t.batch.i!==e.i);n.push({batch:e,attempts:t}),this.#r(n)}take(){let e=this.#n(),t=e.shift();return t&&this.#r(e),t}clear(){this.#t.remove(this.#e)}#n(){let e=U(this.#t,this.#e);return Array.isArray(e)?e.filter(rt):[]}#r(e){let t=JSON.stringify(e);for(;t.length>262144&&e.length>1;)e.shift(),t=JSON.stringify(e);e.length>0?this.#t.set(this.#e,t):this.clear()}},at=class{#e=!1;#t=!1;#n=null;#r=null;#i=0;#a=!1;#o=0;#s=l(()=>this.flush(`normal`));#c;#l;#u;#d;#f;constructor(e,t,n,r,i){this.#c=e,this.#l=t,this.#u=n,this.#d=r,this.#f=i}start(){this.#e=!0,this.#t=!1,this.#u.size>0&&this.#_(0)}stop(){this.#e=!1,this.#m(),this.#r!==null&&clearTimeout(this.#r),this.#r=null}discard(){this.stop(),this.#t=!0,this.#c.clear(),this.#u.clear()}queued(){this.#c.size>=this.#f.flushAt?queueMicrotask(this.#s):this.#n??=setTimeout(this.#s,this.#p())}#p(){let{flushIntervalMs:e}=this.#f;return Date.now()<this.#o?Math.min(500,e):this.#a?e:Math.min(1e3,e)}#m(){this.#n!==null&&clearTimeout(this.#n),this.#n=null}flush(e){if(this.#m(),this.#e&&this.#d().sessionId)for(let t=this.#h();t;t=this.#h())e===`unload`?this.#l.beacon(t)||this.#u.add(t,0):(this.#a=!0,this.#g(t,0).then(l(e=>{e||this.#_()}),()=>void 0))}#h(){return this.#c.take(this.#d())}async#g(e,t){let{result:n,live:r}=await this.#l.send(e);return r&&(this.#o=Date.now()+6e4),n!==`retry`||(this.#t||this.#u.add(e,t+1),!1)}#_(e=2e3*2**Math.min(this.#i,5)){this.#r===null&&this.#e&&(this.#r=setTimeout(l(()=>{this.#r=null,this.#v().catch(()=>void 0)}),e))}async#v(){for(let e=this.#u.size;e>0&&this.#e;e--){let e=this.#u.take();if(!e)break;if(!await this.#g(e.batch,e.attempts)){this.#i++,this.#_();return}}this.#i=0}},ot=class{#e=null;#t=0;#n;#r;constructor(e,t){this.#n=e,this.#r=t}current(e){let t=this.#i();return t&&e-t.last<this.#r?(this.#e=t,this.#o(e),{id:t.id,isNew:!1}):{id:this.#a(e),isNew:!0}}#i(){let e=U(this.#n,`s`),t=e&&v(e.id)&&typeof e.last==`number`?e:null,n=this.#e;return!t||!n?t??n:t.id===n.id?{id:n.id,last:Math.max(t.last,n.last)}:t.last>=n.last?t:n}clear(){this.#e=null,this.#n.remove(`s`)}#a(e){return this.#e={id:ee(e),last:e},this.#s(),this.#e.id}#o(e){this.#e&&(this.#e.last=e,e-this.#t>=5e3&&this.#s())}#s(){this.#e&&(this.#t=this.#e.last,this.#n.set(`s`,JSON.stringify(this.#e)))}};let W=6e4;async function st(e){if(typeof CompressionStream>`u`)return null;try{let t=new Blob([e]).stream().pipeThrough(new CompressionStream(`gzip`));return await new Response(t).blob()}catch{return null}}function ct(e){return e>=200&&e<300?`ok`:e===408||e===429||e>=500?`retry`:`drop`}function lt(e,t,n=!1){return{async send(r){let i=JSON.stringify({...r,at:Date.now()}),a=i.length>1024?await st(i):null,o=a??i,s=a?a.size:i.length;try{let r=await t(a?`${e}&z=1`:e,{method:`POST`,body:o,headers:{"content-type":`text/plain;charset=UTF-8`},credentials:`omit`,keepalive:s<W}),i=ct(r.status);return n&&i===`drop`&&r.status>=400&&r.status<500&&l(()=>console.warn(`[clicklore] dropped batch, HTTP`,r.status))(),{result:i,live:r.headers.get(`x-cl-live`)===`1`}}catch{return{result:`retry`,live:!1}}},beacon(n){let r=JSON.stringify({...n,at:Date.now()});if(r.length>=W)return!1;let i=new Blob([r],{type:`text/plain;charset=UTF-8`});try{return typeof navigator.sendBeacon==`function`?navigator.sendBeacon(e,i):(t(e,{method:`POST`,body:i,credentials:`omit`,keepalive:!0}).catch(()=>void 0),!0)}catch{return!1}}}}let ut=[`a`,`u`,`g`,`q`],G=e=>e.tr===void 0&&e.s===void 0;function K(e,t){let n={};if(!e)return n;let r=0;for(let[i,a]of Object.entries(e)){if(r>=c.T)break;let e=C(i,c.o);if(a===null||typeof a==`boolean`)n[e]=a;else if(typeof a==`number`)n[e]=Number.isFinite(a)?a:null;else if(typeof a==`string`)n[e]=C(t?ve(a):a,c.E);else if(a instanceof Date)n[e]=a.toISOString();else continue;r++}return n}function dt(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=Object.values(e);if(!(t.length===0||t.some(e=>typeof e!=`string`)))return e}function ft(){let e=navigator;return e.doNotTrack===`1`||e.globalPrivacyControl===!0}var pt=class{config;interactive;activity;#e;#t=new ie;#n;#r;#i=[];#a=/* @__PURE__ */ new WeakMap;#o=[];#s=!1;#c=null;#l=null;#u;#d;#f;#p=``;#m=null;#h=0;#g=!1;#_=null;constructor(e,t){this.config=m(e),this.interactive=be(this.config.trackAttribute),this.#e=nt(this.config.storagePrefix),this.#n=new ot(this.#e,this.config.sessionTimeoutMs),this.#r=new at(this.#t,t??lt(this.config.endpoint,window.fetch.bind(window),this.config.debug),new it(this.#e,this.config.projectKey),()=>({anonId:this.#u,sessionId:this.#p,userId:this.#d,groups:this.#f}),this.config),this.activity=f(document);let n=this.#e.get(`a`);this.#u=v(n)?n:_(),this.#d=C(this.#e.get(`u`)??``,c.f)||void 0,this.#f=dt(U(this.#e,`g`))}start(){if(this.#s||this.#c||!this.#b())return;if(document.prerendering){this.#c=d(document,`prerenderingchange`,()=>{this.#c=null,this.start()},{once:!0});return}this.#s=!0,this.#S(),this.#e.remove(`q`),this.#r.start();let e=this.config.capture;e.pages&&this.#o.push(Ge({navigate:e=>this.#j(e)})(this)),e.clicks&&this.#o.push(Pe(this)),e.impressions&&this.#o.push(Ve(this)),e.forms&&this.#o.push(Be(this)),this.#o.push(tt(this)),e.errors&&this.#o.push(ze(this)),e.network&&this.#o.push(Ue(this)),e.slowInteractions&&this.#o.push(qe(this)),e.copy&&this.#o.push(Fe(this)),this.#o.push(d(window,`storage`,e=>{e.key===`${this.config.storagePrefix}_c`&&e.newValue===`out`&&e.storageArea===localStorage&&this.#x()}),d(document,`visibilitychange`,()=>{document.visibilityState===`hidden`&&(this.#P((e,t)=>e.hidden?.(t)),this.flush(`unload`))}),d(window,`pagehide`,()=>{this.#j(`unload`),this.flush(`unload`)}),d(window,`pageshow`,e=>{e.persisted&&this.#j(`restore`)})),this.#M()}stop(e=!0){try{e&&this.#s&&this.#N(`unload`),e||this.#v(),this.#y(),e&&this.flush(`normal`)}finally{this.#v()}}#v(){this.#s=!1,this.#r.stop(),this.#c?.(),this.#c=null}#y(){for(let e of this.#o.splice(0))l(e)();this.#i.length=0,this.activity.dispose(),this.#m=null}#b(){let e=this.#e.get(`c`);return e===`out`||this.config.requireConsent&&e!==`in`?!1:!(this.config.respectDoNotTrack&&ft())}optIn(){this.#e.set(`c`,`in`),this.start()}optOut(){this.#e.set(`c`,`out`),this.#x()}#x(){this.stop(!1),this.#r.discard();for(let e of ut)this.#e.remove(e);this.#n.clear(),this.#p=``,this.#u=_()}identify(e,t){let n=C(String(e),c.f);n&&(n!==this.#d&&(this.flush(`normal`),this.#t.setTraits(void 0),this.#d=n,this.#S()),t&&this.#t.setTraits(K(t,!1)),this.emit({t:`id`}))}group(e,t){this.flush(`normal`),this.#f={...this.#f,[C(e,c.o)]:C(String(t),c.f)},this.#S()}reset(){this.flush(`normal`),this.#t.setTraits(void 0),this.#d=void 0,this.#f=void 0,this.#u=_(),this.#S(),this.#n.clear(),this.#p=``,this.#m&&this.emit(this.#T(this.#m))}get anonymousId(){return this.#u}get currentSessionId(){return this.#p||null}#S(){this.#s&&(this.#e.set(`a`,this.#u),this.#d?this.#e.set(`u`,this.#d):this.#e.remove(`u`),this.#f?this.#e.set(`g`,JSON.stringify(this.#f)):this.#e.remove(`g`))}track(e,t){let n=C(e.trim(),c.o);if(!n)return;let r=K(t,!0);this.emit(Object.keys(r).length>0?{t:`cu`,n,pr:r}:{t:`cu`,n})}emit(e){if(!this.#s)return;let t=Date.now(),n=this.#g&&this.#p?null:this.#n.current(t);n&&n.id!==this.#p&&(this.#p&&this.flush(`normal`),this.#p=n.id,n.isNew&&(this.#w(this.#C(this.#E(),t)),e.t!==`pv`&&this.#m&&this.#w(this.#C(this.#T(this.#m),t)))),this.#w(this.#C(e,t))}#C(e,t){return{...e,ts:t,p:this.#O()}}#w(e){this.config.debug&&console.debug(`[clicklore]`,e.t,e),this.#t.push(e,this.#m?.seq??this.#h),this.#r.queued()}#T(e){let t=w(document.title,c.o);return{t:`pv`,pa:e.sanitizedPath,ti:t||void 0}}#E(){let e=new URLSearchParams(location.search),t={};for(let[n,r]of e)n.startsWith(`utm_`)&&r&&(t[C(n.slice(4),c.o)]=C(r,200));let n={t:`ss`,sw:window.screen?.width??0,sh:window.screen?.height??0,lang:navigator.language,tz:Intl.DateTimeFormat().resolvedOptions().timeZone};Object.keys(t).length>0&&(n.utm=t);let r=this.#D();return r&&(n.r=r),n}#D(){if(document.referrer)try{let e=new URL(document.referrer);return e.origin===location.origin?void 0:`${e.host}${e.pathname===`/`?``:y(e.pathname)}`}catch{return}}ref(e){let{trackAttribute:n,maskAllText:r}=this.config,i=this.#O(),a=E(e),o=M(e,a,r),s=`${a}|${e.getAttribute(t)}|${e.getAttribute(n)}`,c=this.#a.get(e);return(!c||c.inputs!==s||G(c.def)&&(c.route!==i||o!==(c.def.l??``)))&&(c={def:ke(e,{route:i,trackAttr:n,maskAllText:r}),inputs:s,route:i},this.#a.set(e,c)),this.#t.define(c.def),!G(c.def)&&o&&o!==c.def.l?{el:c.def.id,lb:o}:{el:c.def.id}}markClick(e){this.#l={time:Date.now(),ref:e,errored:!1,failures:0}}recentClick(e){let t=this.#l;return t&&Date.now()-t.time<=e?t:null}onPage(e){this.#i.push(e)}#O(){return this.#m?.route??this.#A()}#k(e){let t=l(()=>this.config.sanitizeUrl?.(e))();return C(typeof t==`string`?t:y(e),c._)}#A(e=location.pathname,t){if(this.#_?.path===e)return this.#_.route;let n=l(()=>this.config.route?.(e))();return typeof n==`string`?C(n,c._):t??this.#k(e)}setRoute(e){let t=C(e,c._);this.#_={path:location.pathname,route:t};let n=this.#m;if(n&&n.path===location.pathname&&n.route!==t){n.route=t,this.#t.rewriteRoute(n.seq,t);for(let e of this.#i)l(()=>e.route?.(n))()}}#j(e){this.activity.signal(),e===`restore`?this.#m||this.#M():(e===`unload`||this.#m?.path!==location.pathname)&&(this.#N(e),e!==`unload`&&this.#M())}#M(){let e=location.pathname,t=this.#k(e),n={seq:++this.#h,route:this.#A(e,t),path:e,sanitizedPath:t,start:Date.now()};this.#m=n,this.emit(this.#T(n));for(let e of this.#i)l(()=>e.start?.(n))()}#N(e){this.#P((t,n)=>t.end?.(n,e)),this.#m=null}#P(e){let t=this.#m;if(!t)return;let n=this.#g;this.#g=!0;try{for(let n of this.#i)l(e)(n,t)}finally{this.#g=n}}flush(e){this.#r.flush(e)}};let q=Symbol.for(`clicklore`),J,mt=!1,Y=[];function X(e){typeof window<`u`&&(J?l(e)(J):J===void 0&&Y.length<100&&Y.push(e))}let Z=l(e=>{if(typeof window>`u`||typeof document>`u`||J)return;let t=globalThis;try{if(t[q]){mt||console.warn(`[clicklore] another copy of the SDK is already running; ignoring init()`),mt=!0;return}let n=new pt(e);J=n,t[q]=n,n.start();for(let e of Y.splice(0))l(e)(n)}catch(e){let n=J;J=null,Y.length=0,l(()=>n?.stop(!1))(),t[q]===n&&delete t[q],console.error(`[clicklore] could not start SDK`,e)}});function ht(e,t){X(n=>n.track(e,t))}function gt(e,t){X(n=>n.identify(e,t))}function _t(e,t){X(n=>n.group(e,t))}function vt(){X(e=>e.reset())}function yt(e){X(t=>t.setRoute(e))}function bt(){X(e=>e.optIn())}function xt(){X(e=>e.optOut())}let St=l(()=>{J?.flush(`normal`)}),Q=l(()=>{if(!J)return;J.stop();let e=globalThis;e[q]===J&&delete e[q],J=void 0});function Ct(){return J?.anonymousId??null}function wt(){return J?.currentSessionId??null}let Tt={track:ht,identify:gt,group:_t,reset:vt,setRoute:yt,optIn:bt,optOut:xt,flush:St,shutdown:Q,getAnonymousId:Ct,getSessionId:wt},$=document.currentScript,Et=$?.dataset.key;if($&&Et){let e=$.dataset;Z({projectKey:Et,host:e.host??new URL($.src,location.href).origin,maskAllText:e.maskAllText!==void 0,captureInputValues:e.captureInputValues!==void 0,requireConsent:e.requireConsent!==void 0,debug:e.debug!==void 0})}let Dt=window.clicklore?.q;if(Array.isArray(Dt))for(let e of Dt.splice(0))l(e)(Tt);return e.SDK_VERSION=p,e.clicklore=Tt,e.flush=St,e.getAnonymousId=Ct,e.getSessionId=wt,e.group=_t,e.identify=gt,e.init=Z,e.optIn=bt,e.optOut=xt,e.reset=vt,e.setRoute=yt,e.shutdown=Q,e.track=ht,e})({});
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
//#region src/config.d.ts
|
|
2
|
+
interface CaptureOptions {
|
|
3
|
+
/** page views, page leave (time on page, scroll depth), quick backs */
|
|
4
|
+
pages: boolean;
|
|
5
|
+
/** clicks, rage clicks, dead clicks, error clicks */
|
|
6
|
+
clicks: boolean;
|
|
7
|
+
/** which interactive elements were actually seen */
|
|
8
|
+
impressions: boolean;
|
|
9
|
+
/** field interaction, validation errors, submits, abandonment (values: see `captureInputValues`) */
|
|
10
|
+
forms: boolean;
|
|
11
|
+
/** uncaught errors and unhandled rejections */
|
|
12
|
+
errors: boolean;
|
|
13
|
+
/** failed fetch/XHR requests that follow a click */
|
|
14
|
+
network: boolean;
|
|
15
|
+
/** interactions slower than `slowInteractionMs` (Event Timing API) */
|
|
16
|
+
slowInteractions: boolean;
|
|
17
|
+
/** copy events */
|
|
18
|
+
copy: boolean;
|
|
19
|
+
}
|
|
20
|
+
interface ClickloreConfig {
|
|
21
|
+
/** Public project key (`cl_…`). Named `projectKey` because `key` is reserved for React props. */
|
|
22
|
+
projectKey: string;
|
|
23
|
+
/** Ingest host, e.g. `https://ingest.example.com`. */
|
|
24
|
+
host: string;
|
|
25
|
+
/** Turn individual capture features on or off. Everything is on by default. */
|
|
26
|
+
capture?: Partial<CaptureOptions>;
|
|
27
|
+
/** Attribute used for explicit element names. Default `data-track`. */
|
|
28
|
+
trackAttribute?: string;
|
|
29
|
+
/** Never capture element text (labels become empty). Use for apps that render sensitive content. */
|
|
30
|
+
maskAllText?: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Record what users enter into fields (on commit: change/blur, Enter in search boxes). Off by
|
|
33
|
+
* default; fields can also opt in with `data-cl-capture`. Passwords, payment and one-time-code
|
|
34
|
+
* fields are never captured, and values are redacted (emails, long numbers, tokens).
|
|
35
|
+
*/
|
|
36
|
+
captureInputValues?: boolean;
|
|
37
|
+
/** Capture nothing until `optIn()` is called. */
|
|
38
|
+
requireConsent?: boolean;
|
|
39
|
+
/** Capture nothing when the browser sends Do Not Track or Global Privacy Control. */
|
|
40
|
+
respectDoNotTrack?: boolean;
|
|
41
|
+
/** Custom route template resolver; return undefined to fall back to the built-in heuristic. */
|
|
42
|
+
route?: (pathname: string) => string | undefined;
|
|
43
|
+
/** Replaces a captured page path. Return undefined to use the built-in redaction. */
|
|
44
|
+
sanitizeUrl?: (pathname: string) => string | undefined;
|
|
45
|
+
/** Minimum duration for a slow interaction, ms. Default 500 (INP "poor"). */
|
|
46
|
+
slowInteractionMs?: number;
|
|
47
|
+
/** Flush interval, ms. Default 5000. */
|
|
48
|
+
flushIntervalMs?: number;
|
|
49
|
+
/** Queue size that triggers an immediate flush. Default 50. */
|
|
50
|
+
flushAt?: number;
|
|
51
|
+
/** Inactivity that starts a new session, ms. Default 30 minutes. */
|
|
52
|
+
sessionTimeoutMs?: number;
|
|
53
|
+
/** Prefix for localStorage keys. Default `cl`. */
|
|
54
|
+
storagePrefix?: string;
|
|
55
|
+
/** Log captured events to the console. */
|
|
56
|
+
debug?: boolean;
|
|
57
|
+
}
|
|
58
|
+
export declare const SDK_VERSION: string;
|
|
59
|
+
//#endregion
|
|
60
|
+
//#region src/index.d.ts
|
|
61
|
+
/**
|
|
62
|
+
* Starts capturing. Safe to call during SSR (no-op) and more than once (later calls are ignored).
|
|
63
|
+
* When another copy of the SDK already runs on the page, this one warns and stays inactive.
|
|
64
|
+
*/
|
|
65
|
+
export declare const init: (config: ClickloreConfig) => void;
|
|
66
|
+
/** Records a custom event. */
|
|
67
|
+
export declare function track(name: string, props?: Record<string, unknown>): void;
|
|
68
|
+
/** Associates this visitor with your user id; traits (email, plan…) show up on their profile. */
|
|
69
|
+
export declare function identify(userId: string, traits?: Record<string, unknown>): void;
|
|
70
|
+
/** Associates this visitor with a group, e.g. `group('org', 'acme')`. */
|
|
71
|
+
export declare function group(type: string, id: string): void;
|
|
72
|
+
/** Forgets the identified user (call on logout). */
|
|
73
|
+
export declare function reset(): void;
|
|
74
|
+
/** Tells Clicklore the route template for the current URL, e.g. `/projects/[id]`. */
|
|
75
|
+
export declare function setRoute(template: string): void;
|
|
76
|
+
export declare function optIn(): void;
|
|
77
|
+
export declare function optOut(): void;
|
|
78
|
+
/** Sends queued events now. */
|
|
79
|
+
export declare const flush: () => void | undefined;
|
|
80
|
+
/** Stops capturing and removes all listeners and patches. */
|
|
81
|
+
export declare const shutdown: () => void | undefined;
|
|
82
|
+
export declare function getAnonymousId(): string | null;
|
|
83
|
+
export declare function getSessionId(): string | null;
|
|
84
|
+
/**
|
|
85
|
+
* The public API as one object: what framework adapters hand out (e.g. `useClicklore()`), so
|
|
86
|
+
* every adapter exposes the same functions.
|
|
87
|
+
*/
|
|
88
|
+
export declare const clicklore: {
|
|
89
|
+
readonly track: typeof track;
|
|
90
|
+
readonly identify: typeof identify;
|
|
91
|
+
readonly group: typeof group;
|
|
92
|
+
readonly reset: typeof reset;
|
|
93
|
+
readonly setRoute: typeof setRoute;
|
|
94
|
+
readonly optIn: typeof optIn;
|
|
95
|
+
readonly optOut: typeof optOut;
|
|
96
|
+
readonly flush: () => void | undefined;
|
|
97
|
+
readonly shutdown: () => void | undefined;
|
|
98
|
+
readonly getAnonymousId: typeof getAnonymousId;
|
|
99
|
+
readonly getSessionId: typeof getSessionId;
|
|
100
|
+
};
|
|
101
|
+
export type ClickloreApi = typeof clicklore;
|
|
102
|
+
//#endregion
|
|
103
|
+
export type { CaptureOptions, ClickloreConfig };
|