@himetrica/replaykit 0.2.0 → 0.2.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/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/replaykit.global.js +3 -3
- package/dist/replaykit.global.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +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;
|
|
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(t){this.env=t;this.cache=null}load(t){if(_optionalChain([this, 'access', _2 => _2.cache, 'optionalAccess', _3 => _3.sid])===t)return this.cache;let e=null;try{let s=this.env.getSession(q);s&&(e=JSON.parse(s))}catch (e2){e=null}return(!e||e.sid!==t||typeof e.seq!="number")&&(e={sid:t,seq:0}),this.cache=e,e}save(t){this.cache=t;try{this.env.setSession(q,JSON.stringify(t))}catch (e3){}}};function E(i,t){return{startedAt:i,endedAt:i,activeMs:0,clicks:0,rageClicks:0,deadClicks:0,errors:0,pages:1,entryUrl:t}}var N=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,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function L(i,t){try{return i().getItem(t)}catch (e5){return null}}function B(i,t,e){try{e===null?i().removeItem(t):i().setItem(t,e)}catch (e6){}}function Z(){if(typeof indexedDB>"u")return;let i=null,t=()=>_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)})))),e=(s,r)=>t().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=>e("readonly",r=>r.get(s)),set:(s,r)=>e("readwrite",n=>{n.put(r,s)}).then(()=>{}),del:s=>e("readwrite",r=>{r.delete(s)}).then(()=>{})}}function tt(){if(!(typeof CompressionStream>"u"||typeof Blob>"u"||typeof Response>"u"))return i=>new Response(new Blob([i]).stream().pipeThrough(new CompressionStream("gzip"))).blob()}function F(){let i=typeof fetch=="function"?fetch.bind(globalThis):void 0,t=typeof navigator<"u"?navigator:void 0;return{now:()=>Date.now(),uuid:()=>Q(),fetch:i,sendBeacon:t&&typeof t.sendBeacon=="function"?(e,s)=>{try{return t.sendBeacon(e,new Blob([s],{type:"text/plain"}))}catch (e7){return!1}}:void 0,getLocal:e=>L(()=>localStorage,e),setLocal:(e,s)=>B(()=>localStorage,e,s),getSession:e=>L(()=>sessionStorage,e),setSession:(e,s)=>B(()=>sessionStorage,e,s),getCookie:e=>{try{let s=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return s?decodeURIComponent(s[1]):null}catch (e8){return null}},store:Z(),gzip:tt(),setTimer:(e,s)=>setTimeout(e,s),clearTimer:e=>clearTimeout(e)}}function O(i){let t=i.getCookie("hm_vid")||i.getLocal("hm_visitor_id")||void 0,e=i.getCookie("hm_sid")||i.getSession("hm_session_id")||void 0;return{visitorId:t,sessionId:e}}function et(i,t){let e=i.trim().toLowerCase();if(!e)return!1;let s=(t||"/").toLowerCase();if(!e.includes("*")){let n=e.endsWith("/")&&e.length>1?e.slice(0,-1):e;return s===n||s.startsWith(n.endsWith("/")?n:n+"/")}return new RegExp("^"+e.split("*").map(it).join(".*")+"$").test(s)}function x(i,t){for(let e of i)if(et(e,t))return!0;return!1}function it(i){return i.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}function st(i){let t=3735928559,e=1103547991;for(let r=0;r<i.length;r++){let n=i.charCodeAt(r);t=Math.imul(t^n,2654435761),e=Math.imul(e^n,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(4294967296*(2097151&e)+(t>>>0))/9007199254740992}function D(i,t){return t>0?t>=1?!0:st(i)<t:!1}function u(i){let t=i.search(/[?#]/);return t===-1?i:i.slice(0,t)}var w="replaykit:page";function U(i,t,e){let s=[],r=t;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>=e))break}return s}var _=3e4,f=3e4;function rt(i,t){return t>0&&i[t-1].type===4?t-1:t}function C(i,t,e=_){let s=t-e,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=rt(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(t){let e=this.burst;if(e&&t.ts-e.lastTs<=1e3&&nt(e.first,t))return e.count>=3||t.ts-e.first.ts<=1e3?(e.count++,e.lastTs=t.ts,e.last=t,{trigger:e.count===3,finished:null}):(this.burst={first:e.last,count:2,lastTs:t.ts,last:t},{trigger:!1,finished:null});let s=e&&e.count>=3?e:null;return this.burst={first:t,count:1,lastTs:t.ts,last:t},{trigger:!1,finished:s}}interrupt(){let t=this.burst;return this.burst=null,t&&t.count>=3?t:null}flush(t){let e=this.burst;return!e||t-e.lastTs<=1e3?null:(this.burst=null,e.count>=3?e:null)}currentCount(){return _nullishCoalesce(_optionalChain([this, 'access', _9 => _9.burst, 'optionalAccess', _10 => _10.count]), () => (0))}};function nt(i,t){return i.target&&i.target===t.target?!0:Math.abs(i.x-t.x)<=30&&Math.abs(i.y-t.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 ot=5e3;function A(i,t){if(!i)return 0;let e=t-i;return e>0&&e<=ot?e:0}var at=["error","rage_click","manual"];function M(i,t,e){return e<=0||at.includes(i)?0:Math.max(0,e-t)}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 lt(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(t,e,s){this.env=t;this.apiUrl=e;this.apiKey=s}url(t){return`${this.apiUrl}/api/t/r/${t}?apiKey=${encodeURIComponent(this.apiKey)}`}init(t){return this.post("init",t,!0)}chunk(t){return this.post("chunk",t,!0)}signals(t){return this.post("signals",t,!1)}beaconSignals(t){return!!_optionalChain([this, 'access', _11 => _11.env, 'access', _12 => _12.sendBeacon, 'optionalCall', _13 => _13(this.url("signals"),JSON.stringify(t))])}async put(t,e){if(!this.env.fetch)return"retry";try{let s=await this.env.fetch(t,{method:"PUT",body:e,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(t,e,s){if(!this.env.fetch)return{outcome:"retry"};try{let r=await this.env.fetch(this.url(t),{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"text/plain"},keepalive:!1,credentials:"omit"}),n=lt(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"}}}},ut=2e3,ht=6e4;function d(i){return Math.min(ht,ut*2**Math.max(0,i-1))}var ct=5e3,dt=200,pt=500,ft=2e3,v=class{constructor(t,e,s){this.env=t;this.api=e;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(t){if(this.disabled||this.sentThisPage+this.queue.length>=dt)return;let e=`${t.type}|${t.url}|${t.selector||""}|${t.detail||""}`,s=this.last.get(e);s!==void 0&&t.ts-s<ft||(this.last.set(e,t.ts),this.queue.push(t),this.queue.length>pt&&this.queue.shift(),!this.held&&(this.queue.length>=50?this.schedule(0):this.timer||this.schedule(ct)))}release(t){if(this.held=!1,!t){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(t){this.timer&&this.env.clearTimer(this.timer),this.timer=this.env.setTimer(()=>{this.timer=null,this.flush()},t)}async flush(){if(!(this.busy||this.held||this.disabled)){this.busy=!0;try{for(;this.queue.length&&!this.disabled;){let t=this.queue.slice(0,50),e=await this.api.signals({...this.ids(),signals:t});if(e.outcome==="ok"||e.outcome==="drop"||e.outcome==="quota"){this.queue.splice(0,t.length),this.sentThisPage+=t.length,this.failures=0;continue}if(e.outcome==="off"||e.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 t=this.queue.slice(0,50);if(!this.api.beaconSignals({...this.ids(),signals:t}))return;this.queue.splice(0,t.length),this.sentThisPage+=t.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]",mt=".hm-mask,[data-hm-mask],[data-hm-block],.hm-block",z=80,vt=200;function y(i){let t=[],e=i;for(let s=0;e&&s<3&&e.nodeType===1;s++){let r=e.tagName.toLowerCase();if(r==="html"||r==="body")break;if(e.id&&/^[A-Za-z][\w-]{0,40}$/.test(e.id)&&!/\d{3,}/.test(e.id)){t.unshift(`${r}#${e.id}`);break}let n=(typeof e.className=="string"?e.className:"").split(/\s+/).filter(a=>a&&a.length<30&&!/\d{3,}|^css-|^sc-|__/.test(a)).slice(0,2);t.unshift(r+n.map(a=>"."+a).join("")),e=e.parentElement}return t.join(" > ")}function X(i,t){if(t||i.closest(mt)||i.closest(j))return;let e=(_nullishCoalesce(_nullishCoalesce(i.innerText, () => (i.textContent)), () => (""))).replace(/\s+/g," ").trim();return e?e.slice(0,z):_optionalChain([(i.getAttribute("aria-label")||i.getAttribute("title")||void 0), 'optionalAccess', _14 => _14.slice, 'call', _15 => _15(0,z)])}function yt(i){let t=!1;try{t=getComputedStyle(i).cursor==="pointer"}catch (e13){t=!1}let e=typeof getSelection=="function"?getSelection():null;return{tag:i.tagName.toLowerCase(),insideInteractive:!!i.closest(Y),isFormField:!!i.closest(j),pointerCursor:t,hasSelection:!!e&&!e.isCollapsed&&e.toString().trim().length>0}}function bt(i){let t=i instanceof Element?i:i instanceof Node?i.parentElement:null;return t?t.closest(Y)||t:null}var b=class{constructor(t){this.h=t;this.rage=new g;this.rageEl=null;this.rageTimer=null;this.elKeys=new WeakMap;this.elSeq=0;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 t=(e,s,r=window)=>{let n={capture:!0,passive:!0};r.addEventListener(e,s,n),this.off.push(()=>r.removeEventListener(e,s,n))};t("click",e=>this.onClick(e)),t("keydown",()=>this.h.input("key",this.h.now())),t("scroll",()=>{let e=this.h.now();e-this.lastScrollInput>250&&(this.lastScrollInput=e,this.h.input("scroll",e))}),t("error",e=>this.onError(e.message||_optionalChain([e, 'access', _16 => _16.error, 'optionalAccess', _17 => _17.message])||"")),t("unhandledrejection",e=>{let s=e.reason;this.onError(typeof s=="string"?s:_optionalChain([s, 'optionalAccess', _18 => _18.message])||"Unhandled promise rejection")}),t("popstate",()=>this.backNav()),t("input",e=>this.onField(e.target)),t("change",e=>this.onField(e.target)),t("submit",e=>{e.target instanceof HTMLFormElement&&this.forms.delete(e.target)}),t("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 t of this.off)t();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(t){this.h.signal({ts:_nullishCoalesce(t.ts, () => (this.h.now())),url:u(location.href),...t})}checkHref(){let t=location.href;if(t===this.lastHref)return;let e=this.lastHref;this.lastHref=t,u(t)!==u(e)&&this.h.navigated(u(t))}onClick(t){let e=this.h.now();this.h.input("click",e);let s=bt(t.target);if(!s)return;if(!G(yt(s))){let a=this.rage.interrupt();a&&this.reportRage(a.count,a.first.ts);return}let r=y(s),n=this.rage.onClick({x:t.clientX,y:t.clientY,ts:e,target:this.keyOf(s)});n.finished&&this.reportRage(n.finished.count,n.finished.first.ts),n.trigger&&this.h.trigger("rage_click"),this.rage.currentCount()===1&&(this.rageEl=s),this.rageTimer&&clearTimeout(this.rageTimer),this.rageTimer=setTimeout(()=>this.flushRage(!1),1050),this.rage.currentCount()===1&&this.watchDeadClick(s,r,e)}keyOf(t){let e=this.elKeys.get(t);return e||this.elKeys.set(t,e=String(++this.elSeq)),e}flushRage(t){let e=this.rage.flush(t?Number.MAX_SAFE_INTEGER:this.h.now());e&&this.reportRage(e.count,e.first.ts)}reportRage(t,e){let s=this.rageEl;this.emit({type:"rage_click",ts:e,count:t,selector:s?y(s):void 0,text:s?X(s,this.h.maskAllText()):void 0})}watchDeadClick(t,e,s){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!==t,unloading:this.unloading})&&this.emit({type:"dead_click",ts:s,selector:e,text:X(t,this.h.maskAllText())})},H)}onError(t){let e=(t||"Error").slice(0,vt);this.errorsSeen.has(e)||(this.errorsSeen.add(e),this.emit({type:"error",detail:e}),this.h.trigger("error"))}backNav(){this.emit({type:"back_nav",detail:u(location.href)}),this.checkHref()}onField(t){if(!(t instanceof Element))return;let e=t.closest("form");if(!e)return;let s=t.getAttribute("name")||t.id||y(t),r=this.forms.get(e);r||this.forms.set(e,r=new Set),r.add(s)}flushForms(){for(let[t,e]of this.forms)!t.isConnected&&e.size===0||this.emit({type:"form_abandon",selector:y(t),count:e.size});this.forms.clear()}};var kt=["[data-hm-block]",".hm-block",'[autocomplete^="cc-"]','input[type="password"]'],St=".hm-mask,[data-hm-mask]",Rt=null;function Tt(){return _nullishCoalesce(Rt, () => ((Rt=Promise.resolve().then(() => _interopRequireWildcard(require("@rrweb/record"))).then(i=>i.record))))}function Et(i){return i.filter(t=>{if(!t||typeof t!="string")return!1;try{return document.createDocumentFragment().querySelector(t),!0}catch (e16){return!1}})}var k=class{constructor(){this.record=null;this.stopped=!1}async start(t){try{this.record=await Tt()}catch (e17){return!1}if(this.stopped)return!1;try{return this.stopFn=_nullishCoalesce(this.record({emit:e=>t.emit(e),checkoutEveryNms:f,maskAllInputs:!0,maskInputOptions:{password:!0},maskTextSelector:t.maskAllText?"*":St,blockSelector:Et([...kt,...t.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(t){try{_optionalChain([this, 'access', _28 => _28.record, 'optionalAccess', _29 => _29.addCustomEvent, 'call', _30 => _30(w,{href:t})])}catch (e20){}}stop(){this.stopped=!0;try{_optionalChain([this, 'access', _31 => _31.stopFn, 'optionalCall', _32 => _32()])}catch (e21){}this.stopFn=void 0}};var xt=3e4,wt=256*1024,S=i=>`rk:pending:${i}`,R=class{constructor(t,e,s,r,n){this.env=t;this.api=e;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 t=this.env.store;if(!t)return;let e=await t.get(S(this.ids.sid));if(!e)return;await t.del(S(this.ids.sid));let s=this.state();!s.rid||e.rid!==s.rid||!Array.isArray(e.events)||e.events.length===0||(this.queue=e.events.concat(this.queue),this.queuedBytes+=e.events.reduce((r,n)=>r+I(n),0),this.schedule(0))}add(t){this.stopped||(this.queue.push(t),this.queuedBytes+=I(t),this.queuedBytes>=wt?this.schedule(0):this.timer||this.schedule(xt))}addMany(t){for(let e of t)this.add(e)}schedule(t){this.timer&&this.env.clearTimer(this.timer),this.timer=this.env.setTimer(()=>{this.timer=null,this.flush()},t)}async flush(){if(this.busy||this.stopped)return;let t=this.epoch;this.busy=!0;try{for(;!this.stopped&&t===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 t=this.state();if(!t.rid||!t.trigger||!t.stats)return!1;if(t.seq>=600)return this.stop("limit"),!1;let e=this.env.gzip;if(!e)return this.stop("off"),!1;let s={v:1,rid:t.rid,seq:t.seq,events:this.inflight},r=await e(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===t.rid?this.lastPage:"",a=U(this.inflight,n,50),o=await this.api.chunk({rid:t.rid,sid:this.ids.sid,vid:this.ids.vid,seq:t.seq,bytes:r.size,trigger:t.trigger,stats:t.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=t.rid);let c=this.state();return c.rid===t.rid&&this.states.save({...c,seq:t.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(t){this.stopped=!0,this.queue=[],this.inflight=[],this.queuedBytes=0,this.clearTimers(),this.hooks.onStop(t)}clearTimers(){this.timer&&this.env.clearTimer(this.timer),this.retryTimer&&this.env.clearTimer(this.retryTimer),this.timer=this.retryTimer=null}persist(){let t=this.env.store,e=this.state(),s=this.inflight.concat(this.queue);!t||!e.rid||s.length===0||this.stopped||(this.parked=!0,t.set(S(this.ids.sid),{rid:e.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}`,Ct=500,It=15e3,At=3,T=class{constructor(t,e=F()){this.options=t;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=e;let s=(t.apiUrl||"https://app.himetrica.com").replace(/\/+$/,"");this.api=new m(e,s,t.apiKey),this.states=new p(e)}log(...t){this.options.debug&&console.debug("[ReplayKit]",...t)}start(){if(!N||!this.options.apiKey)return;let t=location.hostname;if(!this.options.allowLocalhost&&(t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost"))){this.log("localhost: idle (allowLocalhost to enable)");return}this.trackVisibility();let e=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()-e<It?this.env.setTimer(s,Ct):this.log("no tracker ids on this page: idle")};s()}boot(){let t=this.ids;this.baseVisibleMs=_nullishCoalesce(this.states.load(t.sid).visibleMs, () => (0)),this.queue=new v(this.env,this.api,()=>({...t,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:e=>this.onSignal(e),trigger:e=>this.trigger(e),input:(e,s)=>this.onInput(e,s),navigated:e=>this.onNavigate(e)}),this.collector.start(),this.listenPage(),this.callInit(1)}state(){return this.states.load(this.ids.sid)}async callInit(t){let e=this.ids,s=await this.api.init({sid:e.sid,vid:e.vid,url:u(location.href)});if(!this.destroyed){if(s.outcome==="ok"&&s.data)return this.applyInit(s.data);if(s.outcome==="retry"&&t<At){this.env.setTimer(()=>{this.callInit(t+1)},d(t));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(t){if(this.init=t,this.config=t.config,this.queue.release(t.signals),!t.signals&&!t.record){this.shutdown();return}this.decide()}consentValue(){let t=this.env.getLocal(J);return t==="1"?!0:t==="0"?!1:null}triggerEnabled(t){return t==="manual"||t==="sample"?!0:!!_optionalChain([this, 'access', _47 => _47.config, 'optionalAccess', _48 => _48.triggers, 'access', _49 => _49.includes, 'call', _50 => _50(t)])}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 t=this.state(),e=V({record:this.init.record,canGzip:!!this.env.gzip,state:t,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:",e.kind,e.kind==="start"?e.trigger:""),e.kind==="off"||e.kind==="wait_consent"){this.mode=e.kind;return}if(e.kind==="continue"){this.mode="live";let s=_nullishCoalesce(t.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=e.kind==="start"?e.trigger:this.earlyTrigger;this.earlyTrigger=null,s&&this.triggerEnabled(s)&&this.requestPromote(s)})}async restoreParkedBuffer(){let t=this.env.store;if(!t)return;let e=K(this.ids.sid),s=await t.get(e);if(!s)return;t.del(e),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 t=this.recorder=new k;!await t.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===t&&(this.log("rrweb failed to start"),this.recorder=null,this.mode="off")}onEvent(t){if(this.mode==="buffer"){this.buffer.push(t),t.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,t.timestamp)),this.uploader.add(t))}makeUploader(){this.uploader=new R(this.env,this.api,this.states,this.ids,{onStop:t=>this.stopRecording(t),beforeChunk:()=>this.saveStats()})}saveStats(){if(!this.stats||this.mode!=="live")return;let t=this.state();t.rid&&this.states.save({...t,stats:this.stats})}trigger(t){if(!(this.destroyed||!this.ids)){if(!this.init){this.earlyTrigger||(this.earlyTrigger=t);return}if(!(this.mode!=="buffer"||!this.triggerEnabled(t))){if(!this.recorder){_nullishCoalesce(this.earlyTrigger, () => ((this.earlyTrigger=t)));return}this.requestPromote(t)}}}trackVisibility(){document.visibilityState==="visible"&&(this.visibleSince=this.env.now());let t=()=>{let e=this.env.now();document.visibilityState==="hidden"?(this.visibleSince!==null&&(this.pageVisibleMs+=e-this.visibleSince),this.visibleSince=null):this.visibleSince===null&&(this.visibleSince=e,this.pending&&this.schedulePending())};document.addEventListener("visibilitychange",t),this.offWindow.push(()=>document.removeEventListener("visibilitychange",t))}visibleMs(){let t=this.visibleSince!==null?this.env.now()-this.visibleSince:0;return this.baseVisibleMs+this.pageVisibleMs+t}requestPromote(t){let e=M(t,this.visibleMs(),_nullishCoalesce(_optionalChain([this, 'access', _59 => _59.config, 'optionalAccess', _60 => _60.minDurationMs]), () => (0)));if(e===0){this.pending=null,this.promote(t);return}_nullishCoalesce(this.pending, () => ((this.pending=t))),this.log("waiting for the minimum duration:",t,e,"ms"),this.schedulePending()}schedulePending(){let t=this.pending;if(!t)return;let e=++this.pendingGen,s=M(t,this.visibleMs(),_nullishCoalesce(_optionalChain([this, 'access', _61 => _61.config, 'optionalAccess', _62 => _62.minDurationMs]), () => (0)));this.env.setTimer(()=>{e!==this.pendingGen||this.pending!==t||this.mode!=="buffer"||this.destroyed||this.visibleSince!==null&&this.requestPromote(t)},Math.max(s,50))}promote(t){let e=this.env.now(),s=this.buffer;this.buffer=[];let r=s.length?s[0].timestamp:e,n=E(r,u(location.href));n.endedAt=Math.max(s.length?s[s.length-1].timestamp:e,e),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:t,stats:n,stopped:void 0}),this.mode="live",this.log("recording:",t),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(t){this.log("recording stopped:",t),_optionalChain([this, 'access', _66 => _66.recorder, 'optionalAccess', _67 => _67.stop, 'call', _68 => _68()]),this.recorder=null,this.mode="off",this.buffer=[];let e=this.state();this.states.save({...e,stopped:t})}onSignal(t){if(this.mode==="live"&&this.stats)t.type==="rage_click"?this.stats.rageClicks++:t.type==="dead_click"?this.stats.deadClicks++:t.type==="error"&&this.stats.errors++;else if(this.mode==="buffer"||this.mode==="idle"){let e=t.type==="rage_click"?"rage":t.type==="dead_click"?"dead":t.type==="error"?"error":null;e&&this.pushRecent(e,t.ts)}_optionalChain([this, 'access', _69 => _69.queue, 'optionalAccess', _70 => _70.add, 'call', _71 => _71(t)])}onInput(t,e){this.mode==="live"&&this.stats?(this.stats.activeMs+=A(this.lastInputTs,e),t==="click"&&this.stats.clicks++):(this.mode==="buffer"||this.mode==="idle")&&this.pushRecent(t==="click"?"click":"input",e),this.lastInputTs=e}pushRecent(t,e){this.recent.push({k:t,ts:e}),this.recent.length>1e3&&this.recent.splice(0,this.recent.length-1e3)}onNavigate(t){if(!this.init||!this.config)return;this.mode==="live"&&this.stats&&this.stats.pages++;let e=this.pathExcluded();if(e&&(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(!e&&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(t)]),this.onCheckoutPath()&&this.trigger("checkout")}listenPage(){let t=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})}},e=()=>{document.visibilityState==="hidden"?t(!1):_optionalChain([this, 'access', _90 => _90.uploader, 'optionalAccess', _91 => _91.unpersist, 'call', _92 => _92()])},s=()=>t(!0);document.addEventListener("visibilitychange",e),window.addEventListener("pagehide",s),this.offWindow.push(()=>document.removeEventListener("visibilitychange",e),()=>window.removeEventListener("pagehide",s))}manualStart(t){if(this.ids){if(t&&this.log("manual trigger:",t),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(t){if(this.env.setLocal(J,t?"1":"0"),!!this.ids){if(t){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 t of this.offWindow)t();this.offWindow=[]}};var h=null;function de(i){h||(h=new T(i),h.start())}function pe(){_optionalChain([h, 'optionalAccess', _118 => _118.manualStart, 'call', _119 => _119()])}function fe(i){_optionalChain([h, 'optionalAccess', _120 => _120.manualStart, 'call', _121 => _121(i)])}function ge(){_optionalChain([h, 'optionalAccess', _122 => _122.manualStop, 'call', _123 => _123()])}function me(i){if(h)h.consent(i);else try{localStorage.setItem("hm_rk_consent",i?"1":"0")}catch (e22){}}function ve(){return _nullishCoalesce(_optionalChain([h, 'optionalAccess', _124 => _124.recordingId, 'call', _125 => _125()]), () => (null))}function ye(){_optionalChain([h, 'optionalAccess', _126 => _126.destroy, 'call', _127 => _127()]),h=null}exports.consent = me; exports.getRecordingId = ve; exports.init = de; exports.shutdown = ye; exports.start = pe; exports.stop = ge; exports.trigger = fe;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +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,CAA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G,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"]}
|
|
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,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,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 /** Identity of the clicked element (one key per DOM node), so a burst on one button counts even if the mouse drifts. */\n target: string;\n}\n\n/**\n * Rage click: RAGE_MIN_CLICKS clicks on the same element (or within RAGE_RADIUS_PX of the first)\n * inside RAGE_WINDOW_MS; once it is rage, the burst goes on while clicks keep coming less than\n * RAGE_WINDOW_MS apart. Only clicks on elements that promise something are fed (see signals-dom),\n * so selecting text with a triple click is not rage.\n */\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 /** Last click of the burst, so a burst too slow to become rage can slide forward. */\n last: ClickPoint;\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, of\n * `interrupt()`, or of `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 if (b.count >= RAGE_MIN_CLICKS || c.ts - b.first.ts <= RAGE_WINDOW_MS) {\n b.count++;\n b.lastTs = c.ts;\n b.last = c;\n return { trigger: b.count === RAGE_MIN_CLICKS, finished: null };\n }\n // Steady clicking slower than the window: restart from the previous click (2 clicks so far).\n this.burst = { first: b.last, count: 2, lastTs: c.ts, last: c };\n return { trigger: false, finished: null };\n }\n const finished = b && b.count >= RAGE_MIN_CLICKS ? b : null;\n this.burst = { first: c, count: 1, lastTs: c.ts, last: c };\n return { trigger: false, finished };\n }\n\n /** A click that cannot be rage (text, background, a field) ends the current burst. */\n interrupt(): RageBurst | null {\n const b = this.burst;\n this.burst = null;\n return b && b.count >= RAGE_MIN_CLICKS ? b : null;\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.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var q="hm_rk_state",p=class{constructor(e){this.env=e;this.cache=null}load(e){if(this.cache?.sid===e)return this.cache;let t=null;try{let s=this.env.getSession(q);s&&(t=JSON.parse(s))}catch{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{}}};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{}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{return null}}function B(i,e,t){try{t===null?i().removeItem(e):i().setItem(e,t)}catch{}}function Z(){if(typeof indexedDB>"u")return;let i=null,e=()=>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{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{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=n.data?.href;else if(n.type===5){let c=n.data;c?.tag===w&&(a=c.payload?.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{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 this.burst?.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!!this.env.sendBeacon?.(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{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{return{outcome:"retry"}}}catch{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=(i.innerText??i.textContent??"").replace(/\s+/g," ").trim();return t?t.slice(0,z):(i.getAttribute("aria-label")||i.getAttribute("title")||void 0)?.slice(0,z)}function ye(i){let e=!1;try{e=getComputedStyle(i).cursor==="pointer"}catch{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||t.error?.message||"")),e("unhandledrejection",t=>{let s=t.reason;this.onError(typeof s=="string"?s:s?.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{performance.getEntriesByType("navigation")[0]?.type==="back_forward"&&this.emit({type:"back_nav",detail:u(location.href)})}catch{}}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: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{return}setTimeout(()=>{if(l?.disconnect(),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 Re??(Re=import("@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{return!1}})}var k=class{constructor(){this.record=null;this.stopped=!1}async start(e){try{this.record=await Te()}catch{return!1}if(this.stopped)return!1;try{return this.stopFn=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{return!1}}snapshot(){try{this.record?.takeFullSnapshot(!0)}catch{}}page(e){try{this.record?.addCustomEvent(w,{href:e})}catch{}}stop(){this.stopped=!0;try{this.stopFn?.()}catch{}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(){this.hooks.beforeChunk?.();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"||!o.data?.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,this.env.store?.del(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=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:()=>this.config?.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"){this.queue?.release(!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:!!this.config?.triggers.includes(e)}pathExcluded(){return x(this.config?.excludePaths??[],location.pathname)}onCheckoutPath(){return this.triggerEnabled("checkout")&&x(this.config?.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=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:this.config?.blockSelectors??[],maskAllText:this.config?.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){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(),this.config?.minDurationMs??0);if(t===0){this.pending=null,this.promote(e);return}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(),this.config?.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||this.recorder?.snapshot(),this.uploader.flush()}stopRecording(e){this.log("recording stopped:",e),this.recorder?.stop(),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)}this.queue?.add(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")){this.recorder?.stop(),this.recorder=null,this.mode==="buffer"&&(this.buffer=[]),this.uploader?.flush(),this.mode="off";return}if(!t&&this.mode==="off"&&!this.state().stopped){this.uploader=null,this.decide();return}this.recorder?.page(e),this.onCheckoutPath()&&this.trigger("checkout")}listenPage(){let e=r=>{if(r&&this.collector?.pageHide(),this.states.save({...this.state(),visibleMs:this.visibleMs()}),this.queue?.beacon(),this.mode==="live")this.saveStats(),this.uploader?.persist();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):this.uploader?.unpersist()},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&&(this.recorder?.stop(),this.recorder=null,this.buffer=[],this.mode==="live"&&(this.saveStats(),this.uploader?.flush()),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}this.recorder?.stop(),this.recorder=null,this.buffer=[],this.uploader?.discard(),this.env.store?.del(K(this.ids.sid)),this.mode="off"}}recordingId(){return this.mode==="live"&&this.ids?this.state().rid??null:null}shutdown(){this.collector?.stop(),this.queue?.disable(),this.recorder?.stop(),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(){h?.manualStart()}function ft(i){h?.manualStart(i)}function gt(){h?.manualStop()}function mt(i){if(h)h.consent(i);else try{localStorage.setItem("hm_rk_consent",i?"1":"0")}catch{}}function vt(){return h?.recordingId()??null}function yt(){h?.destroy(),h=null}export{mt as consent,vt as getRecordingId,dt as init,yt as shutdown,pt as start,gt as stop,ft as trigger};
|
|
1
|
+
var q="hm_rk_state",p=class{constructor(t){this.env=t;this.cache=null}load(t){if(this.cache?.sid===t)return this.cache;let e=null;try{let s=this.env.getSession(q);s&&(e=JSON.parse(s))}catch{e=null}return(!e||e.sid!==t||typeof e.seq!="number")&&(e={sid:t,seq:0}),this.cache=e,e}save(t){this.cache=t;try{this.env.setSession(q,JSON.stringify(t))}catch{}}};function E(i,t){return{startedAt:i,endedAt:i,activeMs:0,clicks:0,rageClicks:0,deadClicks:0,errors:0,pages:1,entryUrl:t}}var N=typeof window<"u"&&typeof document<"u";function Q(){let i=globalThis.crypto;if(i&&typeof i.randomUUID=="function")try{return i.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function L(i,t){try{return i().getItem(t)}catch{return null}}function B(i,t,e){try{e===null?i().removeItem(t):i().setItem(t,e)}catch{}}function Z(){if(typeof indexedDB>"u")return;let i=null,t=()=>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)})),e=(s,r)=>t().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=>e("readonly",r=>r.get(s)),set:(s,r)=>e("readwrite",n=>{n.put(r,s)}).then(()=>{}),del:s=>e("readwrite",r=>{r.delete(s)}).then(()=>{})}}function tt(){if(!(typeof CompressionStream>"u"||typeof Blob>"u"||typeof Response>"u"))return i=>new Response(new Blob([i]).stream().pipeThrough(new CompressionStream("gzip"))).blob()}function F(){let i=typeof fetch=="function"?fetch.bind(globalThis):void 0,t=typeof navigator<"u"?navigator:void 0;return{now:()=>Date.now(),uuid:()=>Q(),fetch:i,sendBeacon:t&&typeof t.sendBeacon=="function"?(e,s)=>{try{return t.sendBeacon(e,new Blob([s],{type:"text/plain"}))}catch{return!1}}:void 0,getLocal:e=>L(()=>localStorage,e),setLocal:(e,s)=>B(()=>localStorage,e,s),getSession:e=>L(()=>sessionStorage,e),setSession:(e,s)=>B(()=>sessionStorage,e,s),getCookie:e=>{try{let s=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"=([^;]*)"));return s?decodeURIComponent(s[1]):null}catch{return null}},store:Z(),gzip:tt(),setTimer:(e,s)=>setTimeout(e,s),clearTimer:e=>clearTimeout(e)}}function O(i){let t=i.getCookie("hm_vid")||i.getLocal("hm_visitor_id")||void 0,e=i.getCookie("hm_sid")||i.getSession("hm_session_id")||void 0;return{visitorId:t,sessionId:e}}function et(i,t){let e=i.trim().toLowerCase();if(!e)return!1;let s=(t||"/").toLowerCase();if(!e.includes("*")){let n=e.endsWith("/")&&e.length>1?e.slice(0,-1):e;return s===n||s.startsWith(n.endsWith("/")?n:n+"/")}return new RegExp("^"+e.split("*").map(it).join(".*")+"$").test(s)}function x(i,t){for(let e of i)if(et(e,t))return!0;return!1}function it(i){return i.replace(/[.+?^${}()|[\]\\]/g,"\\$&")}function st(i){let t=3735928559,e=1103547991;for(let r=0;r<i.length;r++){let n=i.charCodeAt(r);t=Math.imul(t^n,2654435761),e=Math.imul(e^n,1597334677)}return t=Math.imul(t^t>>>16,2246822507)^Math.imul(e^e>>>13,3266489909),e=Math.imul(e^e>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),(4294967296*(2097151&e)+(t>>>0))/9007199254740992}function D(i,t){return t>0?t>=1?!0:st(i)<t:!1}function u(i){let t=i.search(/[?#]/);return t===-1?i:i.slice(0,t)}var w="replaykit:page";function U(i,t,e){let s=[],r=t;for(let n of i){let a;if(n.type===4)a=n.data?.href;else if(n.type===5){let c=n.data;c?.tag===w&&(a=c.payload?.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>=e))break}return s}var _=3e4,f=3e4;function rt(i,t){return t>0&&i[t-1].type===4?t-1:t}function C(i,t,e=_){let s=t-e,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=rt(i,r);return a===0?i:i.slice(a)}function I(i){try{return JSON.stringify(i).length}catch{return 0}}var g=class{constructor(){this.burst=null}onClick(t){let e=this.burst;if(e&&t.ts-e.lastTs<=1e3&&nt(e.first,t))return e.count>=3||t.ts-e.first.ts<=1e3?(e.count++,e.lastTs=t.ts,e.last=t,{trigger:e.count===3,finished:null}):(this.burst={first:e.last,count:2,lastTs:t.ts,last:t},{trigger:!1,finished:null});let s=e&&e.count>=3?e:null;return this.burst={first:t,count:1,lastTs:t.ts,last:t},{trigger:!1,finished:s}}interrupt(){let t=this.burst;return this.burst=null,t&&t.count>=3?t:null}flush(t){let e=this.burst;return!e||t-e.lastTs<=1e3?null:(this.burst=null,e.count>=3?e:null)}currentCount(){return this.burst?.count??0}};function nt(i,t){return i.target&&i.target===t.target?!0:Math.abs(i.x-t.x)<=30&&Math.abs(i.y-t.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 ot=5e3;function A(i,t){if(!i)return 0;let e=t-i;return e>0&&e<=ot?e:0}var at=["error","rage_click","manual"];function M(i,t,e){return e<=0||at.includes(i)?0:Math.max(0,e-t)}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 lt(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(t,e,s){this.env=t;this.apiUrl=e;this.apiKey=s}url(t){return`${this.apiUrl}/api/t/r/${t}?apiKey=${encodeURIComponent(this.apiKey)}`}init(t){return this.post("init",t,!0)}chunk(t){return this.post("chunk",t,!0)}signals(t){return this.post("signals",t,!1)}beaconSignals(t){return!!this.env.sendBeacon?.(this.url("signals"),JSON.stringify(t))}async put(t,e){if(!this.env.fetch)return"retry";try{let s=await this.env.fetch(t,{method:"PUT",body:e,headers:{"Content-Type":"application/gzip"}});return s.status>=200&&s.status<300?"ok":s.status===400||s.status===413?"drop":"retry"}catch{return"retry"}}async post(t,e,s){if(!this.env.fetch)return{outcome:"retry"};try{let r=await this.env.fetch(this.url(t),{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"text/plain"},keepalive:!1,credentials:"omit"}),n=lt(r.status);if(n!=="ok"||!s)return{outcome:n};try{return{outcome:n,data:await r.json()}}catch{return{outcome:"retry"}}}catch{return{outcome:"retry"}}}},ut=2e3,ht=6e4;function d(i){return Math.min(ht,ut*2**Math.max(0,i-1))}var ct=5e3,dt=200,pt=500,ft=2e3,v=class{constructor(t,e,s){this.env=t;this.api=e;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(t){if(this.disabled||this.sentThisPage+this.queue.length>=dt)return;let e=`${t.type}|${t.url}|${t.selector||""}|${t.detail||""}`,s=this.last.get(e);s!==void 0&&t.ts-s<ft||(this.last.set(e,t.ts),this.queue.push(t),this.queue.length>pt&&this.queue.shift(),!this.held&&(this.queue.length>=50?this.schedule(0):this.timer||this.schedule(ct)))}release(t){if(this.held=!1,!t){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(t){this.timer&&this.env.clearTimer(this.timer),this.timer=this.env.setTimer(()=>{this.timer=null,this.flush()},t)}async flush(){if(!(this.busy||this.held||this.disabled)){this.busy=!0;try{for(;this.queue.length&&!this.disabled;){let t=this.queue.slice(0,50),e=await this.api.signals({...this.ids(),signals:t});if(e.outcome==="ok"||e.outcome==="drop"||e.outcome==="quota"){this.queue.splice(0,t.length),this.sentThisPage+=t.length,this.failures=0;continue}if(e.outcome==="off"||e.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 t=this.queue.slice(0,50);if(!this.api.beaconSignals({...this.ids(),signals:t}))return;this.queue.splice(0,t.length),this.sentThisPage+=t.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]",mt=".hm-mask,[data-hm-mask],[data-hm-block],.hm-block",z=80,vt=200;function y(i){let t=[],e=i;for(let s=0;e&&s<3&&e.nodeType===1;s++){let r=e.tagName.toLowerCase();if(r==="html"||r==="body")break;if(e.id&&/^[A-Za-z][\w-]{0,40}$/.test(e.id)&&!/\d{3,}/.test(e.id)){t.unshift(`${r}#${e.id}`);break}let n=(typeof e.className=="string"?e.className:"").split(/\s+/).filter(a=>a&&a.length<30&&!/\d{3,}|^css-|^sc-|__/.test(a)).slice(0,2);t.unshift(r+n.map(a=>"."+a).join("")),e=e.parentElement}return t.join(" > ")}function X(i,t){if(t||i.closest(mt)||i.closest(j))return;let e=(i.innerText??i.textContent??"").replace(/\s+/g," ").trim();return e?e.slice(0,z):(i.getAttribute("aria-label")||i.getAttribute("title")||void 0)?.slice(0,z)}function yt(i){let t=!1;try{t=getComputedStyle(i).cursor==="pointer"}catch{t=!1}let e=typeof getSelection=="function"?getSelection():null;return{tag:i.tagName.toLowerCase(),insideInteractive:!!i.closest(Y),isFormField:!!i.closest(j),pointerCursor:t,hasSelection:!!e&&!e.isCollapsed&&e.toString().trim().length>0}}function bt(i){let t=i instanceof Element?i:i instanceof Node?i.parentElement:null;return t?t.closest(Y)||t:null}var b=class{constructor(t){this.h=t;this.rage=new g;this.rageEl=null;this.rageTimer=null;this.elKeys=new WeakMap;this.elSeq=0;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 t=(e,s,r=window)=>{let n={capture:!0,passive:!0};r.addEventListener(e,s,n),this.off.push(()=>r.removeEventListener(e,s,n))};t("click",e=>this.onClick(e)),t("keydown",()=>this.h.input("key",this.h.now())),t("scroll",()=>{let e=this.h.now();e-this.lastScrollInput>250&&(this.lastScrollInput=e,this.h.input("scroll",e))}),t("error",e=>this.onError(e.message||e.error?.message||"")),t("unhandledrejection",e=>{let s=e.reason;this.onError(typeof s=="string"?s:s?.message||"Unhandled promise rejection")}),t("popstate",()=>this.backNav()),t("input",e=>this.onField(e.target)),t("change",e=>this.onField(e.target)),t("submit",e=>{e.target instanceof HTMLFormElement&&this.forms.delete(e.target)}),t("pageshow",()=>{this.unloading=!1}),this.hrefTimer=setInterval(()=>this.checkHref(),1e3);try{performance.getEntriesByType("navigation")[0]?.type==="back_forward"&&this.emit({type:"back_nav",detail:u(location.href)})}catch{}}stop(){for(let t of this.off)t();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(t){this.h.signal({ts:t.ts??this.h.now(),url:u(location.href),...t})}checkHref(){let t=location.href;if(t===this.lastHref)return;let e=this.lastHref;this.lastHref=t,u(t)!==u(e)&&this.h.navigated(u(t))}onClick(t){let e=this.h.now();this.h.input("click",e);let s=bt(t.target);if(!s)return;if(!G(yt(s))){let a=this.rage.interrupt();a&&this.reportRage(a.count,a.first.ts);return}let r=y(s),n=this.rage.onClick({x:t.clientX,y:t.clientY,ts:e,target:this.keyOf(s)});n.finished&&this.reportRage(n.finished.count,n.finished.first.ts),n.trigger&&this.h.trigger("rage_click"),this.rage.currentCount()===1&&(this.rageEl=s),this.rageTimer&&clearTimeout(this.rageTimer),this.rageTimer=setTimeout(()=>this.flushRage(!1),1050),this.rage.currentCount()===1&&this.watchDeadClick(s,r,e)}keyOf(t){let e=this.elKeys.get(t);return e||this.elKeys.set(t,e=String(++this.elSeq)),e}flushRage(t){let e=this.rage.flush(t?Number.MAX_SAFE_INTEGER:this.h.now());e&&this.reportRage(e.count,e.first.ts)}reportRage(t,e){let s=this.rageEl;this.emit({type:"rage_click",ts:e,count:t,selector:s?y(s):void 0,text:s?X(s,this.h.maskAllText()):void 0})}watchDeadClick(t,e,s){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{return}setTimeout(()=>{if(l?.disconnect(),this.rage.currentCount()>1)return;W({mutations:o,urlChanged:location.href!==r,scrolled:`${scrollX},${scrollY}`!==n,focusChanged:document.activeElement!==a&&document.activeElement!==t,unloading:this.unloading})&&this.emit({type:"dead_click",ts:s,selector:e,text:X(t,this.h.maskAllText())})},H)}onError(t){let e=(t||"Error").slice(0,vt);this.errorsSeen.has(e)||(this.errorsSeen.add(e),this.emit({type:"error",detail:e}),this.h.trigger("error"))}backNav(){this.emit({type:"back_nav",detail:u(location.href)}),this.checkHref()}onField(t){if(!(t instanceof Element))return;let e=t.closest("form");if(!e)return;let s=t.getAttribute("name")||t.id||y(t),r=this.forms.get(e);r||this.forms.set(e,r=new Set),r.add(s)}flushForms(){for(let[t,e]of this.forms)!t.isConnected&&e.size===0||this.emit({type:"form_abandon",selector:y(t),count:e.size});this.forms.clear()}};var kt=["[data-hm-block]",".hm-block",'[autocomplete^="cc-"]','input[type="password"]'],St=".hm-mask,[data-hm-mask]",Rt=null;function Tt(){return Rt??(Rt=import("@rrweb/record").then(i=>i.record))}function Et(i){return i.filter(t=>{if(!t||typeof t!="string")return!1;try{return document.createDocumentFragment().querySelector(t),!0}catch{return!1}})}var k=class{constructor(){this.record=null;this.stopped=!1}async start(t){try{this.record=await Tt()}catch{return!1}if(this.stopped)return!1;try{return this.stopFn=this.record({emit:e=>t.emit(e),checkoutEveryNms:f,maskAllInputs:!0,maskInputOptions:{password:!0},maskTextSelector:t.maskAllText?"*":St,blockSelector:Et([...kt,...t.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{return!1}}snapshot(){try{this.record?.takeFullSnapshot(!0)}catch{}}page(t){try{this.record?.addCustomEvent(w,{href:t})}catch{}}stop(){this.stopped=!0;try{this.stopFn?.()}catch{}this.stopFn=void 0}};var xt=3e4,wt=256*1024,S=i=>`rk:pending:${i}`,R=class{constructor(t,e,s,r,n){this.env=t;this.api=e;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 t=this.env.store;if(!t)return;let e=await t.get(S(this.ids.sid));if(!e)return;await t.del(S(this.ids.sid));let s=this.state();!s.rid||e.rid!==s.rid||!Array.isArray(e.events)||e.events.length===0||(this.queue=e.events.concat(this.queue),this.queuedBytes+=e.events.reduce((r,n)=>r+I(n),0),this.schedule(0))}add(t){this.stopped||(this.queue.push(t),this.queuedBytes+=I(t),this.queuedBytes>=wt?this.schedule(0):this.timer||this.schedule(xt))}addMany(t){for(let e of t)this.add(e)}schedule(t){this.timer&&this.env.clearTimer(this.timer),this.timer=this.env.setTimer(()=>{this.timer=null,this.flush()},t)}async flush(){if(this.busy||this.stopped)return;let t=this.epoch;this.busy=!0;try{for(;!this.stopped&&t===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(){this.hooks.beforeChunk?.();let t=this.state();if(!t.rid||!t.trigger||!t.stats)return!1;if(t.seq>=600)return this.stop("limit"),!1;let e=this.env.gzip;if(!e)return this.stop("off"),!1;let s={v:1,rid:t.rid,seq:t.seq,events:this.inflight},r=await e(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===t.rid?this.lastPage:"",a=U(this.inflight,n,50),o=await this.api.chunk({rid:t.rid,sid:this.ids.sid,vid:this.ids.vid,seq:t.seq,bytes:r.size,trigger:t.trigger,stats:t.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"||!o.data?.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=t.rid);let c=this.state();return c.rid===t.rid&&this.states.save({...c,seq:t.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(t){this.stopped=!0,this.queue=[],this.inflight=[],this.queuedBytes=0,this.clearTimers(),this.hooks.onStop(t)}clearTimers(){this.timer&&this.env.clearTimer(this.timer),this.retryTimer&&this.env.clearTimer(this.retryTimer),this.timer=this.retryTimer=null}persist(){let t=this.env.store,e=this.state(),s=this.inflight.concat(this.queue);!t||!e.rid||s.length===0||this.stopped||(this.parked=!0,t.set(S(this.ids.sid),{rid:e.rid,events:s}))}unpersist(){this.parked&&(this.parked=!1,this.env.store?.del(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}`,Ct=500,It=15e3,At=3,T=class{constructor(t,e=F()){this.options=t;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=e;let s=(t.apiUrl||"https://app.himetrica.com").replace(/\/+$/,"");this.api=new m(e,s,t.apiKey),this.states=new p(e)}log(...t){this.options.debug&&console.debug("[ReplayKit]",...t)}start(){if(!N||!this.options.apiKey)return;let t=location.hostname;if(!this.options.allowLocalhost&&(t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t.endsWith(".localhost"))){this.log("localhost: idle (allowLocalhost to enable)");return}this.trackVisibility();let e=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()-e<It?this.env.setTimer(s,Ct):this.log("no tracker ids on this page: idle")};s()}boot(){let t=this.ids;this.baseVisibleMs=this.states.load(t.sid).visibleMs??0,this.queue=new v(this.env,this.api,()=>({...t,rid:this.mode==="live"?this.state().rid:void 0})),this.collector=new b({now:()=>this.env.now(),maskAllText:()=>this.config?.maskAllText??!0,signal:e=>this.onSignal(e),trigger:e=>this.trigger(e),input:(e,s)=>this.onInput(e,s),navigated:e=>this.onNavigate(e)}),this.collector.start(),this.listenPage(),this.callInit(1)}state(){return this.states.load(this.ids.sid)}async callInit(t){let e=this.ids,s=await this.api.init({sid:e.sid,vid:e.vid,url:u(location.href)});if(!this.destroyed){if(s.outcome==="ok"&&s.data)return this.applyInit(s.data);if(s.outcome==="retry"&&t<At){this.env.setTimer(()=>{this.callInit(t+1)},d(t));return}if(this.log("init refused:",s.outcome),s.outcome==="quota"){this.queue?.release(!0),this.mode="off";return}this.shutdown()}}applyInit(t){if(this.init=t,this.config=t.config,this.queue.release(t.signals),!t.signals&&!t.record){this.shutdown();return}this.decide()}consentValue(){let t=this.env.getLocal(J);return t==="1"?!0:t==="0"?!1:null}triggerEnabled(t){return t==="manual"||t==="sample"?!0:!!this.config?.triggers.includes(t)}pathExcluded(){return x(this.config?.excludePaths??[],location.pathname)}onCheckoutPath(){return this.triggerEnabled("checkout")&&x(this.config?.checkoutPaths??[],location.pathname)}decide(){if(!this.init||!this.config)return;let t=this.state(),e=V({record:this.init.record,canGzip:!!this.env.gzip,state:t,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:",e.kind,e.kind==="start"?e.trigger:""),e.kind==="off"||e.kind==="wait_consent"){this.mode=e.kind;return}if(e.kind==="continue"){this.mode="live";let s=t.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=e.kind==="start"?e.trigger:this.earlyTrigger;this.earlyTrigger=null,s&&this.triggerEnabled(s)&&this.requestPromote(s)})}async restoreParkedBuffer(){let t=this.env.store;if(!t)return;let e=K(this.ids.sid),s=await t.get(e);if(!s)return;t.del(e),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 t=this.recorder=new k;!await t.start({blockSelectors:this.config?.blockSelectors??[],maskAllText:this.config?.maskAllText??!1,emit:s=>this.onEvent(s)})&&this.recorder===t&&(this.log("rrweb failed to start"),this.recorder=null,this.mode="off")}onEvent(t){if(this.mode==="buffer"){this.buffer.push(t),t.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,t.timestamp)),this.uploader.add(t))}makeUploader(){this.uploader=new R(this.env,this.api,this.states,this.ids,{onStop:t=>this.stopRecording(t),beforeChunk:()=>this.saveStats()})}saveStats(){if(!this.stats||this.mode!=="live")return;let t=this.state();t.rid&&this.states.save({...t,stats:this.stats})}trigger(t){if(!(this.destroyed||!this.ids)){if(!this.init){this.earlyTrigger||(this.earlyTrigger=t);return}if(!(this.mode!=="buffer"||!this.triggerEnabled(t))){if(!this.recorder){this.earlyTrigger??(this.earlyTrigger=t);return}this.requestPromote(t)}}}trackVisibility(){document.visibilityState==="visible"&&(this.visibleSince=this.env.now());let t=()=>{let e=this.env.now();document.visibilityState==="hidden"?(this.visibleSince!==null&&(this.pageVisibleMs+=e-this.visibleSince),this.visibleSince=null):this.visibleSince===null&&(this.visibleSince=e,this.pending&&this.schedulePending())};document.addEventListener("visibilitychange",t),this.offWindow.push(()=>document.removeEventListener("visibilitychange",t))}visibleMs(){let t=this.visibleSince!==null?this.env.now()-this.visibleSince:0;return this.baseVisibleMs+this.pageVisibleMs+t}requestPromote(t){let e=M(t,this.visibleMs(),this.config?.minDurationMs??0);if(e===0){this.pending=null,this.promote(t);return}this.pending??(this.pending=t),this.log("waiting for the minimum duration:",t,e,"ms"),this.schedulePending()}schedulePending(){let t=this.pending;if(!t)return;let e=++this.pendingGen,s=M(t,this.visibleMs(),this.config?.minDurationMs??0);this.env.setTimer(()=>{e!==this.pendingGen||this.pending!==t||this.mode!=="buffer"||this.destroyed||this.visibleSince!==null&&this.requestPromote(t)},Math.max(s,50))}promote(t){let e=this.env.now(),s=this.buffer;this.buffer=[];let r=s.length?s[0].timestamp:e,n=E(r,u(location.href));n.endedAt=Math.max(s.length?s[s.length-1].timestamp:e,e),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:t,stats:n,stopped:void 0}),this.mode="live",this.log("recording:",t),this.makeUploader(),this.uploader.addMany(s),s.length||this.recorder?.snapshot(),this.uploader.flush()}stopRecording(t){this.log("recording stopped:",t),this.recorder?.stop(),this.recorder=null,this.mode="off",this.buffer=[];let e=this.state();this.states.save({...e,stopped:t})}onSignal(t){if(this.mode==="live"&&this.stats)t.type==="rage_click"?this.stats.rageClicks++:t.type==="dead_click"?this.stats.deadClicks++:t.type==="error"&&this.stats.errors++;else if(this.mode==="buffer"||this.mode==="idle"){let e=t.type==="rage_click"?"rage":t.type==="dead_click"?"dead":t.type==="error"?"error":null;e&&this.pushRecent(e,t.ts)}this.queue?.add(t)}onInput(t,e){this.mode==="live"&&this.stats?(this.stats.activeMs+=A(this.lastInputTs,e),t==="click"&&this.stats.clicks++):(this.mode==="buffer"||this.mode==="idle")&&this.pushRecent(t==="click"?"click":"input",e),this.lastInputTs=e}pushRecent(t,e){this.recent.push({k:t,ts:e}),this.recent.length>1e3&&this.recent.splice(0,this.recent.length-1e3)}onNavigate(t){if(!this.init||!this.config)return;this.mode==="live"&&this.stats&&this.stats.pages++;let e=this.pathExcluded();if(e&&(this.mode==="live"||this.mode==="buffer")){this.recorder?.stop(),this.recorder=null,this.mode==="buffer"&&(this.buffer=[]),this.uploader?.flush(),this.mode="off";return}if(!e&&this.mode==="off"&&!this.state().stopped){this.uploader=null,this.decide();return}this.recorder?.page(t),this.onCheckoutPath()&&this.trigger("checkout")}listenPage(){let t=r=>{if(r&&this.collector?.pageHide(),this.states.save({...this.state(),visibleMs:this.visibleMs()}),this.queue?.beacon(),this.mode==="live")this.saveStats(),this.uploader?.persist();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})}},e=()=>{document.visibilityState==="hidden"?t(!1):this.uploader?.unpersist()},s=()=>t(!0);document.addEventListener("visibilitychange",e),window.addEventListener("pagehide",s),this.offWindow.push(()=>document.removeEventListener("visibilitychange",e),()=>window.removeEventListener("pagehide",s))}manualStart(t){if(this.ids){if(t&&this.log("manual trigger:",t),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&&(this.recorder?.stop(),this.recorder=null,this.buffer=[],this.mode==="live"&&(this.saveStats(),this.uploader?.flush()),this.mode="off",this.states.save({...this.state(),stopped:"manual"}))}consent(t){if(this.env.setLocal(J,t?"1":"0"),!!this.ids){if(t){this.mode==="wait_consent"&&this.decide();return}this.recorder?.stop(),this.recorder=null,this.buffer=[],this.uploader?.discard(),this.env.store?.del(K(this.ids.sid)),this.mode="off"}}recordingId(){return this.mode==="live"&&this.ids?this.state().rid??null:null}shutdown(){this.collector?.stop(),this.queue?.disable(),this.recorder?.stop(),this.recorder=null,this.mode="off"}destroy(){this.destroyed=!0,this.shutdown();for(let t of this.offWindow)t();this.offWindow=[]}};var h=null;function de(i){h||(h=new T(i),h.start())}function pe(){h?.manualStart()}function fe(i){h?.manualStart(i)}function ge(){h?.manualStop()}function me(i){if(h)h.consent(i);else try{localStorage.setItem("hm_rk_consent",i?"1":"0")}catch{}}function ve(){return h?.recordingId()??null}function ye(){h?.destroy(),h=null}export{me as consent,ve as getRecordingId,de as init,ye as shutdown,pe as start,ge as stop,fe as trigger};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|